feat: add onEnvChanged

This commit is contained in:
pengfei.zhou 2021-07-07 12:44:40 +08:00 committed by osborn
parent 70bde4fba9
commit 0c10b513b9
13 changed files with 109 additions and 46 deletions

View File

@ -288,4 +288,8 @@ public class DoricContext {
} }
} }
} }
public void onEnvChanged() {
callEntity(DoricConstant.DORIC_ENTITY_ENV_CHANGE);
}
} }

View File

@ -27,6 +27,7 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import pub.doric.engine.DoricJSEngine;
import pub.doric.plugin.AnimatePlugin; import pub.doric.plugin.AnimatePlugin;
import pub.doric.plugin.CoordinatorPlugin; import pub.doric.plugin.CoordinatorPlugin;
import pub.doric.plugin.DoricJavaPlugin; import pub.doric.plugin.DoricJavaPlugin;
@ -72,8 +73,6 @@ public class DoricRegistry {
private static final Map<String, String> bundles = new ConcurrentHashMap<>(); private static final Map<String, String> bundles = new ConcurrentHashMap<>();
private static final Set<DoricLibrary> doricLibraries = new HashSet<>(); private static final Set<DoricLibrary> doricLibraries = new HashSet<>();
private static final List<WeakReference<DoricRegistry>> registries = new ArrayList<>(); private static final List<WeakReference<DoricRegistry>> registries = new ArrayList<>();
private final Map<String, Object> extendedEnvValues = new HashMap<>();
private final Map<String, DoricMetaInfo<DoricJavaPlugin>> pluginInfoMap = new HashMap<>(); private final Map<String, DoricMetaInfo<DoricJavaPlugin>> pluginInfoMap = new HashMap<>();
private final Map<String, DoricMetaInfo<ViewNode>> nodeInfoMap = new HashMap<>(); private final Map<String, DoricMetaInfo<ViewNode>> nodeInfoMap = new HashMap<>();
@ -99,7 +98,10 @@ public class DoricRegistry {
} }
} }
public DoricRegistry() { private final WeakReference<DoricJSEngine> doricJSEngineWeakReference;
public DoricRegistry(DoricJSEngine doricJSEngine) {
doricJSEngineWeakReference = new WeakReference<>(doricJSEngine);
this.registerNativePlugin(ShaderPlugin.class); this.registerNativePlugin(ShaderPlugin.class);
this.registerNativePlugin(ModalPlugin.class); this.registerNativePlugin(ModalPlugin.class);
this.registerNativePlugin(NetworkPlugin.class); this.registerNativePlugin(NetworkPlugin.class);
@ -168,11 +170,11 @@ public class DoricRegistry {
} }
public void setEnvironmentVariable(String key, Object val) { public void setEnvironmentVariable(String key, Object val) {
extendedEnvValues.put(key, val); DoricJSEngine doricJSEngine = doricJSEngineWeakReference.get();
} if (doricJSEngine == null) {
return;
public Map<String, Object> getEnvironmentVariables() { }
return extendedEnvValues; doricJSEngine.setEnvironmentVariable(key, val);
} }
public void registerMonitor(IDoricMonitor monitor) { public void registerMonitor(IDoricMonitor monitor) {

View File

@ -34,11 +34,12 @@ import com.github.pengfeizhou.jscore.JavaFunction;
import com.github.pengfeizhou.jscore.JavaValue; import com.github.pengfeizhou.jscore.JavaValue;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import pub.doric.Doric; import pub.doric.Doric;
import pub.doric.DoricContext; import pub.doric.DoricContext;
import pub.doric.DoricContextManager;
import pub.doric.DoricRegistry; import pub.doric.DoricRegistry;
import pub.doric.IDoricMonitor; import pub.doric.IDoricMonitor;
import pub.doric.extension.bridge.DoricBridgeExtension; import pub.doric.extension.bridge.DoricBridgeExtension;
@ -59,8 +60,9 @@ public class DoricJSEngine implements Handler.Callback, DoricTimerExtension.Time
private final DoricBridgeExtension mDoricBridgeExtension = new DoricBridgeExtension(); private final DoricBridgeExtension mDoricBridgeExtension = new DoricBridgeExtension();
protected IDoricJSE mDoricJSE; protected IDoricJSE mDoricJSE;
private final DoricTimerExtension mTimerExtension; private final DoricTimerExtension mTimerExtension;
private final DoricRegistry mDoricRegistry = new DoricRegistry(); private final DoricRegistry mDoricRegistry = new DoricRegistry(this);
private final JSONBuilder mEnvironment = new JSONBuilder(); private final Map<String, Object> mEnvironmentMap = new ConcurrentHashMap<>();
private boolean initialized = false;
public DoricJSEngine() { public DoricJSEngine() {
handlerThread = new HandlerThread(this.getClass().getSimpleName()); handlerThread = new HandlerThread(this.getClass().getSimpleName());
@ -73,6 +75,7 @@ public class DoricJSEngine implements Handler.Callback, DoricTimerExtension.Time
initJSEngine(); initJSEngine();
injectGlobal(); injectGlobal();
initDoricRuntime(); initDoricRuntime();
initialized = true;
} }
}); });
mTimerExtension = new DoricTimerExtension(looper, this); mTimerExtension = new DoricTimerExtension(looper, this);
@ -87,6 +90,26 @@ public class DoricJSEngine implements Handler.Callback, DoricTimerExtension.Time
mDoricJSE = new DoricNativeJSExecutor(); mDoricJSE = new DoricNativeJSExecutor();
} }
public void setEnvironmentVariable(String key, Object v) {
mEnvironmentMap.put(key, v);
if (initialized) {
final JSONBuilder jsonBuilder = new JSONBuilder();
for (String k : mEnvironmentMap.keySet()) {
jsonBuilder.put(k, mEnvironmentMap.get(k));
}
mJSHandler.post(new Runnable() {
@Override
public void run() {
mDoricJSE.injectGlobalJSObject(DoricConstant.INJECT_ENVIRONMENT,
new JavaValue(jsonBuilder.toJSONObject()));
}
});
for(DoricContext context:DoricContextManager.aliveContexts()){
context.onEnvChanged();
}
}
}
private void injectGlobal() { private void injectGlobal() {
String appName = ""; String appName = "";
String appVersion = ""; String appVersion = "";
@ -101,29 +124,26 @@ public class DoricJSEngine implements Handler.Callback, DoricTimerExtension.Time
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
mEnvironment mEnvironmentMap.put("platform", "Android");
.put("platform", "Android") mEnvironmentMap.put("platformVersion", String.valueOf(android.os.Build.VERSION.SDK_INT));
.put("platformVersion", String.valueOf(android.os.Build.VERSION.SDK_INT)) mEnvironmentMap.put("appName", appName);
.put("appName", appName) mEnvironmentMap.put("appVersion", appVersion);
.put("appVersion", appVersion) mEnvironmentMap.put("screenWidth", DoricUtils.px2dp(DoricUtils.getScreenWidth()));
.put("screenWidth", DoricUtils.px2dp(DoricUtils.getScreenWidth())) mEnvironmentMap.put("screenHeight", DoricUtils.px2dp(DoricUtils.getScreenHeight()));
.put("screenHeight", DoricUtils.px2dp(DoricUtils.getScreenHeight())) mEnvironmentMap.put("screenScale", DoricUtils.getScreenScale());
.put("screenScale", DoricUtils.getScreenScale()) mEnvironmentMap.put("statusBarHeight", DoricUtils.px2dp(DoricUtils.getStatusBarHeight()));
.put("statusBarHeight", DoricUtils.px2dp(DoricUtils.getStatusBarHeight())) mEnvironmentMap.put("hasNotch", false);
.put("hasNotch", false) mEnvironmentMap.put("deviceBrand", Build.BRAND);
.put("deviceBrand", Build.BRAND) mEnvironmentMap.put("deviceModel", Build.MODEL);
.put("deviceModel", Build.MODEL) mEnvironmentMap.put("localeLanguage", context.getResources().getConfiguration().locale.getLanguage());
.put("localeLanguage", context.getResources().getConfiguration().locale.getLanguage()) mEnvironmentMap.put("localeCountry", context.getResources().getConfiguration().locale.getCountry());
.put("localeCountry", context.getResources().getConfiguration().locale.getCountry());
Map<String, Object> extend = mDoricRegistry.getEnvironmentVariables(); JSONBuilder jsonBuilder = new JSONBuilder();
for (String key : extend.keySet()) { for (String key : mEnvironmentMap.keySet()) {
mEnvironment.put(key, extend.get(key)); jsonBuilder.put(key, mEnvironmentMap.get(key));
} }
mDoricJSE.injectGlobalJSObject(DoricConstant.INJECT_ENVIRONMENT, mDoricJSE.injectGlobalJSObject(DoricConstant.INJECT_ENVIRONMENT,
new JavaValue(mEnvironment.toJSONObject())); new JavaValue(jsonBuilder.toJSONObject()));
mDoricJSE.injectGlobalJSFunction(DoricConstant.INJECT_LOG, new JavaFunction() { mDoricJSE.injectGlobalJSFunction(DoricConstant.INJECT_LOG, new JavaFunction() {
@Override @Override
public JavaValue exec(JSDecoder[] args) { public JavaValue exec(JSDecoder[] args) {

View File

@ -73,4 +73,5 @@ public class DoricConstant {
public static final String DORIC_ENTITY_SHOW = "__onShow__"; public static final String DORIC_ENTITY_SHOW = "__onShow__";
public static final String DORIC_ENTITY_HIDDEN = "__onHidden__"; public static final String DORIC_ENTITY_HIDDEN = "__onHidden__";
public static final String DORIC_ENTITY_BUILD = "__build__"; public static final String DORIC_ENTITY_BUILD = "__build__";
public static final String DORIC_ENTITY_ENV_CHANGE = "__onEnvChanged__";
} }

View File

@ -63,6 +63,8 @@ NS_ASSUME_NONNULL_BEGIN
- (void)onHidden; - (void)onHidden;
-(void)onEnvChanged;
- (DoricViewNode *)targetViewNode:(NSString *)viewId; - (DoricViewNode *)targetViewNode:(NSString *)viewId;
- (void)dispatchToMainQueue:(_Nonnull dispatch_block_t)block; - (void)dispatchToMainQueue:(_Nonnull dispatch_block_t)block;

View File

@ -121,6 +121,10 @@ - (void)onHidden {
[self callEntity:DORIC_ENTITY_HIDDEN withArgumentsArray:@[]]; [self callEntity:DORIC_ENTITY_HIDDEN withArgumentsArray:@[]];
} }
- (void)onEnvChanged {
[self callEntity:DORIC_ENTITY_ENV_CHANGE withArgumentsArray:@[]];
}
- (UIViewController *)vc { - (UIViewController *)vc {
if (!_vc) { if (!_vc) {
return [UIApplication sharedApplication].keyWindow.rootViewController; return [UIApplication sharedApplication].keyWindow.rootViewController;

View File

@ -26,11 +26,14 @@
NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
@class DoricLibrary; @class DoricLibrary;
@class DoricJSEngine;
@interface DoricRegistry : NSObject <DoricMonitorProtocol> @interface DoricRegistry : NSObject <DoricMonitorProtocol>
@property(nonatomic, strong) UIImage *defaultPlaceHolderImage; @property(nonatomic, strong) UIImage *defaultPlaceHolderImage;
@property(nonatomic, strong) UIImage *defaultErrorImage; @property(nonatomic, strong) UIImage *defaultErrorImage;
- (instancetype)initWithJSEngine:(DoricJSEngine *)jsEngine;
- (NSString *)acquireJSBundle:(NSString *)name; - (NSString *)acquireJSBundle:(NSString *)name;
- (void)registerJSBundle:(NSString *)bundle withName:(NSString *)name; - (void)registerJSBundle:(NSString *)bundle withName:(NSString *)name;
@ -46,8 +49,6 @@ NS_ASSUME_NONNULL_BEGIN
- (void)setEnvironment:(NSString *)key variable:(id)value; - (void)setEnvironment:(NSString *)key variable:(id)value;
- (NSDictionary *)environmentVariables;
- (void)registerMonitor:(id <DoricMonitorProtocol>)monitor; - (void)registerMonitor:(id <DoricMonitorProtocol>)monitor;
+ (void)register:(DoricLibrary *)library; + (void)register:(DoricLibrary *)library;

View File

@ -48,12 +48,12 @@
#import "DoricLibrary.h" #import "DoricLibrary.h"
#import "DoricNotificationPlugin.h" #import "DoricNotificationPlugin.h"
#import "DoricStatusBarPlugin.h" #import "DoricStatusBarPlugin.h"
#import "DoricUtil.h"
#import "DoricCoordinatorPlugin.h" #import "DoricCoordinatorPlugin.h"
#import "DoricSwitchNode.h" #import "DoricSwitchNode.h"
#import "DoricNotchPlugin.h" #import "DoricNotchPlugin.h"
#import "DoricFlexNode.h" #import "DoricFlexNode.h"
#import "DoricKeyboardPlugin.h" #import "DoricKeyboardPlugin.h"
#import "DoricJSEngine.h"
@interface DoricLibraries : NSObject @interface DoricLibraries : NSObject
@property(nonatomic, strong) NSMutableSet <DoricLibrary *> *libraries; @property(nonatomic, strong) NSMutableSet <DoricLibrary *> *libraries;
@ -87,12 +87,19 @@ @interface DoricRegistry ()
@property(nonatomic, strong) NSMutableDictionary *bundles; @property(nonatomic, strong) NSMutableDictionary *bundles;
@property(nonatomic, strong) NSMutableDictionary *plugins; @property(nonatomic, strong) NSMutableDictionary *plugins;
@property(nonatomic, strong) NSMutableDictionary *nodes; @property(nonatomic, strong) NSMutableDictionary *nodes;
@property(nonatomic, strong) NSMutableDictionary <NSString *, id> *envVariables;
@property(nonatomic, strong) NSMutableSet <id <DoricMonitorProtocol>> *monitors; @property(nonatomic, strong) NSMutableSet <id <DoricMonitorProtocol>> *monitors;
@property(nonatomic, weak) DoricJSEngine *jsEngine;
@end @end
@implementation DoricRegistry @implementation DoricRegistry
- (instancetype)initWithJSEngine:(DoricJSEngine *)jsEngine {
if (self = [super init]) {
_jsEngine = jsEngine;
}
return self;
}
+ (void)register:(DoricLibrary *)library { + (void)register:(DoricLibrary *)library {
[DoricLibraries.instance.libraries addObject:library]; [DoricLibraries.instance.libraries addObject:library];
for (NSValue *value in DoricLibraries.instance.registries) { for (NSValue *value in DoricLibraries.instance.registries) {
@ -108,7 +115,6 @@ - (instancetype)init {
_bundles = [NSMutableDictionary new]; _bundles = [NSMutableDictionary new];
_plugins = [NSMutableDictionary new]; _plugins = [NSMutableDictionary new];
_nodes = [NSMutableDictionary new]; _nodes = [NSMutableDictionary new];
_envVariables = [NSMutableDictionary new];
[self innerRegister]; [self innerRegister];
_monitors = [NSMutableSet new]; _monitors = [NSMutableSet new];
[DoricLibraries.instance.libraries enumerateObjectsUsingBlock:^(DoricLibrary *obj, BOOL *stop) { [DoricLibraries.instance.libraries enumerateObjectsUsingBlock:^(DoricLibrary *obj, BOOL *stop) {
@ -180,11 +186,7 @@ - (Class)acquireViewNode:(NSString *)name {
} }
- (void)setEnvironment:(NSString *)key variable:(id)value { - (void)setEnvironment:(NSString *)key variable:(id)value {
self.envVariables[key] = value; [self.jsEngine setEnvironment:key variable:value];
}
- (NSDictionary *)environmentVariables {
return self.envVariables;
} }
- (void)registerMonitor:(id <DoricMonitorProtocol>)monitor { - (void)registerMonitor:(id <DoricMonitorProtocol>)monitor {

View File

@ -50,6 +50,8 @@ NS_ASSUME_NONNULL_BEGIN
- (void)initJSEngine; - (void)initJSEngine;
- (void)teardown; - (void)teardown;
- (void)setEnvironment:(NSString *)key variable:(id)value;
@end @end
NS_ASSUME_NONNULL_END NS_ASSUME_NONNULL_END

View File

@ -27,6 +27,7 @@
#import "DoricBridgeExtension.h" #import "DoricBridgeExtension.h"
#import <sys/utsname.h> #import <sys/utsname.h>
#import "DoricContext.h" #import "DoricContext.h"
#import "DoricContextManager.h"
@interface DoricDefaultMonitor : NSObject <DoricMonitorProtocol> @interface DoricDefaultMonitor : NSObject <DoricMonitorProtocol>
@end @end
@ -47,12 +48,14 @@ @interface DoricJSEngine ()
@property(nonatomic, strong) NSMutableDictionary *environmentDictionary; @property(nonatomic, strong) NSMutableDictionary *environmentDictionary;
@property(nonatomic, strong) NSThread *jsThread; @property(nonatomic, strong) NSThread *jsThread;
@property(nonatomic, assign) BOOL destroyed; @property(nonatomic, assign) BOOL destroyed;
@property(nonatomic, assign) BOOL initialized;
@end @end
@implementation DoricJSEngine @implementation DoricJSEngine
- (instancetype)init { - (instancetype)init {
if (self = [super init]) { if (self = [super init]) {
_initialized = NO;
_jsThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadRun) object:nil]; _jsThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadRun) object:nil];
[_jsThread start]; [_jsThread start];
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary]; NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
@ -88,7 +91,7 @@ - (instancetype)init {
@"localeLanguage": [[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode], @"localeLanguage": [[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode],
@"localeCountry": [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode], @"localeCountry": [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode],
}.mutableCopy; }.mutableCopy;
self.registry = [[DoricRegistry alloc] init]; self.registry = [[DoricRegistry alloc] initWithJSEngine:self];
[self ensureRunOnJSThread:^() { [self ensureRunOnJSThread:^() {
self.timers = [[NSMutableDictionary alloc] init]; self.timers = [[NSMutableDictionary alloc] init];
self.bridgeExtension = [DoricBridgeExtension new]; self.bridgeExtension = [DoricBridgeExtension new];
@ -96,12 +99,25 @@ - (instancetype)init {
[self initJSEngine]; [self initJSEngine];
[self initJSExecutor]; [self initJSExecutor];
[self initDoricEnvironment]; [self initDoricEnvironment];
self.initialized = YES;
}]; }];
[self.registry registerMonitor:[DoricDefaultMonitor new]]; [self.registry registerMonitor:[DoricDefaultMonitor new]];
} }
return self; return self;
} }
- (void)setEnvironment:(NSString *)key variable:(id)value {
[self ensureRunOnJSThread:^{
self.environmentDictionary[key] = value;
if (self.initialized) {
[self.jsExecutor injectGlobalJSObject:INJECT_ENVIRONMENT obj:[self.environmentDictionary copy]];
for (DoricContext *doricContext in DoricContextManager.instance.aliveContexts) {
[doricContext onEnvChanged];
}
}
}];
}
- (void)teardown { - (void)teardown {
_destroyed = YES; _destroyed = YES;
//To ensure runloop continue. //To ensure runloop continue.
@ -136,9 +152,6 @@ - (void)initJSEngine {
- (void)initJSExecutor { - (void)initJSExecutor {
__weak typeof(self) _self = self; __weak typeof(self) _self = self;
[self.registry.environmentVariables enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
self.environmentDictionary[key] = obj;
}];
[self.jsExecutor injectGlobalJSObject:INJECT_ENVIRONMENT obj:[self.environmentDictionary copy]]; [self.jsExecutor injectGlobalJSObject:INJECT_ENVIRONMENT obj:[self.environmentDictionary copy]];
[self.jsExecutor injectGlobalJSObject:INJECT_LOG obj:^(NSString *type, NSString *message) { [self.jsExecutor injectGlobalJSObject:INJECT_LOG obj:^(NSString *type, NSString *message) {
if ([type isEqualToString:@"e"]) { if ([type isEqualToString:@"e"]) {

View File

@ -67,3 +67,5 @@ extern NSString *const DORIC_ENTITY_SHOW;
extern NSString *const DORIC_ENTITY_HIDDEN; extern NSString *const DORIC_ENTITY_HIDDEN;
extern NSString *const DORIC_ENTITY_BUILD; extern NSString *const DORIC_ENTITY_BUILD;
extern NSString *const DORIC_ENTITY_ENV_CHANGE;

View File

@ -85,3 +85,5 @@
NSString *const DORIC_ENTITY_HIDDEN = @"__onHidden__"; NSString *const DORIC_ENTITY_HIDDEN = @"__onHidden__";
NSString *const DORIC_ENTITY_BUILD = @"__build__"; NSString *const DORIC_ENTITY_BUILD = @"__build__";
NSString *const DORIC_ENTITY_ENV_CHANGE = @"__onEnvChanged__";

View File

@ -39,7 +39,10 @@ export abstract class Panel {
onDestroy() { } onDestroy() { }
onShow() { } onShow() { }
onHidden() { } onHidden() { }
onEnvChanged() {
this.__root__.children.length = 0
this.build(this.__root__)
}
abstract build(rootView: Group): void abstract build(rootView: Group): void
private __data__?: object private __data__?: object
@ -126,6 +129,11 @@ export abstract class Panel {
this.build(this.__root__) this.build(this.__root__)
} }
@NativeCall
private __onEnvChanged__() {
this.onEnvChanged()
}
@NativeCall @NativeCall
private __response__(viewIds: string[], callbackId: string) { private __response__(viewIds: string[], callbackId: string) {
const v = this.retrospectView(viewIds) const v = this.retrospectView(viewIds)