public override CfrV8Value OnExtensionExecute(string nativeFunctionName, CfrV8Value[] arguments, CfrV8Value @this, ref string exception) { CfrV8Value retval = null; Console.WriteLine($"[FUNC]:{nativeFunctionName}"); switch (nativeFunctionName) { case nameof(Version): var accessor = new CfrV8Accessor(); var versionObject = CfrV8Value.CreateObject(accessor); versionObject.SetValue("nanui", CfrV8Value.CreateString(Version), CfxV8PropertyAttribute.DontDelete | CfxV8PropertyAttribute.ReadOnly); versionObject.SetValue("cef", CfrV8Value.CreateString(CefVersion), CfxV8PropertyAttribute.DontDelete | CfxV8PropertyAttribute.ReadOnly); versionObject.SetValue("chromium", CfrV8Value.CreateString(ChromiumVersion), CfxV8PropertyAttribute.DontDelete | CfxV8PropertyAttribute.ReadOnly); retval = versionObject; break; } return(retval); }
private void SaveDialog(CfrV8Value callback, string Filter) { var oThread = new Thread(() => { var basePath = AppDomain.CurrentDomain.BaseDirectory; var dialog = new SaveFileDialog { Filter = Filter }; if (dialog.ShowDialog() == DialogResult.OK) { originalName = dialog.FileName; retStr = dialog.FileName; } }); oThread.SetApartmentState(ApartmentState.STA); oThread.Start(); var isSafe = oThread.Join(new TimeSpan(2, 0, 0)); var callbackArgs = CfrV8Value.CreateObject(new CfrV8Accessor()); if (isSafe) { oThread.Abort(); } callbackArgs.SetValue("filename", CfrV8Value.CreateString(originalName), CfxV8PropertyAttribute.ReadOnly); callback.ExecuteFunction(null, new CfrV8Value[] { callbackArgs }); }
internal BindFunctionsTask(CfrBrowser remoteBrowser, string objName, string[] funcNames, CfrV8Handler v8Handler) { this.Execute += (s, e) => { var context = remoteBrowser.MainFrame.V8Context; context.Enter(); CfrV8Value obj = null; if (objName != null && objName != "" && !context.Global.HasValue(objName)) { obj = CfrV8Value.CreateObject(new CfrV8Accessor()); context.Global.SetValue(objName, obj, CfxV8PropertyAttribute.DontDelete | CfxV8PropertyAttribute.ReadOnly); //context.Global.DeleteValue(objName); } foreach (string name in funcNames) { // bind CfrV8Value func = CfrV8Value.CreateFunction(name, v8Handler); if (obj != null && !obj.HasValue(name)) { obj.SetValue(name, func, CfxV8PropertyAttribute.DontDelete | CfxV8PropertyAttribute.ReadOnly); } else if (!context.Global.HasValue(name)) { context.Global.SetValue(name, func, CfxV8PropertyAttribute.DontDelete | CfxV8PropertyAttribute.ReadOnly); } } context.Exit(); }; }
internal BindFunctionsTask(CfrBrowser remoteBrowser, string objName, string[] funcNames, CfrV8Handler v8Handler) { Execute += (s, e) => { var v8Context = remoteBrowser.MainFrame.V8Context; v8Context.Enter(); var cfrV8Value = (CfrV8Value)null; if (!string.IsNullOrEmpty(objName) && !v8Context.Global.HasValue(objName)) { cfrV8Value = CfrV8Value.CreateObject(new CfrV8Accessor()); v8Context.Global.SetValue(objName, cfrV8Value, CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete); } foreach (var funcName in funcNames) { var function = CfrV8Value.CreateFunction(funcName, v8Handler); if (cfrV8Value != null && !cfrV8Value.HasValue(funcName)) { cfrV8Value.SetValue(funcName, function, CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete); } else if (!v8Context.Global.HasValue(funcName)) { v8Context.Global.SetValue(funcName, function, CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete); } } v8Context.Exit(); }; }
public CfrV8Value GetHostWindowState() { var windowStateName = Container.WindowState.ToString().ToLower(); var windowStateCode = (int)Container.WindowState; var clientRect = new RECT(); User32.GetClientRect(ContainerHandle, ref clientRect); var retval = CfrV8Value.CreateObject(new CfrV8Accessor()); var windowState = CfrV8Value.CreateObject(new CfrV8Accessor()); windowState.SetValue("state", CfrV8Value.CreateString(windowStateName), CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete); windowState.SetValue("code", CfrV8Value.CreateInt(windowStateCode), CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete); retval.SetValue("windowState", windowState, CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete); retval.SetValue("clientWidth", CfrV8Value.CreateInt(clientRect.Width), CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete); retval.SetValue("clientHeight", CfrV8Value.CreateInt(clientRect.Height), CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete); retval.SetValue("width", CfrV8Value.CreateInt(Container.Width), CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete); retval.SetValue("height", CfrV8Value.CreateInt(Container.Height), CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete); return(retval); }
private void GetCalendar(object sender, CfrV8HandlerExecuteEventArgs e) { using (var context = new HotelContext()) { var year = e.Arguments[0].IntValue; var date_start = new DateTime(year, 1, 1); var date_end = new DateTime(year + 1, 1, 1).AddDays(-1); EventInputObject lastInput = null; var listOut = new List <EventInputObject>(); var calendar = context.RoomCalendars .Include("Kind") .Where(c => c.DateAt >= date_start) .Where(c => c.DateAt <= date_end) .OrderBy(c => c.DateAt) .ToList(); foreach (var item in calendar) { if (lastInput != null) { var dateNext = lastInput.end; var dateDiff = item.DateAt - dateNext; var title = lastInput.title; if (title == item.Kind.KindName && dateDiff.TotalDays == 1) { lastInput.end = item.DateAt; continue; } } lastInput = new EventInputObject { start = item.DateAt, end = item.DateAt, title = item.Kind.KindName, color = "#" + item.Kind.KindColor, }; listOut.Add(lastInput); } foreach (var input in listOut) { var diff = input.end - input.start; if (diff.TotalDays > 0) { input.end = input.end.AddDays(1); } } var callbackArgs = CfrV8Value.CreateObject(new CfrV8Accessor()); var callback = e.Arguments[1]; callbackArgs.SetValue("list", ConvertValue(listOut.ToArray()), CfxV8PropertyAttribute.ReadOnly); callback.ExecuteFunction(null, new CfrV8Value[] { callbackArgs }); } }
private void GetConfigFormCSFunc_Execute(object sender, CfrV8HandlerExecuteEventArgs e) { var config = JsonConvert.SerializeObject(CommonUtils.ConfigInstance); var jsObjectAccessor = new CfrV8Accessor(); var jsObject = CfrV8Value.CreateObject(jsObjectAccessor); jsObject.SetValue("config", config, CfxV8PropertyAttribute.DontDelete); e.SetReturnValue(jsObject); }
public void GetFlowPicSize(object func, CfrV8HandlerExecuteEventArgs args) { var jsObjectAccessor = new CfrV8Accessor(); var jsObject = CfrV8Value.CreateObject(jsObjectAccessor); jsObject.SetValue("width", CfrV8Value.CreateInt(GlobDef.sz_image.width), CfxV8PropertyAttribute.ReadOnly); jsObject.SetValue("height", CfrV8Value.CreateInt(GlobDef.sz_image.height), CfxV8PropertyAttribute.ReadOnly); args.SetReturnValue(jsObject); }
public IJavascriptObject CreateObject(bool iLocal) { var rawResult = CfrV8Value.CreateObject(null); if (iLocal) { return(UpdateConvert(rawResult)); } _CfrV8Context.Global.SetValue($"__ChromiumFX_Object_{_GlobalCount++}__", rawResult, CfxV8PropertyAttribute.DontDelete | CfxV8PropertyAttribute.ReadOnly); return(UpdateConvert(rawResult)); }
public CfrV8Value Serialize(HashSet <object> refin = null) { var propattr = CfxV8PropertyAttribute.DontDelete | CfxV8PropertyAttribute.ReadOnly; var referenced = refin; if (referenced != null && referenced.Contains(this)) { return(CfrV8Value.CreateNull()); } else if (referenced == null) { referenced = new HashSet <object>(); referenced.Add(this); } else { referenced.Add(this); } switch (Type) { case TokenType.Array: lock (Array) { var reslist = (from object obj in Array select obj.V8Serialize(referenced)).ToList(); var resa = CfrV8Value.CreateArray(reslist.Count); for (int i = 0; i < reslist.Count; i++) { resa.SetValue(i, reslist[i]); } return(resa); } case TokenType.Object: var reso = CfrV8Value.CreateObject(ClrV8ValueSerializer.Accessor); lock (Properties) { foreach (var prop in Properties.ToArray()) { var cobj = prop.Value.V8Serialize(referenced); reso.SetValue(prop.Key, cobj, propattr); } } return(reso); default: return(reso = CfrV8Value.CreateUndefined()); } }
private void GetNoteContentFormCSFunc_Execute(object sender, Chromium.Remote.Event.CfrV8HandlerExecuteEventArgs e) { var noteID = e.Arguments.FirstOrDefault(p => p.IsString).ToString(); var noteContent = noteUtils.GetNoteContent(Convert.ToInt32(noteID)); var jsObjectAccessor = new CfrV8Accessor(); var jsObject = CfrV8Value.CreateObject(jsObjectAccessor); if (noteContent == null) { return; } jsObject.SetValue("id", noteContent.id, CfxV8PropertyAttribute.DontDelete); jsObject.SetValue("n_content", noteContent.n_content, CfxV8PropertyAttribute.DontDelete); e.SetReturnValue(jsObject); }
protected void CallCallback(CfrV8Value callback, CfrV8Context v8Context, params KeyValuePair <string, object>[] par) { if (callback != null) { //get render process context var rc = callback.CreateRemoteCallContext(); //enter render process rc.Enter(); //create render task var task = new CfrTask(); task.Execute += (_, taskArgs) => { //enter saved context v8Context.Enter(); var callbackArgs = CfrV8Value.CreateObject(new CfrV8Accessor()); foreach (var val in par) { var validValue = ConvertValue(val.Value); callbackArgs.SetValue(val.Key, validValue, CfxV8PropertyAttribute.ReadOnly); } //execute callback callback.ExecuteFunction(null, new CfrV8Value[] { callbackArgs }); v8Context.Exit(); //lock task from gc lock (task) { Monitor.PulseAll(task); } }; lock (task) { //post task to render process v8Context.TaskRunner.PostTask(task); } rc.Exit(); GC.KeepAlive(task); } }
private void GetHistoryContentFormCSFunc_Execute(object sender, CfrV8HandlerExecuteEventArgs e) { var htime = e.Arguments.FirstOrDefault(p => p.IsString).ToString(); foreach (var item in noteContentHistoryList) { if (item != null && item.create_time.Equals(htime)) { var jsObjectAccessor = new CfrV8Accessor(); var jsObject = CfrV8Value.CreateObject(jsObjectAccessor); jsObject.SetValue("n_content", item.n_content, CfxV8PropertyAttribute.DontDelete); e.SetReturnValue(jsObject); break; } } }
internal override CfrV8Value CreateV8Value() { v8Accessor = new CfrV8Accessor(); v8Accessor.Get += v8Accessor_Get; v8Accessor.Set += v8Accessor_Set; var o = CfrV8Value.CreateObject(v8Accessor); foreach (var p in jsProperties) { if (p.Value.PropertyType == JSPropertyType.Dynamic) { o.SetValue(p.Key, CfxV8AccessControl.Default, CfxV8PropertyAttribute.DontDelete); } else { o.SetValue(p.Key, p.Value.GetV8Value(v8Context), CfxV8PropertyAttribute.DontDelete | CfxV8PropertyAttribute.ReadOnly); } } return(o); }
private void GetNoteContentHistoryFormCSFunc_Execute(object sender, CfrV8HandlerExecuteEventArgs e) { var noteID = e.Arguments.FirstOrDefault(p => p.IsString).ToString(); noteContentHistoryList = noteUtils.GetHistoryNoteContent(Convert.ToInt32(noteID)); if (noteContentHistoryList != null && noteContentHistoryList.Count > 0) { var jsObjectAccessor = new CfrV8Accessor(); var jsObject = CfrV8Value.CreateObject(jsObjectAccessor); var noteListArray = CfrV8Value.CreateArray(noteContentHistoryList.Count); int i = 0; foreach (var note in noteContentHistoryList) { noteListArray.SetValue(i, note.create_time); i++; } jsObject.SetValue("historyArray", noteListArray, CfxV8PropertyAttribute.DontDelete); e.SetReturnValue(jsObject); } }
private void Room_PropertyGet(object sender, CfrV8AccessorGetEventArgs e) { var total = 0; var used = 0; var C = CfrV8Value.CreateObject(new CfrV8Accessor()); using (var context = new HotelContext()) { try { total = context.Rooms.Count(); var roomAvail = context.Rooms.Where(p => p.RoomStateId == 1 || p.RoomStateId == 2).Count(); used = total - roomAvail; } catch { } } C.SetValue("Used", used, CfxV8PropertyAttribute.ReadOnly); C.SetValue("Total", total, CfxV8PropertyAttribute.ReadOnly); e.Retval = C; e.SetReturnValue(true); }
private void GetTitleFormCSFunc_Execute(object sender, Chromium.Remote.Event.CfrV8HandlerExecuteEventArgs e) { var noteList = noteUtils.GetNotesTitle(); var jsObjectAccessor = new CfrV8Accessor(); var jsObject = CfrV8Value.CreateObject(jsObjectAccessor); var noteListArray = CfrV8Value.CreateArray(noteList.Count); int i = 0; foreach (var note in noteList) { //jsObject.SetValue(note.id.ToString(), CfrV8Value.CreateString(note.n_title), CfxV8PropertyAttribute.ReadOnly); var jsArray = CfrV8Value.CreateArray(5); jsArray.SetValue("id", note.id, CfxV8PropertyAttribute.DontDelete); jsArray.SetValue("n_title", note.n_title, CfxV8PropertyAttribute.DontDelete); jsArray.SetValue("n_length", note.n_length, CfxV8PropertyAttribute.DontDelete); jsArray.SetValue("create_time", note.create_time, CfxV8PropertyAttribute.DontDelete); jsArray.SetValue("update_time", note.update_time, CfxV8PropertyAttribute.DontDelete); noteListArray.SetValue(i, jsArray); i++; } jsObject.SetValue("noteArray", noteListArray, CfxV8PropertyAttribute.DontDelete); e.SetReturnValue(jsObject); }
private void OpenDialog(CfrV8Value callback, string Filter) { var oThread = new Thread(() => { var basePath = AppDomain.CurrentDomain.BaseDirectory; var dialog = new OpenFileDialog { Filter = Filter }; if (dialog.ShowDialog() == DialogResult.OK) { var file = new FileInfo(dialog.FileName); var ext = file.Extension; var newName = Guid.NewGuid() + ext; var newPath = Path.Combine(basePath, @"Assets\upload\", newName); file.CopyTo(newPath); originalName = file.Name; retStr = newName; } }); oThread.SetApartmentState(ApartmentState.STA); oThread.Start(); var isSafe = oThread.Join(new TimeSpan(2, 0, 0)); var callbackArgs = CfrV8Value.CreateObject(new CfrV8Accessor()); if (isSafe) { oThread.Abort(); } callbackArgs.SetValue("hashname", CfrV8Value.CreateString(retStr), CfxV8PropertyAttribute.ReadOnly); callbackArgs.SetValue("filename", CfrV8Value.CreateString(originalName), CfxV8PropertyAttribute.ReadOnly); callback.ExecuteFunction(null, new CfrV8Value[] { callbackArgs }); }
public static CfrV8Value GetCfrObject(this JSObject _, object item) { var nameDict = new Dictionary <string, string>(); var accessor = new CfrV8Accessor(); var o = CfrV8Value.CreateObject(accessor); var t = item.GetType(); foreach (var p in t.GetProperties()) { var name = p.Name.Substring(0, 1).ToLower() + p.Name.Substring(1); nameDict[name] = p.Name; o.SetValue(name, CfxV8AccessControl.Default, CfxV8PropertyAttribute.DontDelete); } accessor.Get += (s, e) => { var name = nameDict[e.Name]; var p = t.GetProperty(name); var value = p.GetValue(item, null); var valueType = value?.GetType(); if (value == null) { e.Retval = CfrV8Value.CreateNull(); } else if (valueType == typeof(string) || valueType == typeof(Guid)) { e.Retval = CfrV8Value.CreateString((string)value); } else if (valueType == typeof(int) || valueType == typeof(short) || valueType == typeof(long)) { e.Retval = CfrV8Value.CreateInt((int)value); } else if (valueType == typeof(decimal)) { e.Retval = CfrV8Value.CreateDouble(Convert.ToDouble(value)); } else if (valueType == typeof(float) || valueType == typeof(double)) { e.Retval = CfrV8Value.CreateDouble(Convert.ToDouble(value)); } else if (valueType == typeof(bool)) { e.Retval = CfrV8Value.CreateBool(Convert.ToBoolean(value)); } else if (valueType == typeof(DateTime)) { e.Retval = CfrV8Value.CreateDate(CfrTime.FromUniversalTime((DateTime)value)); } else { e.Retval = CfrV8Value.CreateNull(); } e.SetReturnValue(true); }; return(o); }
public Form1() : base("http://res.app.local/www/index.html") { InitializeComponent(); LoadHandler.OnLoadEnd += LoadHandler_OnLoadEnd; //register the "my" object var myObject = GlobalObject.AddObject("my"); //add property "name" to my, you should implemnt the getter/setter of name property by using PropertyGet/PropertySet events. var nameProp = myObject.AddDynamicProperty("name"); nameProp.PropertyGet += (prop, args) => { // getter - if js code "my.name" executes, it'll get the string "NanUI". args.Retval = CfrV8Value.CreateString("NanUI"); args.SetReturnValue(true); }; nameProp.PropertySet += (prop, args) => { // setter's value from js context, here we do nothing, so it will store or igrone by your mind. var value = args.Value; args.SetReturnValue(true); }; //add a function showCSharpMessageBox var showMessageBoxFunc = myObject.AddFunction("showCSharpMessageBox"); showMessageBoxFunc.Execute += (func, args) => { //it will be raised by js code "my.showCSharpMessageBox(`some text`)" executed. //get the first string argument in Arguments, it pass by js function. var stringArgument = args.Arguments.FirstOrDefault(p => p.IsString); if (stringArgument != null) { MessageBox.Show(this, stringArgument.StringValue, "C# Messagebox", MessageBoxButtons.OK, MessageBoxIcon.Information); } }; //add a function getArrayFromCSharp, this function has an argument, it will combind C# string array with js array and return to js context. var friends = new string[] { "Mr.JSON", "Mr.Lee", "Mr.BONG" }; var getArrayFromCSFunc = myObject.AddFunction("getArrayFromCSharp"); getArrayFromCSFunc.Execute += (func, args) => { var jsArray = args.Arguments.FirstOrDefault(p => p.IsArray); if (jsArray == null) { jsArray = CfrV8Value.CreateArray(friends.Length); for (int i = 0; i < friends.Length; i++) { jsArray.SetValue(i, CfrV8Value.CreateString(friends[i])); } } else { var newArray = CfrV8Value.CreateArray(jsArray.ArrayLength + friends.Length); for (int i = 0; i < jsArray.ArrayLength; i++) { newArray.SetValue(i, jsArray.GetValue(i)); } var jsArrayLength = jsArray.ArrayLength; for (int i = 0; i < friends.Length; i++) { newArray.SetValue(i + jsArrayLength, CfrV8Value.CreateString(friends[i])); } jsArray = newArray; } //return the array to js context args.SetReturnValue(jsArray); //in js context, use code "my.getArrayFromCSharp()" will get an array like ["Mr.JSON", "Mr.Lee", "Mr.BONG"] }; //add a function getObjectFromCSharp, this function has no arguments, but it will return a Object to js context. var getObjectFormCSFunc = myObject.AddFunction("getObjectFromCSharp"); getObjectFormCSFunc.Execute += (func, args) => { //create the CfrV8Value object and the accssor of this Object. var jsObjectAccessor = new CfrV8Accessor(); var jsObject = CfrV8Value.CreateObject(jsObjectAccessor); //create a CfrV8Value array var jsArray = CfrV8Value.CreateArray(friends.Length); for (int i = 0; i < friends.Length; i++) { jsArray.SetValue(i, CfrV8Value.CreateString(friends[i])); } jsObject.SetValue("libName", CfrV8Value.CreateString("NanUI"), CfxV8PropertyAttribute.ReadOnly); jsObject.SetValue("friends", jsArray, CfxV8PropertyAttribute.DontDelete); args.SetReturnValue(jsObject); //in js context, use code "my.getObjectFromCSharp()" will get an object like { friends:["Mr.JSON", "Mr.Lee", "Mr.BONG"], libName:"NanUI" } }; //add a function with callback var callbackTestFunc = GlobalObject.AddFunction("callbackTest"); callbackTestFunc.Execute += (func, args) => { var callback = args.Arguments.FirstOrDefault(p => p.IsFunction); if (callback != null) { var callbackArgs = CfrV8Value.CreateObject(new CfrV8Accessor()); callbackArgs.SetValue("success", CfrV8Value.CreateBool(true), CfxV8PropertyAttribute.ReadOnly); callbackArgs.SetValue("text", CfrV8Value.CreateString("Message from C#"), CfxV8PropertyAttribute.ReadOnly); callback.ExecuteFunction(null, new CfrV8Value[] { callbackArgs }); } }; //add a function with async callback var asyncCallbackTestFunc = GlobalObject.AddFunction("asyncCallbackTest"); asyncCallbackTestFunc.Execute += async(func, args) => { //save current context var v8Context = CfrV8Context.GetCurrentContext(); var callback = args.Arguments.FirstOrDefault(p => p.IsFunction); //simulate async methods. await Task.Delay(5000); if (callback != null) { //get render process context var rc = callback.CreateRemoteCallContext(); //enter render process rc.Enter(); //create render task var task = new CfrTask(); task.Execute += (_, taskArgs) => { //enter saved context v8Context.Enter(); //create callback argument var callbackArgs = CfrV8Value.CreateObject(new CfrV8Accessor()); callbackArgs.SetValue("success", CfrV8Value.CreateBool(true), CfxV8PropertyAttribute.ReadOnly); callbackArgs.SetValue("text", CfrV8Value.CreateString("Message from C#"), CfxV8PropertyAttribute.ReadOnly); //execute callback callback.ExecuteFunction(null, new CfrV8Value[] { callbackArgs }); v8Context.Exit(); //lock task from gc lock (task) { Monitor.PulseAll(task); } }; lock (task) { //post task to render process v8Context.TaskRunner.PostTask(task); } rc.Exit(); GC.KeepAlive(task); } }; }
// 浏览器Javascript环境初始化完成 protected override void OnRegisterGlobalObject(JSObject global) { // 可以在此处将C#对象注入到当前窗口的JS上下文中 //add a function with callback function Console.Write(global); var callbackTestFunc = global.AddFunction("callbackTest"); callbackTestFunc.Execute += (func, args) => { var callback = args.Arguments.FirstOrDefault(p => p.IsFunction); if (callback != null) { WebBrowser.ExecuteJavascript("ChangeTitle()"); var callbackArgs = CfrV8Value.CreateObject(new CfrV8Accessor()); callbackArgs.SetValue("success", CfrV8Value.CreateBool(true), CfxV8PropertyAttribute.ReadOnly); callbackArgs.SetValue("text", CfrV8Value.CreateString("Message from Windows Client"), CfxV8PropertyAttribute.ReadOnly); callback.ExecuteFunction(null, new CfrV8Value[] { callbackArgs }); } }; //register the "my" object var myObject = global.AddObject("my"); //add property "name" to my, you should implemnt the getter/setter of name property by using PropertyGet/PropertySet events. var nameProp = myObject.AddDynamicProperty("name"); nameProp.PropertyGet += (prop, args) => { string computerName = Environment.MachineName; string value = $"My Computer Name is JoyNop :)\n{computerName}"; // getter - if js code "my.name" executes, it'll get the string "NanUI". args.Retval = CfrV8Value.CreateString(value); args.SetReturnValue(true); }; nameProp.PropertySet += (prop, args) => { // setter's value from js context, here we do nothing, so it will store or igrone by your mind. var value = args.Value; args.SetReturnValue(true); }; //add a function showCSharpMessageBox var showMessageBoxFunc = myObject.AddFunction("showCSharpMessageBox"); showMessageBoxFunc.Execute += (func, args) => { //it will be raised by js code "my.showCSharpMessageBox(`some text`)" executed. //get the first string argument in Arguments, it pass by js function. var stringArgument = args.Arguments.FirstOrDefault(p => p.IsString); if (stringArgument != null) { string osVersionName = Environment.OSVersion.ToString(); MessageBox.Show(osVersionName, "Windows 内核版本", MessageBoxButtons.OK, MessageBoxIcon.Information); } }; var friends = new string[] { "Mr.JSON", "Mr.Lee", "Mr.BONG" }; var getObjectFormCSFunc = myObject.AddFunction("getObjectFromCSharp"); getObjectFormCSFunc.Execute += (func, args) => { //create the CfrV8Value object and the accssor of this Object. var jsObjectAccessor = new CfrV8Accessor(); var jsObject = CfrV8Value.CreateObject(jsObjectAccessor); //create a CfrV8Value array var jsArray = CfrV8Value.CreateArray(friends.Length); for (int i = 0; i < friends.Length; i++) { jsArray.SetValue(i, CfrV8Value.CreateString(friends[i])); } jsObject.SetValue("libName", CfrV8Value.CreateString("NanUI"), CfxV8PropertyAttribute.ReadOnly); jsObject.SetValue("friends", jsArray, CfxV8PropertyAttribute.DontDelete); args.SetReturnValue(jsObject); //in js context, use code "my.getObjectFromCSharp()" will get an object like { friends:["Mr.JSON", "Mr.Lee", "Mr.BONG"], libName:"NanUI" } }; }
public CfrV8Value ConvertValue(object data) { if (data == null) { return(CfrV8Value.CreateNull()); } var typObject = data.GetType(); var retValue = CfrV8Value.CreateUndefined(); switch (typObject.Name) { case "Boolean": retValue = Convert.ToBoolean(data); break; case "ExpandoObject": IDictionary <string, object> keyValues = data as IDictionary <string, object>; var resultx = CfrV8Value.CreateObject(new CfrV8Accessor(), new CfrV8Interceptor()); foreach (var keypair in keyValues) { resultx.SetValue(keypair.Key, ConvertValue(keypair.Value), CfxV8PropertyAttribute.ReadOnly); } retValue = resultx; break; case "DBNull": retValue = CfrV8Value.CreateNull(); break; case "DateTime": var newValt = Convert.ToDateTime(data); var univerTime = newValt.ToUniversalTime(); retValue = CfrV8Value.CreateDate(CfrTime.FromUniversalTime(univerTime)); break; case "Decimal": case "Double": case "Single": retValue = Convert.ToDouble(data); break; case "Byte": case "UInt16": case "UInt32": case "UInt64": retValue = Convert.ToUInt64(data); break; case "SByte": case "Int16": case "Int32": case "Int64": retValue = Convert.ToInt64(data); break; case "String": retValue = (string)data; break; default: if (typObject.IsEnum) { retValue = Enum.GetName(typObject, data); } else if (typObject.IsArray) { var pos = 0; if (typObject.Name == "Byte[]") { var arr_byte = (byte[])data; var result = CfrV8Value.CreateArray(arr_byte.Length); foreach (var item in arr_byte) { result.SetValue(pos++, ConvertValue(item)); } retValue = result; } else { var arr = (object[])data; var result = CfrV8Value.CreateArray(arr.Length); foreach (var item in arr) { result.SetValue(pos++, ConvertValue(item)); } retValue = result; } } else if (typObject.Name.StartsWith("Dictionary")) { var dictionary = (IDictionary <string, object>)data; var result = CfrV8Value.CreateObject(new CfrV8Accessor(), new CfrV8Interceptor()); foreach (var keypair in dictionary) { result.SetValue(keypair.Key, ConvertValue(keypair.Value), CfxV8PropertyAttribute.ReadOnly); } retValue = result; } else if (typObject.IsClass) { var propertyInfoes = typObject.GetProperties(); var result = CfrV8Value.CreateObject(new CfrV8Accessor(), new CfrV8Interceptor()); foreach (var item in propertyInfoes) { result.SetValue(item.Name, ConvertValue(item.GetValue(data)), CfxV8PropertyAttribute.ReadOnly); } retValue = result; } break; } return(retValue); }
public IJavascriptObject CreateObject() { return(CfrV8Value.CreateObject(null, null).ConvertObject()); }
public static CfrV8Value V8Serialize(this object o, HashSet <object> refin = null) { if (Accessor == null) { Accessor = new CfrV8Accessor(); } var propattr = CfxV8PropertyAttribute.DontDelete | CfxV8PropertyAttribute.ReadOnly; switch (o) { case null: return(CfrV8Value.CreateNull()); case bool onb: return(CfrV8Value.CreateBool(onb)); case string os: return(CfrV8Value.CreateString(os)); case Enum oenum: return(CfrV8Value.CreateString(oenum.ToString())); case int oni: return(CfrV8Value.CreateInt(oni)); case sbyte oni: return(CfrV8Value.CreateInt(oni)); case short oni: return(CfrV8Value.CreateInt(oni)); case long oni: return(CfrV8Value.CreateInt((int)oni)); case uint onui: return(CfrV8Value.CreateUint(onui)); case byte onui: return(CfrV8Value.CreateUint(onui)); case ushort onui: return(CfrV8Value.CreateUint(onui)); case double ond: return(CfrV8Value.CreateDouble(ond)); case float onf: return(CfrV8Value.CreateDouble(onf)); case ObjectBuilder oob: return(oob.Serialize(refin)); case RGBAColor ocv: var vcolres = CfrV8Value.CreateObject(Accessor); vcolres.SetValue("r", CfrV8Value.CreateInt(ocv.Color.R), propattr); vcolres.SetValue("g", CfrV8Value.CreateInt(ocv.Color.G), propattr); vcolres.SetValue("b", CfrV8Value.CreateInt(ocv.Color.B), propattr); vcolres.SetValue("a", CfrV8Value.CreateDouble(ocv.A), propattr); vcolres.SetValue("name", CfrV8Value.CreateString("#" + ocv.Color.Name.Remove(0, 2)), propattr); return(vcolres); case Color4 ocdx: var dxcolres = CfrV8Value.CreateObject(Accessor); dxcolres.SetValue("r", CfrV8Value.CreateDouble(ocdx.Red * 255), propattr); dxcolres.SetValue("g", CfrV8Value.CreateDouble(ocdx.Green * 255), propattr); dxcolres.SetValue("b", CfrV8Value.CreateDouble(ocdx.Blue * 255), propattr); dxcolres.SetValue("a", CfrV8Value.CreateDouble(ocdx.Alpha), propattr); dxcolres.SetValue("name", CfrV8Value.CreateString(ocdx.ToString()), propattr); return(dxcolres); case TimeSpan ots: return(CfrV8Value.CreateDate(new CfrTime() { Year = 0, Month = 0, DayOfMonth = ots.Days, DayOfWeek = ots.Days, Hour = ots.Hours, Minute = ots.Minutes, Second = ots.Seconds, Millisecond = ots.Milliseconds })); case DateTime odt: return(CfrV8Value.CreateDate(new CfrTime() { Year = odt.Year, Month = odt.Month, DayOfMonth = odt.Day, DayOfWeek = (int)odt.DayOfWeek, Hour = odt.Hour, Minute = odt.Minute, Second = odt.Second, Millisecond = odt.Millisecond })); case IEnumerable oenum: lock (oenum) { var reslist = (from object obj in oenum select obj.V8Serialize()).ToList(); var res = CfrV8Value.CreateArray(reslist.Count); for (int i = 0; i < reslist.Count; i++) { res.SetValue(i, reslist[i]); } return(res); } default: var referenced = refin; if (referenced != null && referenced.Contains(o)) { return(CfrV8Value.CreateNull()); } else if (referenced == null) { referenced = new HashSet <object> { o }; } else { referenced.Add(o); } var oT = o.GetType(); if (oT.IsClass || (oT.IsValueType && !oT.IsPrimitive)) { var reso = CfrV8Value.CreateObject(Accessor); foreach (var prop in oT.GetProperties().Where(p => p.CanRead && p.GetMethod.IsPublic && !p.GetMethod.IsStatic && !p.PropertyType.IsPointer) ) { var cobj = prop.GetValue(o).V8Serialize(referenced); reso.SetValue(prop.Name, cobj, propattr); } foreach (var field in oT.GetFields().Where(f => f.IsPublic && !f.IsStatic && !f.FieldType.IsPointer) ) { var cobj = field.GetValue(o).V8Serialize(referenced); reso.SetValue(field.Name, cobj, propattr); } return(reso); } else { return(CfrV8Value.CreateNull()); } } }
private void FormV8Handler_Execute(object sender, Chromium.Remote.Event.CfrV8HandlerExecuteEventArgs e) { switch (e.Name) { case "Minimize": { HostForm.RequireUIThread(() => { if (HostForm.WindowState == FormWindowState.Minimized) { HostForm.WindowState = FormWindowState.Normal; } else { HostForm.WindowState = FormWindowState.Minimized; } }); } break; case "Maximize": { HostForm.RequireUIThread(() => { if (HostForm.WindowState == FormWindowState.Maximized) { HostForm.WindowState = FormWindowState.Normal; } else { HostForm.WindowState = FormWindowState.Maximized; } }); } break; case "Restore": { HostForm.RequireUIThread(() => { HostForm.WindowState = FormWindowState.Normal; }); } break; case "Close": { if (HostForm != null && !HostForm.IsDisposed) { HostForm.RequireUIThread(() => { HostForm.Close(); }); } } break; case "GetWinActivated": { if (HostForm != null && !HostForm.IsDisposed) { e.SetReturnValue(CfrV8Value.CreateBool(Form.ActiveForm == HostForm)); } } break; case "GetWinState": { if (HostForm != null && !HostForm.IsDisposed) { var obj = CfrV8Value.CreateObject(new CfrV8Accessor()); var stateString = "normal"; var currentState = 0; if (HostForm.WindowState == FormWindowState.Maximized) { currentState = 2; stateString = "maximized"; } else if (HostForm.WindowState == FormWindowState.Minimized) { currentState = 1; stateString = "minimized"; } obj.SetValue("state", CfrV8Value.CreateInt(currentState), Chromium.CfxV8PropertyAttribute.ReadOnly | Chromium.CfxV8PropertyAttribute.DontDelete); obj.SetValue("stateName", CfrV8Value.CreateString(stateString), Chromium.CfxV8PropertyAttribute.ReadOnly | Chromium.CfxV8PropertyAttribute.DontDelete); obj.SetValue("width", CfrV8Value.CreateInt(HostForm.ClientSize.Width), Chromium.CfxV8PropertyAttribute.ReadOnly | Chromium.CfxV8PropertyAttribute.DontDelete); obj.SetValue("height", CfrV8Value.CreateInt(HostForm.ClientSize.Height), Chromium.CfxV8PropertyAttribute.ReadOnly | Chromium.CfxV8PropertyAttribute.DontDelete); e.SetReturnValue(obj); } } break; } }
private void ExecuteCallback(CfrV8Value callback) { var callbackArgs = CfrV8Value.CreateObject(new CfrV8Accessor()); callback.ExecuteFunction(null, new CfrV8Value[] { callbackArgs }); }