├── .editorconfig ├── .gitignore ├── BrowserHost.Common ├── BrowserHost.Common.csproj ├── JSONParser.cs ├── JSONWriter.cs ├── Properties │ └── AssemblyInfo.cs └── RenderProcess.cs ├── BrowserHost.Plugin ├── BrowserHost.Plugin.csproj ├── BrowserHost.Plugin.json ├── Configuration.cs ├── DependencyManager.cs ├── DxHandler.cs ├── Inlay.cs ├── IpcBuffer.cs ├── NativeMethods.cs ├── Plugin.cs ├── Properties │ └── AssemblyInfo.cs ├── RenderProcess.cs ├── Settings.cs ├── TextureHandlers │ ├── BitmapBufferTextureHandler.cs │ ├── ITextureHandler.cs │ └── SharedTextureHandler.cs ├── WndProcHandler.cs └── images │ ├── icon.png │ └── image1.png ├── BrowserHost.Renderer ├── App.config ├── BrowserHost.Renderer.csproj ├── CefHandler.cs ├── DxHandler.cs ├── Inlay.cs ├── IpcBuffer.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── RenderHandlers │ ├── BaseRenderHandler.cs │ ├── BitmapBufferRenderHandler.cs │ └── TextureRenderHandler.cs ├── cef │ └── VERSION └── packages.config ├── BrowserHost.sln ├── COPYING ├── COPYING.LESSER └── README.md /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | trim_trailing_whitespace = true 7 | indent_style = tab 8 | indent_size=2 9 | tab_width=2 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vs/ 2 | bin/ 3 | obj/ 4 | packages/ 5 | -------------------------------------------------------------------------------- /BrowserHost.Common/BrowserHost.Common.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {9EC3F19A-CEA0-44BD-B55C-FECF7D02CC6B} 8 | Library 9 | Properties 10 | BrowserHost.Common 11 | BrowserHost.Common 12 | v4.8 13 | 8.0 14 | 512 15 | true 16 | PackageReference 17 | 18 | 19 | true 20 | ..\bin\Debug\plugin\ 21 | DEBUG;TRACE 22 | full 23 | x64 24 | 8.0 25 | prompt 26 | MinimumRecommendedRules.ruleset 27 | 28 | 29 | ..\bin\Release\plugin\ 30 | TRACE 31 | true 32 | none 33 | x64 34 | 8.0 35 | prompt 36 | MinimumRecommendedRules.ruleset 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /BrowserHost.Common/JSONParser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Reflection; 5 | using System.Runtime.Serialization; 6 | using System.Text; 7 | 8 | namespace TinyJson 9 | { 10 | // Really simple JSON parser in ~300 lines 11 | // - Attempts to parse JSON files with minimal GC allocation 12 | // - Nice and simple "[1,2,3]".FromJson>() API 13 | // - Classes and structs can be parsed too! 14 | // class Foo { public int Value; } 15 | // "{\"Value\":10}".FromJson() 16 | // - Can parse JSON without type information into Dictionary and List e.g. 17 | // "[1,2,3]".FromJson().GetType() == typeof(List) 18 | // "{\"Value\":10}".FromJson().GetType() == typeof(Dictionary) 19 | // - No JIT Emit support to support AOT compilation on iOS 20 | // - Attempts are made to NOT throw an exception if the JSON is corrupted or invalid: returns null instead. 21 | // - Only public fields and property setters on classes/structs will be written to 22 | // 23 | // Limitations: 24 | // - No JIT Emit support to parse structures quickly 25 | // - Limited to parsing <2GB JSON files (due to int.MaxValue) 26 | // - Parsing of abstract classes or interfaces is NOT supported and will throw an exception. 27 | internal static class JSONParser 28 | { 29 | [ThreadStatic] static Stack> splitArrayPool; 30 | [ThreadStatic] static StringBuilder stringBuilder; 31 | [ThreadStatic] static Dictionary> fieldInfoCache; 32 | [ThreadStatic] static Dictionary> propertyInfoCache; 33 | 34 | public static T FromJson(string json) 35 | { 36 | // Initialize, if needed, the ThreadStatic variables 37 | if (propertyInfoCache == null) propertyInfoCache = new Dictionary>(); 38 | if (fieldInfoCache == null) fieldInfoCache = new Dictionary>(); 39 | if (stringBuilder == null) stringBuilder = new StringBuilder(); 40 | if (splitArrayPool == null) splitArrayPool = new Stack>(); 41 | 42 | //Remove all whitespace not within strings to make parsing simpler 43 | stringBuilder.Length = 0; 44 | for (int i = 0; i < json.Length; i++) 45 | { 46 | char c = json[i]; 47 | if (c == '"') 48 | { 49 | i = AppendUntilStringEnd(true, i, json); 50 | continue; 51 | } 52 | if (char.IsWhiteSpace(c)) 53 | continue; 54 | 55 | stringBuilder.Append(c); 56 | } 57 | 58 | //Parse the thing! 59 | return (T)ParseValue(typeof(T), stringBuilder.ToString()); 60 | } 61 | 62 | static int AppendUntilStringEnd(bool appendEscapeCharacter, int startIdx, string json) 63 | { 64 | stringBuilder.Append(json[startIdx]); 65 | for (int i = startIdx + 1; i < json.Length; i++) 66 | { 67 | if (json[i] == '\\') 68 | { 69 | if (appendEscapeCharacter) 70 | stringBuilder.Append(json[i]); 71 | stringBuilder.Append(json[i + 1]); 72 | i++;//Skip next character as it is escaped 73 | } 74 | else if (json[i] == '"') 75 | { 76 | stringBuilder.Append(json[i]); 77 | return i; 78 | } 79 | else 80 | stringBuilder.Append(json[i]); 81 | } 82 | return json.Length - 1; 83 | } 84 | 85 | //Splits { :, : } and [ , ] into a list of strings 86 | static List Split(string json) 87 | { 88 | List splitArray = splitArrayPool.Count > 0 ? splitArrayPool.Pop() : new List(); 89 | splitArray.Clear(); 90 | if (json.Length == 2) 91 | return splitArray; 92 | int parseDepth = 0; 93 | stringBuilder.Length = 0; 94 | for (int i = 1; i < json.Length - 1; i++) 95 | { 96 | switch (json[i]) 97 | { 98 | case '[': 99 | case '{': 100 | parseDepth++; 101 | break; 102 | case ']': 103 | case '}': 104 | parseDepth--; 105 | break; 106 | case '"': 107 | i = AppendUntilStringEnd(true, i, json); 108 | continue; 109 | case ',': 110 | case ':': 111 | if (parseDepth == 0) 112 | { 113 | splitArray.Add(stringBuilder.ToString()); 114 | stringBuilder.Length = 0; 115 | continue; 116 | } 117 | break; 118 | } 119 | 120 | stringBuilder.Append(json[i]); 121 | } 122 | 123 | splitArray.Add(stringBuilder.ToString()); 124 | 125 | return splitArray; 126 | } 127 | 128 | internal static object ParseValue(Type type, string json) 129 | { 130 | if (type == typeof(string)) 131 | { 132 | if (json.Length <= 2) 133 | return string.Empty; 134 | StringBuilder parseStringBuilder = new StringBuilder(json.Length); 135 | for (int i = 1; i < json.Length - 1; ++i) 136 | { 137 | if (json[i] == '\\' && i + 1 < json.Length - 1) 138 | { 139 | int j = "\"\\nrtbf/".IndexOf(json[i + 1]); 140 | if (j >= 0) 141 | { 142 | parseStringBuilder.Append("\"\\\n\r\t\b\f/"[j]); 143 | ++i; 144 | continue; 145 | } 146 | if (json[i + 1] == 'u' && i + 5 < json.Length - 1) 147 | { 148 | UInt32 c = 0; 149 | if (UInt32.TryParse(json.Substring(i + 2, 4), System.Globalization.NumberStyles.AllowHexSpecifier, null, out c)) 150 | { 151 | parseStringBuilder.Append((char)c); 152 | i += 5; 153 | continue; 154 | } 155 | } 156 | } 157 | parseStringBuilder.Append(json[i]); 158 | } 159 | return parseStringBuilder.ToString(); 160 | } 161 | if (type.IsPrimitive) 162 | { 163 | var result = Convert.ChangeType(json, type, System.Globalization.CultureInfo.InvariantCulture); 164 | return result; 165 | } 166 | if (type == typeof(decimal)) 167 | { 168 | decimal result; 169 | decimal.TryParse(json, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out result); 170 | return result; 171 | } 172 | if (json == "null") 173 | { 174 | return null; 175 | } 176 | if (type.IsEnum) 177 | { 178 | if (json[0] == '"') 179 | json = json.Substring(1, json.Length - 2); 180 | try 181 | { 182 | return Enum.Parse(type, json, false); 183 | } 184 | catch 185 | { 186 | return 0; 187 | } 188 | } 189 | if (type.IsArray) 190 | { 191 | Type arrayType = type.GetElementType(); 192 | if (json[0] != '[' || json[json.Length - 1] != ']') 193 | return null; 194 | 195 | List elems = Split(json); 196 | Array newArray = Array.CreateInstance(arrayType, elems.Count); 197 | for (int i = 0; i < elems.Count; i++) 198 | newArray.SetValue(ParseValue(arrayType, elems[i]), i); 199 | splitArrayPool.Push(elems); 200 | return newArray; 201 | } 202 | if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) 203 | { 204 | Type listType = type.GetGenericArguments()[0]; 205 | if (json[0] != '[' || json[json.Length - 1] != ']') 206 | return null; 207 | 208 | List elems = Split(json); 209 | var list = (IList)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count }); 210 | for (int i = 0; i < elems.Count; i++) 211 | list.Add(ParseValue(listType, elems[i])); 212 | splitArrayPool.Push(elems); 213 | return list; 214 | } 215 | if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) 216 | { 217 | Type keyType, valueType; 218 | { 219 | Type[] args = type.GetGenericArguments(); 220 | keyType = args[0]; 221 | valueType = args[1]; 222 | } 223 | 224 | //Refuse to parse dictionary keys that aren't of type string 225 | if (keyType != typeof(string)) 226 | return null; 227 | //Must be a valid dictionary element 228 | if (json[0] != '{' || json[json.Length - 1] != '}') 229 | return null; 230 | //The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON 231 | List elems = Split(json); 232 | if (elems.Count % 2 != 0) 233 | return null; 234 | 235 | var dictionary = (IDictionary)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count / 2 }); 236 | for (int i = 0; i < elems.Count; i += 2) 237 | { 238 | if (elems[i].Length <= 2) 239 | continue; 240 | string keyValue = elems[i].Substring(1, elems[i].Length - 2); 241 | object val = ParseValue(valueType, elems[i + 1]); 242 | dictionary.Add(keyValue, val); 243 | } 244 | return dictionary; 245 | } 246 | if (type == typeof(object)) 247 | { 248 | return ParseAnonymousValue(json); 249 | } 250 | if (json[0] == '{' && json[json.Length - 1] == '}') 251 | { 252 | return ParseObject(type, json); 253 | } 254 | 255 | return null; 256 | } 257 | 258 | static object ParseAnonymousValue(string json) 259 | { 260 | if (json.Length == 0) 261 | return null; 262 | if (json[0] == '{' && json[json.Length - 1] == '}') 263 | { 264 | List elems = Split(json); 265 | if (elems.Count % 2 != 0) 266 | return null; 267 | var dict = new Dictionary(elems.Count / 2); 268 | for (int i = 0; i < elems.Count; i += 2) 269 | dict.Add(elems[i].Substring(1, elems[i].Length - 2), ParseAnonymousValue(elems[i + 1])); 270 | return dict; 271 | } 272 | if (json[0] == '[' && json[json.Length - 1] == ']') 273 | { 274 | List items = Split(json); 275 | var finalList = new List(items.Count); 276 | for (int i = 0; i < items.Count; i++) 277 | finalList.Add(ParseAnonymousValue(items[i])); 278 | return finalList; 279 | } 280 | if (json[0] == '"' && json[json.Length - 1] == '"') 281 | { 282 | string str = json.Substring(1, json.Length - 2); 283 | return str.Replace("\\", string.Empty); 284 | } 285 | if (char.IsDigit(json[0]) || json[0] == '-') 286 | { 287 | if (json.Contains(".")) 288 | { 289 | double result; 290 | double.TryParse(json, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out result); 291 | return result; 292 | } 293 | else 294 | { 295 | int result; 296 | int.TryParse(json, out result); 297 | return result; 298 | } 299 | } 300 | if (json == "true") 301 | return true; 302 | if (json == "false") 303 | return false; 304 | // handles json == "null" as well as invalid JSON 305 | return null; 306 | } 307 | 308 | static Dictionary CreateMemberNameDictionary(T[] members) where T : MemberInfo 309 | { 310 | Dictionary nameToMember = new Dictionary(StringComparer.OrdinalIgnoreCase); 311 | for (int i = 0; i < members.Length; i++) 312 | { 313 | T member = members[i]; 314 | if (member.IsDefined(typeof(IgnoreDataMemberAttribute), true)) 315 | continue; 316 | 317 | string name = member.Name; 318 | if (member.IsDefined(typeof(DataMemberAttribute), true)) 319 | { 320 | DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)Attribute.GetCustomAttribute(member, typeof(DataMemberAttribute), true); 321 | if (!string.IsNullOrEmpty(dataMemberAttribute.Name)) 322 | name = dataMemberAttribute.Name; 323 | } 324 | 325 | nameToMember.Add(name, member); 326 | } 327 | 328 | return nameToMember; 329 | } 330 | 331 | static object ParseObject(Type type, string json) 332 | { 333 | object instance = FormatterServices.GetUninitializedObject(type); 334 | 335 | //The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON 336 | List elems = Split(json); 337 | if (elems.Count % 2 != 0) 338 | return instance; 339 | 340 | Dictionary nameToField; 341 | Dictionary nameToProperty; 342 | if (!fieldInfoCache.TryGetValue(type, out nameToField)) 343 | { 344 | nameToField = CreateMemberNameDictionary(type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy)); 345 | fieldInfoCache.Add(type, nameToField); 346 | } 347 | if (!propertyInfoCache.TryGetValue(type, out nameToProperty)) 348 | { 349 | nameToProperty = CreateMemberNameDictionary(type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy)); 350 | propertyInfoCache.Add(type, nameToProperty); 351 | } 352 | 353 | for (int i = 0; i < elems.Count; i += 2) 354 | { 355 | if (elems[i].Length <= 2) 356 | continue; 357 | string key = elems[i].Substring(1, elems[i].Length - 2); 358 | string value = elems[i + 1]; 359 | 360 | FieldInfo fieldInfo; 361 | PropertyInfo propertyInfo; 362 | if (nameToField.TryGetValue(key, out fieldInfo)) 363 | fieldInfo.SetValue(instance, ParseValue(fieldInfo.FieldType, value)); 364 | else if (nameToProperty.TryGetValue(key, out propertyInfo)) 365 | propertyInfo.SetValue(instance, ParseValue(propertyInfo.PropertyType, value), null); 366 | } 367 | 368 | return instance; 369 | } 370 | } 371 | } 372 | -------------------------------------------------------------------------------- /BrowserHost.Common/JSONWriter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Reflection; 5 | using System.Runtime.Serialization; 6 | using System.Text; 7 | 8 | namespace TinyJson 9 | { 10 | //Really simple JSON writer 11 | //- Outputs JSON structures from an object 12 | //- Really simple API (new List { 1, 2, 3 }).ToJson() == "[1,2,3]" 13 | //- Will only output public fields and property getters on objects 14 | internal static class JSONWriter 15 | { 16 | public static string ToJson(object item) 17 | { 18 | StringBuilder stringBuilder = new StringBuilder(); 19 | AppendValue(stringBuilder, item); 20 | return stringBuilder.ToString(); 21 | } 22 | 23 | static void AppendValue(StringBuilder stringBuilder, object item) 24 | { 25 | if (item == null) 26 | { 27 | stringBuilder.Append("null"); 28 | return; 29 | } 30 | 31 | Type type = item.GetType(); 32 | if (type == typeof(string) || type == typeof(char)) 33 | { 34 | stringBuilder.Append('"'); 35 | string str = item.ToString(); 36 | for (int i = 0; i < str.Length; ++i) 37 | if (str[i] < ' ' || str[i] == '"' || str[i] == '\\') 38 | { 39 | stringBuilder.Append('\\'); 40 | int j = "\"\\\n\r\t\b\f".IndexOf(str[i]); 41 | if (j >= 0) 42 | stringBuilder.Append("\"\\nrtbf"[j]); 43 | else 44 | stringBuilder.AppendFormat("u{0:X4}", (UInt32)str[i]); 45 | } 46 | else 47 | stringBuilder.Append(str[i]); 48 | stringBuilder.Append('"'); 49 | } 50 | else if (type == typeof(byte) || type == typeof(sbyte)) 51 | { 52 | stringBuilder.Append(item.ToString()); 53 | } 54 | else if (type == typeof(short) || type == typeof(ushort)) 55 | { 56 | stringBuilder.Append(item.ToString()); 57 | } 58 | else if (type == typeof(int) || type == typeof(uint)) 59 | { 60 | stringBuilder.Append(item.ToString()); 61 | } 62 | else if (type == typeof(long) || type == typeof(ulong)) 63 | { 64 | stringBuilder.Append(item.ToString()); 65 | } 66 | else if (type == typeof(float)) 67 | { 68 | stringBuilder.Append(((float)item).ToString(System.Globalization.CultureInfo.InvariantCulture)); 69 | } 70 | else if (type == typeof(double)) 71 | { 72 | stringBuilder.Append(((double)item).ToString(System.Globalization.CultureInfo.InvariantCulture)); 73 | } 74 | else if (type == typeof(decimal)) 75 | { 76 | stringBuilder.Append(((decimal)item).ToString(System.Globalization.CultureInfo.InvariantCulture)); 77 | } 78 | else if (type == typeof(bool)) 79 | { 80 | stringBuilder.Append(((bool)item) ? "true" : "false"); 81 | } 82 | else if (type.IsEnum) 83 | { 84 | stringBuilder.Append('"'); 85 | stringBuilder.Append(item.ToString()); 86 | stringBuilder.Append('"'); 87 | } 88 | else if (item is IList) 89 | { 90 | stringBuilder.Append('['); 91 | bool isFirst = true; 92 | IList list = item as IList; 93 | for (int i = 0; i < list.Count; i++) 94 | { 95 | if (isFirst) 96 | isFirst = false; 97 | else 98 | stringBuilder.Append(','); 99 | AppendValue(stringBuilder, list[i]); 100 | } 101 | stringBuilder.Append(']'); 102 | } 103 | else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) 104 | { 105 | Type keyType = type.GetGenericArguments()[0]; 106 | 107 | //Refuse to output dictionary keys that aren't of type string 108 | if (keyType != typeof(string)) 109 | { 110 | stringBuilder.Append("{}"); 111 | return; 112 | } 113 | 114 | stringBuilder.Append('{'); 115 | IDictionary dict = item as IDictionary; 116 | bool isFirst = true; 117 | foreach (object key in dict.Keys) 118 | { 119 | if (isFirst) 120 | isFirst = false; 121 | else 122 | stringBuilder.Append(','); 123 | stringBuilder.Append('\"'); 124 | stringBuilder.Append((string)key); 125 | stringBuilder.Append("\":"); 126 | AppendValue(stringBuilder, dict[key]); 127 | } 128 | stringBuilder.Append('}'); 129 | } 130 | else 131 | { 132 | stringBuilder.Append('{'); 133 | 134 | bool isFirst = true; 135 | FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy); 136 | for (int i = 0; i < fieldInfos.Length; i++) 137 | { 138 | if (fieldInfos[i].IsDefined(typeof(IgnoreDataMemberAttribute), true)) 139 | continue; 140 | 141 | object value = fieldInfos[i].GetValue(item); 142 | if (value != null) 143 | { 144 | if (isFirst) 145 | isFirst = false; 146 | else 147 | stringBuilder.Append(','); 148 | stringBuilder.Append('\"'); 149 | stringBuilder.Append(GetMemberName(fieldInfos[i])); 150 | stringBuilder.Append("\":"); 151 | AppendValue(stringBuilder, value); 152 | } 153 | } 154 | PropertyInfo[] propertyInfo = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy); 155 | for (int i = 0; i < propertyInfo.Length; i++) 156 | { 157 | if (!propertyInfo[i].CanRead || propertyInfo[i].IsDefined(typeof(IgnoreDataMemberAttribute), true)) 158 | continue; 159 | 160 | object value = propertyInfo[i].GetValue(item, null); 161 | if (value != null) 162 | { 163 | if (isFirst) 164 | isFirst = false; 165 | else 166 | stringBuilder.Append(','); 167 | stringBuilder.Append('\"'); 168 | stringBuilder.Append(GetMemberName(propertyInfo[i])); 169 | stringBuilder.Append("\":"); 170 | AppendValue(stringBuilder, value); 171 | } 172 | } 173 | 174 | stringBuilder.Append('}'); 175 | } 176 | } 177 | 178 | static string GetMemberName(MemberInfo member) 179 | { 180 | if (member.IsDefined(typeof(DataMemberAttribute), true)) 181 | { 182 | DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)Attribute.GetCustomAttribute(member, typeof(DataMemberAttribute), true); 183 | if (!string.IsNullOrEmpty(dataMemberAttribute.Name)) 184 | return dataMemberAttribute.Name; 185 | } 186 | 187 | return member.Name; 188 | } 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /BrowserHost.Common/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("BrowserHost.Common")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("BrowserHost.Common")] 13 | [assembly: AssemblyCopyright("Copyright © 2020")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("9ec3f19a-cea0-44bd-b55c-fecf7d02cc6b")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.4.1.2")] 36 | [assembly: AssemblyFileVersion("1.4.1.2")] 37 | -------------------------------------------------------------------------------- /BrowserHost.Common/RenderProcess.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace BrowserHost.Common 4 | { 5 | // TODO: I should probably split this file up it's getting a bit silly 6 | 7 | public class RenderProcessArguments 8 | { 9 | public int ParentPid; 10 | public string CefAssemblyDir; 11 | public string CefCacheDir; 12 | public string DalamudAssemblyDir; 13 | public long DxgiAdapterLuid; 14 | public string KeepAliveHandleName; 15 | public string IpcChannelName; 16 | 17 | public string Serialise() 18 | { 19 | return TinyJson.JSONWriter.ToJson(this); 20 | } 21 | 22 | public static RenderProcessArguments Deserialise(string serialisedArgs) 23 | { 24 | return TinyJson.JSONParser.FromJson(serialisedArgs); 25 | } 26 | } 27 | 28 | public struct BitmapFrame 29 | { 30 | public int Length; 31 | public int Width; 32 | public int Height; 33 | public int DirtyX; 34 | public int DirtyY; 35 | public int DirtyWidth; 36 | public int DirtyHeight; 37 | } 38 | 39 | public enum FrameTransportMode 40 | { 41 | None = 0, 42 | SharedTexture = 1 << 0, 43 | BitmapBuffer = 1 << 1, 44 | } 45 | 46 | #region Downstream IPC 47 | 48 | [Serializable] 49 | public class DownstreamIpcRequest { } 50 | 51 | [Serializable] 52 | public class NewInlayRequest : DownstreamIpcRequest { 53 | public Guid Guid; 54 | public FrameTransportMode FrameTransportMode; 55 | public string Url; 56 | public int Width; 57 | public int Height; 58 | } 59 | 60 | [Serializable] 61 | public class ResizeInlayRequest : DownstreamIpcRequest 62 | { 63 | public Guid Guid; 64 | public int Width; 65 | public int Height; 66 | } 67 | 68 | [Serializable] 69 | public class FrameTransportResponse { } 70 | 71 | [Serializable] 72 | public class TextureHandleResponse : FrameTransportResponse 73 | { 74 | public IntPtr TextureHandle; 75 | } 76 | 77 | [Serializable] 78 | public class BitmapBufferResponse : FrameTransportResponse 79 | { 80 | public string BitmapBufferName; 81 | public string FrameInfoBufferName; 82 | } 83 | 84 | [Serializable] 85 | public class NavigateInlayRequest : DownstreamIpcRequest 86 | { 87 | public Guid Guid; 88 | public string Url; 89 | } 90 | 91 | [Serializable] 92 | public class DebugInlayRequest : DownstreamIpcRequest 93 | { 94 | public Guid Guid; 95 | } 96 | 97 | [Serializable] 98 | public class RemoveInlayRequest : DownstreamIpcRequest 99 | { 100 | public Guid Guid; 101 | } 102 | 103 | public enum InputModifier 104 | { 105 | None = 0, 106 | Shift = 1 << 0, 107 | Control = 1 << 1, 108 | Alt = 1 << 2, 109 | } 110 | 111 | public enum MouseButton 112 | { 113 | None = 0, 114 | Primary = 1 << 0, 115 | Secondary = 1 << 1, 116 | Tertiary = 1 << 2, 117 | Fourth = 1 << 3, 118 | Fifth = 1 << 4, 119 | } 120 | 121 | [Serializable] 122 | public class MouseEventRequest : DownstreamIpcRequest 123 | { 124 | public Guid Guid; 125 | public float X; 126 | public float Y; 127 | public bool Leaving; 128 | // The following button fields represent changes since the previous event, not current state 129 | // TODO: May be approaching being advantageous for button->fields map 130 | public MouseButton Down; 131 | public MouseButton Double; 132 | public MouseButton Up; 133 | public float WheelX; 134 | public float WheelY; 135 | public InputModifier Modifier; 136 | } 137 | 138 | public enum KeyEventType 139 | { 140 | KeyDown, 141 | KeyUp, 142 | Character, 143 | } 144 | 145 | [Serializable] 146 | public class KeyEventRequest : DownstreamIpcRequest 147 | { 148 | public Guid Guid; 149 | public KeyEventType Type; 150 | public bool SystemKey; 151 | public int UserKeyCode; 152 | public int NativeKeyCode; 153 | public InputModifier Modifier; 154 | } 155 | 156 | #endregion 157 | 158 | #region Upstream IPC 159 | 160 | [Serializable] 161 | public class UpstreamIpcRequest { } 162 | 163 | [Serializable] 164 | public class ReadyNotificationRequest : UpstreamIpcRequest 165 | { 166 | public FrameTransportMode availableTransports; 167 | } 168 | 169 | // Akk, did you really write out every supported value of the cursor property despite both sides of the IPC not supporting the full set? 170 | // Yes. Yes I did. 171 | public enum Cursor 172 | { 173 | Default, 174 | None, 175 | ContextMenu, 176 | Help, 177 | Pointer, 178 | Progress, 179 | Wait, 180 | Cell, 181 | Crosshair, 182 | Text, 183 | VerticalText, 184 | Alias, 185 | Copy, 186 | Move, 187 | NoDrop, 188 | NotAllowed, 189 | Grab, 190 | Grabbing, 191 | AllScroll, 192 | ColResize, 193 | RowResize, 194 | NResize, 195 | EResize, 196 | SResize, 197 | WResize, 198 | NEResize, 199 | NWResize, 200 | SEResize, 201 | SWResize, 202 | EWResize, 203 | NSResize, 204 | NESWResize, 205 | NWSEResize, 206 | ZoomIn, 207 | ZoomOut, 208 | 209 | // Special case value - cursor is on a fully-transparent section of the page, and should not capture 210 | BrowserHostNoCapture, 211 | } 212 | 213 | [Serializable] 214 | public class SetCursorRequest : UpstreamIpcRequest 215 | { 216 | public Guid Guid; 217 | public Cursor Cursor; 218 | } 219 | 220 | #endregion 221 | } 222 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/BrowserHost.Plugin.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | net5.0-windows 4 | Library 5 | 8.0 6 | false 7 | false 8 | false 9 | x64 10 | true 11 | 12 | 13 | ..\bin\Debug\plugin\ 14 | false 15 | 8.0 16 | MinimumRecommendedRules.ruleset 17 | true 18 | 19 | 20 | ..\bin\Release\plugin\ 21 | none 22 | 8.0 23 | MinimumRecommendedRules.ruleset 24 | 25 | 26 | 27 | $(AppData)\XIVLauncher\addon\Hooks\dev\Dalamud.dll 28 | False 29 | 30 | 31 | $(AppData)\XIVLauncher\addon\Hooks\dev\ImGui.NET.dll 32 | False 33 | 34 | 35 | $(AppData)\XIVLauncher\addon\Hooks\dev\ImGuiScene.dll 36 | False 37 | 38 | 39 | $(AppData)\XIVLauncher\addon\Hooks\dev\SharpDX.dll 40 | False 41 | 42 | 43 | $(AppData)\XIVLauncher\addon\Hooks\dev\SharpDX.Direct3D11.dll 44 | False 45 | 46 | 47 | $(AppData)\XIVLauncher\addon\Hooks\dev\SharpDX.DXGI.dll 48 | False 49 | 50 | 51 | 52 | 53 | PreserveNewest 54 | 55 | 56 | PreserveNewest 57 | 58 | 59 | PreserveNewest 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/BrowserHost.Plugin.json: -------------------------------------------------------------------------------- 1 | { 2 | "Author": "ackwell", 3 | "Name": "Browser Host", 4 | "Punchline": "Dalamud plugin for in-game browser rendering.", 5 | "Description": "Dalamud plugin for in-game browser rendering. Think OverlayPlugin, but it's in the game itself.\nUse the settings button below or the '/bh config' command to configure.", 6 | "InternalName": "BrowserHost.Plugin", 7 | "AssemblyVersion": "1.4.1.2", 8 | "RepoUrl": "https://github.com/ackwell/BrowserHost", 9 | "ApplicableVersion": "any", 10 | "Tags": [ "framework", "browser", "inlay" ], 11 | "DalamudApiLevel": 4 12 | } 13 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/Configuration.cs: -------------------------------------------------------------------------------- 1 | using BrowserHost.Common; 2 | using Dalamud.Configuration; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | namespace BrowserHost.Plugin 7 | { 8 | [Serializable] 9 | class Configuration : IPluginConfiguration 10 | { 11 | public int Version { get; set; } = 0; 12 | 13 | public FrameTransportMode FrameTransportMode = FrameTransportMode.SharedTexture; 14 | public List Inlays = new List(); 15 | } 16 | 17 | [Serializable] 18 | class InlayConfiguration 19 | { 20 | public Guid Guid; 21 | public string Name; 22 | public string Url; 23 | public bool Hidden; 24 | public bool Locked; 25 | public bool TypeThrough; 26 | public bool ClickThrough; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/DependencyManager.cs: -------------------------------------------------------------------------------- 1 | using Dalamud.Logging; 2 | using ImGuiNET; 3 | using System; 4 | using System.Collections.Concurrent; 5 | using System.Diagnostics.Contracts; 6 | using System.IO; 7 | using System.IO.Compression; 8 | using System.Linq; 9 | using System.Net; 10 | using System.Numerics; 11 | using System.Security.Cryptography; 12 | using System.Text; 13 | using System.Threading.Tasks; 14 | 15 | namespace BrowserHost.Plugin 16 | { 17 | class Dependency 18 | { 19 | public string Url; 20 | public string Version; 21 | public string Directory; 22 | public string Checksum; 23 | } 24 | 25 | class DependencyManager : IDisposable 26 | { 27 | private static string DOWNLOAD_DIR = "downloads"; 28 | private static Dependency[] DEPENDENCIES = new[] 29 | { 30 | new Dependency() 31 | { 32 | Url = "https://github.com/ackwell/BrowserHost/releases/download/cef-binaries/cefsharp-{VERSION}.zip", 33 | Directory = "cef", 34 | Version = "89.0.17+ge7bbb1d+chromium-89.0.4389.114", 35 | Checksum = "0710C93F7FEC62064EC1811AD0398C343342D17CFFA0E091FD21C5BE5A15CF69", 36 | } 37 | }; 38 | 39 | public event EventHandler DependenciesReady; 40 | 41 | private string dependencyDir; 42 | private string debugCheckDir; 43 | private Dependency[] missingDependencies; 44 | private ConcurrentDictionary installProgress = new ConcurrentDictionary(); 45 | 46 | private enum ViewMode 47 | { 48 | Confirm, 49 | Installing, 50 | Complete, 51 | Failed, 52 | Hidden, 53 | } 54 | private ViewMode viewMode = ViewMode.Hidden; 55 | 56 | // Per-dependency special-cased progress values 57 | private static short DEP_EXTRACTING = -1; 58 | private static short DEP_COMPLETE = -2; 59 | private static short DEP_FAILED = -3; 60 | 61 | public DependencyManager(string pluginDir, string pluginConfigDir) 62 | { 63 | dependencyDir = Path.Join(pluginConfigDir, "dependencies"); 64 | debugCheckDir = Path.GetDirectoryName(pluginDir); 65 | } 66 | 67 | public void Initialise() 68 | { 69 | CheckDependencies(); 70 | } 71 | 72 | public void Dispose() { } 73 | 74 | private void CheckDependencies() 75 | { 76 | missingDependencies = DEPENDENCIES.Where(DependencyMissing).ToArray(); 77 | if (missingDependencies.Length == 0) 78 | { 79 | viewMode = ViewMode.Hidden; 80 | DependenciesReady?.Invoke(this, null); 81 | } 82 | else 83 | { 84 | viewMode = ViewMode.Confirm; 85 | } 86 | } 87 | 88 | private bool DependencyMissing(Dependency dependency) 89 | { 90 | var versionFilePath = Path.Combine(GetDependencyPath(dependency), "VERSION"); 91 | 92 | string versionContents; 93 | try { versionContents = File.ReadAllText(versionFilePath); } 94 | catch { return true; } 95 | 96 | return !versionContents.Contains(dependency.Version); 97 | } 98 | 99 | private void InstallDependencies() 100 | { 101 | viewMode = ViewMode.Installing; 102 | PluginLog.Log("Installing dependencies..."); 103 | 104 | var installTasks = missingDependencies.Select(InstallDependency); 105 | Task.WhenAll(installTasks).ContinueWith(task => 106 | { 107 | var failed = installProgress.Any(pair => pair.Value == DEP_FAILED); 108 | viewMode = failed ? ViewMode.Failed : ViewMode.Complete; 109 | PluginLog.Log($"Dependency install {viewMode}."); 110 | 111 | try { Directory.Delete(Path.Combine(dependencyDir, DOWNLOAD_DIR), true); } 112 | catch { } 113 | }); 114 | } 115 | 116 | private async Task InstallDependency(Dependency dependency) 117 | { 118 | PluginLog.Log($"Downloading {dependency.Directory} {dependency.Version}"); 119 | 120 | // Ensure the downloads dir exists 121 | var downloadDir = Path.Combine(dependencyDir, DOWNLOAD_DIR); 122 | Directory.CreateDirectory(downloadDir); 123 | 124 | // Get the file name we'll download to - if it's already in downloads, it may be corrupt, delete 125 | var filePath = Path.Combine(downloadDir, $"{dependency.Directory}-{dependency.Version}.zip"); 126 | File.Delete(filePath); 127 | 128 | // Set up the download and kick it off 129 | using WebClient client = new WebClient(); 130 | client.DownloadProgressChanged += (sender, args) => installProgress.AddOrUpdate( 131 | dependency.Directory, 132 | args.ProgressPercentage, 133 | (key, oldValue) => Math.Max(oldValue, args.ProgressPercentage)); 134 | await client.DownloadFileTaskAsync( 135 | dependency.Url.Replace("{VERSION}", dependency.Version), 136 | filePath); 137 | 138 | // Download complete, mark as extracting 139 | installProgress.AddOrUpdate(dependency.Directory, DEP_EXTRACTING, (key, oldValue) => DEP_EXTRACTING); 140 | 141 | // Calculate the checksum for the download 142 | string downloadedChecksum; 143 | try 144 | { 145 | using (var sha = SHA256.Create()) 146 | using (var stream = new FileStream(filePath, FileMode.Open)) 147 | { 148 | stream.Position = 0; 149 | var rawHash = sha.ComputeHash(stream); 150 | var builder = new StringBuilder(rawHash.Length); 151 | for (var i = 0; i < rawHash.Length; i++) { builder.Append($"{rawHash[i]:X2}"); } 152 | downloadedChecksum = builder.ToString(); 153 | } 154 | } 155 | catch 156 | { 157 | PluginLog.LogError($"Failed to calculate checksum for {filePath}"); 158 | downloadedChecksum = "FAILED"; 159 | } 160 | 161 | // Make sure the checksum matches 162 | if (downloadedChecksum != dependency.Checksum) 163 | { 164 | PluginLog.LogError($"Mismatched checksum for {filePath}"); 165 | installProgress.AddOrUpdate(dependency.Directory, DEP_FAILED, (key, oldValue) => DEP_FAILED); 166 | File.Delete(filePath); 167 | return; 168 | } 169 | 170 | installProgress.AddOrUpdate(dependency.Directory, DEP_COMPLETE, (key, oldValue) => DEP_COMPLETE); 171 | 172 | // Extract to the destination dir 173 | var destinationDir = GetDependencyPath(dependency); 174 | try { Directory.Delete(destinationDir, true); } 175 | catch { } 176 | ZipFile.ExtractToDirectory(filePath, destinationDir); 177 | 178 | // Clear out the downloaded file now we're done with it 179 | File.Delete(filePath); 180 | } 181 | 182 | public string GetDependencyPathFor(string dependencyDir) 183 | { 184 | var dependency = DEPENDENCIES.First(dependency => dependency.Directory == dependencyDir); 185 | if (dependency == null) { throw new Exception($"Unknown dependency {dependencyDir}"); } 186 | return GetDependencyPath(dependency); 187 | } 188 | 189 | private string GetDependencyPath(Dependency dependency) 190 | { 191 | var localDebug = Path.Combine(debugCheckDir, dependency.Directory); 192 | if (Directory.Exists(localDebug)) { return localDebug; } 193 | return Path.Combine(dependencyDir, dependency.Directory); 194 | } 195 | 196 | public void Render() 197 | { 198 | if (viewMode == ViewMode.Hidden) { return; } 199 | 200 | var windowFlags = ImGuiWindowFlags.AlwaysAutoResize; 201 | ImGui.Begin("BrowserHost dependencies", windowFlags); 202 | ImGui.SetWindowFocus(); 203 | 204 | switch (viewMode) 205 | { 206 | case ViewMode.Confirm: RenderConfirm(); break; 207 | case ViewMode.Installing: RenderInstalling(); break; 208 | case ViewMode.Complete: RenderComplete(); break; 209 | case ViewMode.Failed: RenderFailed(); break; 210 | } 211 | 212 | ImGui.End(); 213 | } 214 | 215 | private void RenderConfirm() 216 | { 217 | ImGui.Text($"The following dependencies are currently missing:"); 218 | 219 | if (missingDependencies == null) { return; } 220 | 221 | ImGui.Indent(); 222 | foreach (var dependency in missingDependencies) 223 | { 224 | ImGui.Text($"{dependency.Directory} ({dependency.Version})"); 225 | } 226 | ImGui.Unindent(); 227 | 228 | ImGui.Separator(); 229 | 230 | if (ImGui.Button("Install missing dependencies")) { InstallDependencies(); } 231 | } 232 | 233 | private void RenderInstalling() 234 | { 235 | ImGui.Text("Installing dependencies..."); 236 | 237 | ImGui.Separator(); 238 | 239 | RenderDownloadProgress(); 240 | } 241 | 242 | private void RenderComplete() 243 | { 244 | ImGui.Text("Dependency installation complete!"); 245 | 246 | ImGui.Separator(); 247 | 248 | RenderDownloadProgress(); 249 | 250 | ImGui.Separator(); 251 | 252 | if (ImGui.Button("OK", new Vector2(100, 0))) { CheckDependencies(); } 253 | } 254 | 255 | private void RenderFailed() 256 | { 257 | ImGui.Text("One or more dependencies failed to install successfully."); 258 | ImGui.Text("This is usually caused by network interruptions. Please retry."); 259 | ImGui.Text("If this keeps happening, let us know on discord."); 260 | 261 | ImGui.Separator(); 262 | 263 | RenderDownloadProgress(); 264 | 265 | ImGui.Separator(); 266 | 267 | if (ImGui.Button("Retry", new Vector2(100, 0))) { CheckDependencies(); } 268 | } 269 | 270 | private void RenderDownloadProgress() 271 | { 272 | var progressSize = new Vector2(200, 0); 273 | 274 | foreach (var progress in installProgress) 275 | { 276 | if (progress.Value == DEP_EXTRACTING) { ImGui.ProgressBar(1, progressSize, "Extracting"); } 277 | else if (progress.Value == DEP_COMPLETE) { ImGui.ProgressBar(1, progressSize, "Complete"); } 278 | else if (progress.Value == DEP_FAILED) 279 | { 280 | ImGui.PushStyleColor(ImGuiCol.PlotHistogram, 0xAA0000FF); 281 | ImGui.ProgressBar(1, progressSize, "Error"); 282 | ImGui.PopStyleColor(); 283 | } 284 | else { ImGui.ProgressBar(progress.Value / 100, progressSize); } 285 | ImGui.SameLine(); 286 | ImGui.Text(progress.Key); 287 | } 288 | } 289 | } 290 | } 291 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/DxHandler.cs: -------------------------------------------------------------------------------- 1 | using Dalamud.Plugin; 2 | using D3D11 = SharpDX.Direct3D11; 3 | using DXGI = SharpDX.DXGI; 4 | using System; 5 | 6 | namespace BrowserHost.Plugin 7 | { 8 | static class DxHandler 9 | { 10 | public static D3D11.Device Device { get; private set; } 11 | public static IntPtr WindowHandle { get; private set; } 12 | public static long AdapterLuid { get; private set; } 13 | 14 | public static void Initialise(DalamudPluginInterface pluginInterface) 15 | { 16 | Device = pluginInterface.UiBuilder.Device; 17 | //Device = new D3D11.Device(SharpDX.Direct3D.DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport | D3D11.DeviceCreationFlags.Debug); 18 | 19 | // Grab the window handle, we'll use this for setting up our wndproc hook 20 | WindowHandle = pluginInterface.UiBuilder.WindowHandlePtr; 21 | 22 | // Get the game's device adapter, we'll need that as a reference for the render process. 23 | var dxgiDevice = Device.QueryInterface(); 24 | AdapterLuid = dxgiDevice.Adapter.Description.Luid; 25 | } 26 | 27 | public static void Shutdown() 28 | { 29 | Device = null; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/Inlay.cs: -------------------------------------------------------------------------------- 1 | using BrowserHost.Common; 2 | using BrowserHost.Plugin.TextureHandlers; 3 | using Dalamud.Logging; 4 | using ImGuiNET; 5 | using System; 6 | using System.Numerics; 7 | 8 | namespace BrowserHost.Plugin 9 | { 10 | class Inlay : IDisposable 11 | { 12 | private Configuration config; 13 | private InlayConfiguration inlayConfig; 14 | public Guid RenderGuid { get; private set; } = Guid.NewGuid(); 15 | 16 | private bool resizing = false; 17 | private Vector2 size; 18 | 19 | private RenderProcess renderProcess; 20 | private ITextureHandler textureHandler; 21 | private Exception textureRenderException; 22 | 23 | private bool mouseInWindow; 24 | private bool windowFocused; 25 | private InputModifier modifier; 26 | private ImGuiMouseCursor cursor; 27 | private bool captureCursor; 28 | 29 | public Inlay(RenderProcess renderProcess, Configuration config, InlayConfiguration inlayConfig) 30 | { 31 | this.renderProcess = renderProcess; 32 | this.config = config; 33 | this.inlayConfig = inlayConfig; 34 | } 35 | 36 | public void Dispose() 37 | { 38 | textureHandler?.Dispose(); 39 | renderProcess.Send(new RemoveInlayRequest() { Guid = RenderGuid }); 40 | } 41 | 42 | public void Navigate(string newUrl) 43 | { 44 | renderProcess.Send(new NavigateInlayRequest() { Guid = RenderGuid, Url = newUrl }); 45 | } 46 | 47 | public void Debug() 48 | { 49 | renderProcess.Send(new DebugInlayRequest() { Guid = RenderGuid }); 50 | } 51 | 52 | public void InvalidateTransport() 53 | { 54 | // Get old refs so we can clean up later 55 | var oldTextureHandler = textureHandler; 56 | var oldRenderGuid = RenderGuid; 57 | 58 | // Invalidate the handler, and reset the size to trigger a rebuild 59 | // Also need to generate a new renderer guid so we don't have a collision during the hand over 60 | // TODO: Might be able to tweak the logic in resize alongside this to shore up (re)builds 61 | textureHandler = null; 62 | size = Vector2.Zero; 63 | RenderGuid = Guid.NewGuid(); 64 | 65 | // Clean up 66 | oldTextureHandler.Dispose(); 67 | renderProcess.Send(new RemoveInlayRequest() { Guid = oldRenderGuid }); 68 | } 69 | 70 | public void SetCursor(Cursor cursor) 71 | { 72 | captureCursor = cursor != Cursor.BrowserHostNoCapture; 73 | this.cursor = DecodeCursor(cursor); 74 | } 75 | 76 | public (bool, long) WndProcMessage(WindowsMessage msg, ulong wParam, long lParam) 77 | { 78 | // Check if there was a click, and use it to set the window focused state 79 | // We're avoiding ImGui for this, as we want to check for clicks entirely outside 80 | // ImGui's pervue to defocus inlays 81 | if (msg == WindowsMessage.WM_LBUTTONDOWN) { windowFocused = mouseInWindow && captureCursor; } 82 | 83 | // Bail if we're not focused or we're typethrough 84 | // TODO: Revisit the focus check for UI stuff, might not hold 85 | if (!windowFocused || inlayConfig.TypeThrough) { return (false, 0); } 86 | 87 | KeyEventType? eventType = msg switch 88 | { 89 | WindowsMessage.WM_KEYDOWN => KeyEventType.KeyDown, 90 | WindowsMessage.WM_SYSKEYDOWN => KeyEventType.KeyDown, 91 | WindowsMessage.WM_KEYUP => KeyEventType.KeyUp, 92 | WindowsMessage.WM_SYSKEYUP => KeyEventType.KeyUp, 93 | WindowsMessage.WM_CHAR => KeyEventType.Character, 94 | WindowsMessage.WM_SYSCHAR => KeyEventType.Character, 95 | _ => (KeyEventType?) null, 96 | }; 97 | 98 | // If the event isn't something we're tracking, bail early with no capture 99 | if (eventType == null) { return (false, 0); } 100 | 101 | var isSystemKey = false 102 | || msg == WindowsMessage.WM_SYSKEYDOWN 103 | || msg == WindowsMessage.WM_SYSKEYUP 104 | || msg == WindowsMessage.WM_SYSCHAR; 105 | 106 | // TODO: Technically this is only firing once, because we're checking focused before this point, 107 | // but having this logic essentially duped per-inlay is a bit eh. Dedupe at higher point? 108 | var modifierAdjust = InputModifier.None; 109 | if (wParam == (int)VirtualKey.Shift) { modifierAdjust |= InputModifier.Shift; } 110 | if (wParam == (int)VirtualKey.Control) { modifierAdjust |= InputModifier.Control; } 111 | // SYS* messages signal alt is held (really?) 112 | if (isSystemKey) { modifierAdjust |= InputModifier.Alt; } 113 | 114 | if (eventType == KeyEventType.KeyDown) { modifier |= modifierAdjust; } 115 | else if (eventType == KeyEventType.KeyUp) { modifier &= ~modifierAdjust; } 116 | 117 | renderProcess.Send(new KeyEventRequest() 118 | { 119 | Guid = RenderGuid, 120 | Type = eventType.Value, 121 | SystemKey = isSystemKey, 122 | UserKeyCode = (int)wParam, 123 | NativeKeyCode = (int)lParam, 124 | Modifier = modifier, 125 | }); 126 | 127 | // We've handled the input, signal. For these message types, `0` signals a capture. 128 | return (true, 0); 129 | } 130 | 131 | public void Render() 132 | { 133 | if (inlayConfig.Hidden) 134 | { 135 | mouseInWindow = false; 136 | return; 137 | } 138 | 139 | ImGui.SetNextWindowSize(new Vector2(640, 480), ImGuiCond.FirstUseEver); 140 | ImGui.Begin($"{inlayConfig.Name}###{inlayConfig.Guid}", GetWindowFlags()); 141 | 142 | HandleWindowSize(); 143 | 144 | // TODO: Renderer can take some time to spin up properly, should add a loading state. 145 | if (textureHandler != null) 146 | { 147 | HandleMouseEvent(); 148 | 149 | textureHandler.Render(); 150 | } 151 | else if (textureRenderException != null) 152 | { 153 | ImGui.PushStyleColor(ImGuiCol.Text, 0xFF0000FF); 154 | ImGui.Text("An error occured while building the browser inlay texture:"); 155 | ImGui.Text(textureRenderException.ToString()); 156 | ImGui.PopStyleColor(); 157 | } 158 | ImGui.End(); 159 | } 160 | 161 | private ImGuiWindowFlags GetWindowFlags() 162 | { 163 | var flags = ImGuiWindowFlags.None 164 | | ImGuiWindowFlags.NoTitleBar 165 | | ImGuiWindowFlags.NoCollapse 166 | | ImGuiWindowFlags.NoScrollbar 167 | | ImGuiWindowFlags.NoScrollWithMouse 168 | | ImGuiWindowFlags.NoBringToFrontOnFocus 169 | | ImGuiWindowFlags.NoFocusOnAppearing; 170 | 171 | // ClickThrough is implicitly locked 172 | var locked = inlayConfig.Locked || inlayConfig.ClickThrough; 173 | 174 | if (locked) 175 | { 176 | flags |= ImGuiWindowFlags.None 177 | | ImGuiWindowFlags.NoMove 178 | | ImGuiWindowFlags.NoResize 179 | | ImGuiWindowFlags.NoBackground; 180 | } 181 | 182 | if (inlayConfig.ClickThrough || (!captureCursor && locked)) 183 | { 184 | flags |= ImGuiWindowFlags.NoMouseInputs | ImGuiWindowFlags.NoNav; 185 | } 186 | 187 | return flags; 188 | } 189 | 190 | private void HandleMouseEvent() 191 | { 192 | // Render proc won't be ready on first boot 193 | // Totally skip mouse handling for click through inlays, as well 194 | if (renderProcess == null || inlayConfig.ClickThrough) { return; } 195 | 196 | var io = ImGui.GetIO(); 197 | var windowPos = ImGui.GetWindowPos(); 198 | var mousePos = io.MousePos - windowPos - ImGui.GetWindowContentRegionMin(); 199 | 200 | // Generally we want to use IsWindowHovered for hit checking, as it takes z-stacking into account - 201 | // but when cursor isn't being actively captured, imgui will always return false - so fall back 202 | // so a slightly more naive hover check, just to maintain a bit of flood prevention. 203 | // TODO: Need to test how this will handle overlaps... fully transparent _shouldn't_ be accepting 204 | // clicks so shouuulllddd beee fineee??? 205 | var hovered = captureCursor 206 | ? ImGui.IsWindowHovered() 207 | : ImGui.IsMouseHoveringRect(windowPos, windowPos + ImGui.GetWindowSize()); 208 | 209 | // If the cursor is outside the window, send a final mouse leave then noop 210 | if (!hovered) 211 | { 212 | if (mouseInWindow) 213 | { 214 | mouseInWindow = false; 215 | renderProcess.Send(new MouseEventRequest() 216 | { 217 | Guid = RenderGuid, 218 | X = mousePos.X, 219 | Y = mousePos.Y, 220 | Leaving = true, 221 | }); 222 | } 223 | return; 224 | } 225 | mouseInWindow = true; 226 | 227 | ImGui.SetMouseCursor(cursor); 228 | 229 | var down = EncodeMouseButtons(io.MouseClicked); 230 | var double_ = EncodeMouseButtons(io.MouseDoubleClicked); 231 | var up = EncodeMouseButtons(io.MouseReleased); 232 | var wheelX = io.MouseWheelH; 233 | var wheelY = io.MouseWheel; 234 | 235 | // If the event boils down to no change, bail before sending 236 | if (io.MouseDelta == Vector2.Zero && down == MouseButton.None && double_ == MouseButton.None && up == MouseButton.None && wheelX == 0 && wheelY == 0) 237 | { 238 | return; 239 | } 240 | 241 | var modifier = InputModifier.None; 242 | if (io.KeyShift) { modifier |= InputModifier.Shift; } 243 | if (io.KeyCtrl) { modifier |= InputModifier.Control; } 244 | if (io.KeyAlt) { modifier |= InputModifier.Alt; } 245 | 246 | // TODO: Either this or the entire handler function should be asynchronous so we're not blocking the entire draw thread 247 | renderProcess.Send(new MouseEventRequest() 248 | { 249 | Guid = RenderGuid, 250 | X = mousePos.X, 251 | Y = mousePos.Y, 252 | Down = down, 253 | Double = double_, 254 | Up = up, 255 | WheelX = wheelX, 256 | WheelY = wheelY, 257 | Modifier = modifier, 258 | }); 259 | } 260 | 261 | private async void HandleWindowSize() 262 | { 263 | var currentSize = ImGui.GetWindowContentRegionMax() - ImGui.GetWindowContentRegionMin(); 264 | if (currentSize == size || resizing) { return; } 265 | 266 | // If there isn't a size yet, we haven't rendered at all - boot up an inlay in the render process 267 | // TODO: Edge case - if a user _somehow_ makes the size zero, this will freak out and generate a new render inlay 268 | // TODO: Maybe consolidate the request types? dunno. 269 | var request = size == Vector2.Zero 270 | ? new NewInlayRequest() 271 | { 272 | Guid = RenderGuid, 273 | FrameTransportMode = config.FrameTransportMode, 274 | Url = inlayConfig.Url, 275 | Width = (int)currentSize.X, 276 | Height = (int)currentSize.Y, 277 | } 278 | : new ResizeInlayRequest() 279 | { 280 | Guid = RenderGuid, 281 | Width = (int)currentSize.X, 282 | Height = (int)currentSize.Y, 283 | } as DownstreamIpcRequest; 284 | 285 | resizing = true; 286 | 287 | var response = await renderProcess.Send(request); 288 | if (!response.Success) 289 | { 290 | PluginLog.LogError("Texture build failure, retrying..."); 291 | resizing = false; 292 | return; 293 | } 294 | 295 | size = currentSize; 296 | resizing = false; 297 | 298 | var oldTextureHandler = textureHandler; 299 | try 300 | { 301 | textureHandler = response.Data switch 302 | { 303 | TextureHandleResponse textureHandleResponse => new SharedTextureHandler(textureHandleResponse), 304 | BitmapBufferResponse bitmapBufferResponse => new BitmapBufferTextureHandler(bitmapBufferResponse), 305 | _ => throw new Exception($"Unhandled frame transport {response.GetType().Name}"), 306 | }; 307 | } 308 | catch (Exception e) { textureRenderException = e; } 309 | if (oldTextureHandler != null) { oldTextureHandler.Dispose(); } 310 | } 311 | 312 | #region serde 313 | 314 | private MouseButton EncodeMouseButtons(RangeAccessor buttons) 315 | { 316 | var result = MouseButton.None; 317 | if (buttons[0]) { result |= MouseButton.Primary; } 318 | if (buttons[1]) { result |= MouseButton.Secondary; } 319 | if (buttons[2]) { result |= MouseButton.Tertiary; } 320 | if (buttons[3]) { result |= MouseButton.Fourth; } 321 | if (buttons[4]) { result |= MouseButton.Fifth; } 322 | return result; 323 | } 324 | 325 | private ImGuiMouseCursor DecodeCursor(Cursor cursor) 326 | { 327 | // ngl kinda disappointed at the lack of options here 328 | switch (cursor) 329 | { 330 | case Cursor.Default: return ImGuiMouseCursor.Arrow; 331 | case Cursor.None: return ImGuiMouseCursor.None; 332 | case Cursor.Pointer: return ImGuiMouseCursor.Hand; 333 | 334 | case Cursor.Text: 335 | case Cursor.VerticalText: 336 | return ImGuiMouseCursor.TextInput; 337 | 338 | case Cursor.NResize: 339 | case Cursor.SResize: 340 | case Cursor.NSResize: 341 | return ImGuiMouseCursor.ResizeNS; 342 | 343 | case Cursor.EResize: 344 | case Cursor.WResize: 345 | case Cursor.EWResize: 346 | return ImGuiMouseCursor.ResizeEW; 347 | 348 | case Cursor.NEResize: 349 | case Cursor.SWResize: 350 | case Cursor.NESWResize: 351 | return ImGuiMouseCursor.ResizeNESW; 352 | 353 | case Cursor.NWResize: 354 | case Cursor.SEResize: 355 | case Cursor.NWSEResize: 356 | return ImGuiMouseCursor.ResizeNWSE; 357 | } 358 | 359 | return ImGuiMouseCursor.Arrow; 360 | } 361 | 362 | #endregion 363 | } 364 | } 365 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/IpcBuffer.cs: -------------------------------------------------------------------------------- 1 | using SharedMemory; 2 | using System; 3 | using System.IO; 4 | using System.Reflection; 5 | using System.Runtime.Serialization; 6 | using System.Runtime.Serialization.Formatters.Binary; 7 | using System.Threading.Tasks; 8 | 9 | namespace BrowserHost.Plugin 10 | { 11 | public class IpcResponse 12 | { 13 | public bool Success; 14 | public TResponse Data; 15 | } 16 | 17 | public class IpcBuffer : RpcBuffer 18 | { 19 | private static BinaryFormatter formatter = new BinaryFormatter() 20 | { 21 | Binder = new FuckingKillMeBinder() 22 | }; 23 | 24 | // Handle conversion between wire's byte[] and nicer clr types 25 | private static Func CallbackFactory(Func callback) 26 | { 27 | return (messageId, rawRequest) => 28 | { 29 | var request = Decode(rawRequest); 30 | 31 | var response = callback(request); 32 | 33 | return response == null ? null : Encode(response); 34 | }; 35 | } 36 | 37 | public IpcBuffer(string name, Func callback) : base(name, CallbackFactory(callback)) { } 38 | 39 | public IpcResponse RemoteRequest(TOutgoing request, int timeout = 5000) 40 | { 41 | var rawRequest = Encode(request); 42 | var rawResponse = RemoteRequest(rawRequest, timeout); 43 | return new IpcResponse 44 | { 45 | Success = rawResponse.Success, 46 | Data = rawResponse.Success ? Decode(rawResponse.Data) : default, 47 | }; 48 | } 49 | 50 | public async Task> RemoteRequestAsync(TOutgoing request, int timeout = 5000) 51 | { 52 | var rawRequest = Encode(request); 53 | var rawResponse = await RemoteRequestAsync(rawRequest, timeout); 54 | return new IpcResponse 55 | { 56 | Success = rawResponse.Success, 57 | Data = rawResponse.Success ? Decode(rawResponse.Data) : default, 58 | }; 59 | } 60 | 61 | private static byte[] Encode(T value) 62 | { 63 | byte[] encoded; 64 | using (MemoryStream stream = new MemoryStream()) 65 | { 66 | formatter.Serialize(stream, value); 67 | encoded = stream.ToArray(); 68 | } 69 | return encoded; 70 | } 71 | 72 | private static T Decode(byte[] encoded) 73 | { 74 | if (encoded == null) { return default; } 75 | 76 | T value; 77 | using (MemoryStream stream = new MemoryStream(encoded)) 78 | { 79 | value = (T)formatter.Deserialize(stream); 80 | } 81 | return value; 82 | } 83 | } 84 | 85 | public sealed class FuckingKillMeBinder : SerializationBinder 86 | { 87 | public override Type BindToType(string assemblyName, string typeName) 88 | { 89 | return Type.GetType(string.Format("{0}, {1}", typeName, assemblyName)); 90 | } 91 | 92 | public override void BindToName(Type serializedType, out string assemblyName, out string typeName) 93 | { 94 | base.BindToName(serializedType, out assemblyName, out typeName); 95 | if (serializedType.ToString().Contains("BrowserHost.Common")) 96 | { 97 | assemblyName = typeof(Common.DownstreamIpcRequest).Assembly.FullName; 98 | } 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/NativeMethods.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace BrowserHost.Plugin 5 | { 6 | // Enums are not comprehensive for the sake of omitting stuff I won't use. 7 | enum WindowLongType : int 8 | { 9 | GWL_WNDPROC = -4, 10 | } 11 | 12 | enum WindowsMessage 13 | { 14 | WM_KEYDOWN = 0x0100, 15 | WM_KEYUP = 0x0101, 16 | WM_CHAR = 0x0102, 17 | WM_SYSKEYDOWN = 0x0104, 18 | WM_SYSKEYUP = 0x0105, 19 | WM_SYSCHAR = 0x0106, 20 | 21 | WM_LBUTTONDOWN = 0x0201, 22 | } 23 | 24 | enum VirtualKey : int 25 | { 26 | Shift = 0x10, 27 | Control = 0x11, 28 | } 29 | 30 | class NativeMethods 31 | { 32 | public static bool IsKeyActive(VirtualKey key) 33 | { 34 | return (GetKeyState((int)key) & 1) == 1; 35 | } 36 | 37 | [DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW")] 38 | public static extern IntPtr GetWindowLongPtr(IntPtr hWnd, WindowLongType nIndex); 39 | 40 | [DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW")] 41 | public static extern IntPtr SetWindowLongPtr(IntPtr hWnd, WindowLongType nIndex, IntPtr dwNewLong); 42 | 43 | [DllImport("user32.dll", EntryPoint = "CallWindowProcW")] 44 | public static extern long CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint msg, ulong wParam, long lParam); 45 | 46 | [DllImport("user32.dll")] 47 | private static extern short GetKeyState(int nVirtKey); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/Plugin.cs: -------------------------------------------------------------------------------- 1 | using BrowserHost.Common; 2 | using Dalamud.Game.Command; 3 | using Dalamud.Game.Gui; 4 | using Dalamud.IoC; 5 | using Dalamud.Plugin; 6 | using ImGuiNET; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Diagnostics; 10 | using System.IO; 11 | using System.Linq; 12 | using System.Numerics; 13 | using System.Reflection; 14 | 15 | namespace BrowserHost.Plugin 16 | { 17 | public class Plugin : IDalamudPlugin 18 | { 19 | public string Name => "Browser Host"; 20 | 21 | private static string COMMAND = "/bh"; 22 | 23 | [PluginService] private static DalamudPluginInterface pluginInterface { get; set; } 24 | [PluginService] private static CommandManager commandManager { get; set; } 25 | [PluginService] private static ChatGui chat { get; set; } 26 | private string pluginDir; 27 | private string pluginConfigDir; 28 | 29 | private DependencyManager dependencyManager; 30 | private Settings settings; 31 | 32 | private RenderProcess renderProcess; 33 | private Dictionary inlays = new Dictionary(); 34 | 35 | // Required for LivePluginLoader support 36 | public string AssemblyLocation { get; private set; } = Assembly.GetExecutingAssembly().Location; 37 | 38 | public Plugin() 39 | { 40 | //this.pluginInterface = pluginInterface; 41 | pluginDir = Path.GetDirectoryName(AssemblyLocation); 42 | pluginConfigDir = pluginInterface.GetPluginConfigDirectory(); 43 | 44 | // Hook up render hook 45 | pluginInterface.UiBuilder.Draw += Render; 46 | 47 | dependencyManager = new DependencyManager(pluginDir, pluginConfigDir); 48 | dependencyManager.DependenciesReady += (sender, args) => DependenciesReady(); 49 | dependencyManager.Initialise(); 50 | } 51 | 52 | private void DependenciesReady() 53 | { 54 | // Spin up DX handling from the plugin interface 55 | DxHandler.Initialise(pluginInterface); 56 | 57 | // Spin up WndProc hook 58 | WndProcHandler.Initialise(DxHandler.WindowHandle); 59 | WndProcHandler.WndProcMessage += OnWndProc; 60 | 61 | // Boot the render process. This has to be done before initialising settings to prevent a 62 | // race conditionson inlays recieving a null reference. 63 | var pid = Process.GetCurrentProcess().Id; 64 | renderProcess = new RenderProcess(pid, pluginDir, pluginConfigDir, dependencyManager); 65 | renderProcess.Recieve += HandleIpcRequest; 66 | renderProcess.Start(); 67 | 68 | // Prep settings 69 | settings = pluginInterface.Create(); 70 | settings.InlayAdded += OnInlayAdded; 71 | settings.InlayNavigated += OnInlayNavigated; 72 | settings.InlayDebugged += OnInlayDebugged; 73 | settings.InlayRemoved += OnInlayRemoved; 74 | settings.TransportChanged += OnTransportChanged; 75 | settings.Initialise(); 76 | 77 | // Hook up the main BH command 78 | commandManager.AddHandler(COMMAND, new CommandInfo(HandleCommand) 79 | { 80 | HelpMessage = "Control BrowserHost from the chat line! Type '/bh config' or open the settings for more info.", 81 | ShowInHelp = true, 82 | }); 83 | } 84 | 85 | private (bool, long) OnWndProc(WindowsMessage msg, ulong wParam, long lParam) 86 | { 87 | // Notify all the inlays of the wndproc, respond with the first capturing response (if any) 88 | // TODO: Yeah this ain't great but realistically only one will capture at any one time for now. Revisit if shit breaks or something idfk. 89 | var responses = inlays.Select(pair => pair.Value.WndProcMessage(msg, wParam, lParam)); 90 | return responses.FirstOrDefault(pair => pair.Item1); 91 | } 92 | 93 | private void OnInlayAdded(object sender, InlayConfiguration inlayConfig) 94 | { 95 | var inlay = new Inlay(renderProcess, settings.Config, inlayConfig); 96 | inlays.Add(inlayConfig.Guid, inlay); 97 | } 98 | 99 | private void OnInlayNavigated(object sender, InlayConfiguration config) 100 | { 101 | var inlay = inlays[config.Guid]; 102 | inlay.Navigate(config.Url); 103 | } 104 | 105 | private void OnInlayDebugged(object sender, InlayConfiguration config) 106 | { 107 | var inlay = inlays[config.Guid]; 108 | inlay.Debug(); 109 | } 110 | 111 | private void OnInlayRemoved(object sender, InlayConfiguration config) 112 | { 113 | var inlay = inlays[config.Guid]; 114 | inlays.Remove(config.Guid); 115 | inlay.Dispose(); 116 | } 117 | 118 | private void OnTransportChanged(object sender, EventArgs unused) 119 | { 120 | // Transport has changed, need to rebuild all the inlay renderers 121 | foreach (var inlay in inlays.Values) 122 | { 123 | inlay.InvalidateTransport(); 124 | } 125 | } 126 | 127 | private object HandleIpcRequest(object sender, UpstreamIpcRequest request) 128 | { 129 | switch (request) 130 | { 131 | case ReadyNotificationRequest readyNotificationRequest: 132 | { 133 | settings.SetAvailableTransports(readyNotificationRequest.availableTransports); 134 | settings.HydrateInlays(); 135 | return null; 136 | } 137 | 138 | case SetCursorRequest setCursorRequest: 139 | { 140 | // TODO: Integrate ideas from Bridge re: SoC between widget and inlay 141 | var inlay = inlays.Values.Where(inlay => inlay.RenderGuid == setCursorRequest.Guid).FirstOrDefault(); 142 | if (inlay == null) { return null; } 143 | inlay.SetCursor(setCursorRequest.Cursor); 144 | return null; 145 | } 146 | 147 | default: 148 | throw new Exception($"Unknown IPC request type {request.GetType().Name} received."); 149 | } 150 | } 151 | 152 | private void Render() 153 | { 154 | dependencyManager?.Render(); 155 | settings?.Render(); 156 | 157 | ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(0, 0)); 158 | 159 | foreach (var inlay in inlays.Values) { inlay.Render(); } 160 | 161 | ImGui.PopStyleVar(); 162 | } 163 | 164 | private void HandleCommand(string command, string rawArgs) 165 | { 166 | // Docs complain about perf of multiple splits. 167 | // I'm not convinced this is a sufficiently perf-critical path to care. 168 | var args = rawArgs.Split(null as char[], 2, StringSplitOptions.RemoveEmptyEntries); 169 | 170 | if (args.Length == 0) 171 | { 172 | chat.PrintError( 173 | "No subcommand specified. Valid subcommands are: config,inlay."); 174 | return; 175 | } 176 | 177 | var subcommandArgs = args.Length > 1 ? args[1] : ""; 178 | 179 | switch (args[0]) 180 | { 181 | case "config": 182 | settings.HandleConfigCommand(subcommandArgs); 183 | break; 184 | case "inlay": 185 | settings.HandleInlayCommand(subcommandArgs); 186 | break; 187 | default: 188 | chat.PrintError( 189 | $"Unknown subcommand '{args[0]}'. Valid subcommands are: config,inlay."); 190 | break; 191 | } 192 | } 193 | 194 | public void Dispose() 195 | { 196 | foreach (var inlay in inlays.Values) { inlay.Dispose(); } 197 | inlays.Clear(); 198 | 199 | renderProcess?.Dispose(); 200 | 201 | settings?.Dispose(); 202 | 203 | commandManager.RemoveHandler(COMMAND); 204 | 205 | WndProcHandler.Shutdown(); 206 | DxHandler.Shutdown(); 207 | 208 | pluginInterface.Dispose(); 209 | 210 | dependencyManager.Dispose(); 211 | } 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | using System.Runtime.Versioning; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("BrowserHost.Plugin")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("BrowserHost.Plugin")] 13 | [assembly: AssemblyCopyright("Copyright © 2020")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("d047232d-8c20-4185-ac61-78aed2a1ea74")] 24 | 25 | [assembly: SupportedOSPlatform("windows7.0")] 26 | 27 | // Version information for an assembly consists of the following four values: 28 | // 29 | // Major Version 30 | // Minor Version 31 | // Build Number 32 | // Revision 33 | // 34 | // You can specify all the values or you can default the Build and Revision Numbers 35 | // by using the '*' as shown below: 36 | // [assembly: AssemblyVersion("1.0.*")] 37 | [assembly: AssemblyVersion("1.4.1.2")] 38 | [assembly: AssemblyFileVersion("1.4.1.2")] 39 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/RenderProcess.cs: -------------------------------------------------------------------------------- 1 | using BrowserHost.Common; 2 | using Dalamud.Logging; 3 | using System; 4 | using System.Diagnostics; 5 | using System.IO; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | namespace BrowserHost.Plugin 10 | { 11 | class RenderProcess : IDisposable 12 | { 13 | public delegate object RecieveEventHandler(object sender, UpstreamIpcRequest request); 14 | public event RecieveEventHandler Recieve; 15 | 16 | private Process process; 17 | private IpcBuffer ipc; 18 | private bool running; 19 | 20 | private string keepAliveHandleName; 21 | private string ipcChannelName; 22 | 23 | public RenderProcess( 24 | int pid, 25 | string pluginDir, 26 | string configDir, 27 | DependencyManager dependencyManager 28 | ) 29 | { 30 | keepAliveHandleName = $"BrowserHostRendererKeepAlive{pid}"; 31 | ipcChannelName = $"BrowserHostRendererIpcChannel{pid}"; 32 | 33 | ipc = new IpcBuffer(ipcChannelName, request => Recieve?.Invoke(this, request)); 34 | 35 | var cefAssemblyDir = dependencyManager.GetDependencyPathFor("cef"); 36 | var processArgs = new RenderProcessArguments() 37 | { 38 | ParentPid = pid, 39 | DalamudAssemblyDir = Path.GetDirectoryName(typeof(PluginLog).Assembly.Location), 40 | CefAssemblyDir = cefAssemblyDir, 41 | CefCacheDir = Path.Combine(configDir, "cef-cache"), 42 | DxgiAdapterLuid = DxHandler.AdapterLuid, 43 | KeepAliveHandleName = keepAliveHandleName, 44 | IpcChannelName = ipcChannelName, 45 | }; 46 | 47 | process = new Process(); 48 | process.StartInfo = new ProcessStartInfo() 49 | { 50 | FileName = Path.Combine(pluginDir, "renderer", "BrowserHost.Renderer.exe"), 51 | Arguments = processArgs.Serialise().Replace("\"", "\"\"\""), 52 | UseShellExecute = false, 53 | CreateNoWindow = true, 54 | RedirectStandardOutput = true, 55 | RedirectStandardError = true, 56 | }; 57 | 58 | process.OutputDataReceived += (sender, args) => PluginLog.Log($"[Render]: {args.Data}"); 59 | process.ErrorDataReceived += (sender, args) => PluginLog.LogError($"[Render]: {args.Data}"); 60 | } 61 | 62 | public void Start() 63 | { 64 | if (running) { return; } 65 | running = true; 66 | 67 | process.Start(); 68 | process.BeginOutputReadLine(); 69 | process.BeginErrorReadLine(); 70 | } 71 | 72 | public void Send(DownstreamIpcRequest request) { Send(request); } 73 | 74 | // TODO: Option to wrap this func in an async version? 75 | public Task> Send(DownstreamIpcRequest request) 76 | { 77 | return ipc.RemoteRequestAsync(request); 78 | } 79 | 80 | public void Stop() 81 | { 82 | if (!running) { return; } 83 | running = false; 84 | 85 | // Grab the handle the process is waiting on and open it up 86 | var handle = new EventWaitHandle(false, EventResetMode.ManualReset, keepAliveHandleName); 87 | handle.Set(); 88 | handle.Dispose(); 89 | 90 | // Give the process a sec to gracefully shut down, then kill it 91 | process.WaitForExit(1000); 92 | try { process.Kill(); } 93 | catch (InvalidOperationException) { } 94 | } 95 | 96 | public void Dispose() 97 | { 98 | Stop(); 99 | 100 | process.Dispose(); 101 | ipc.Dispose(); 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/Settings.cs: -------------------------------------------------------------------------------- 1 | using BrowserHost.Common; 2 | using Dalamud.Game.Gui; 3 | using Dalamud.Interface; 4 | using Dalamud.IoC; 5 | using Dalamud.Plugin; 6 | using ImGuiNET; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Numerics; 11 | using System.Text.RegularExpressions; 12 | using System.Threading; 13 | 14 | namespace BrowserHost.Plugin 15 | { 16 | class Settings : IDisposable 17 | { 18 | public event EventHandler InlayAdded; 19 | public event EventHandler InlayNavigated; 20 | public event EventHandler InlayDebugged; 21 | public event EventHandler InlayRemoved; 22 | public event EventHandler TransportChanged; 23 | 24 | public Configuration Config; 25 | 26 | [PluginService] private static DalamudPluginInterface pluginInterface { get; set; } 27 | [PluginService] private static ChatGui chat { get; set; } 28 | 29 | #if DEBUG 30 | private bool open = true; 31 | #else 32 | private bool open = false; 33 | #endif 34 | 35 | private List availableTransports = new List(); 36 | 37 | InlayConfiguration selectedInlay = null; 38 | private Timer saveDebounceTimer; 39 | 40 | public Settings() 41 | { 42 | pluginInterface.UiBuilder.OpenConfigUi += () => open = true; 43 | } 44 | 45 | public void Initialise() 46 | { 47 | Config = pluginInterface.GetPluginConfig() as Configuration ?? new Configuration(); 48 | } 49 | 50 | public void Dispose() { } 51 | 52 | public void HandleConfigCommand(string rawArgs) 53 | { 54 | open = true; 55 | 56 | // TODO: Add further config handling if required here. 57 | } 58 | 59 | public void HandleInlayCommand(string rawArgs) 60 | { 61 | var args = rawArgs.Split(null as char[], 3, StringSplitOptions.RemoveEmptyEntries); 62 | 63 | // Ensure there's enough arguments 64 | if (args.Length < 3) 65 | { 66 | chat.PrintError( 67 | "Invalid inlay command. Supported syntax: '[inlayCommandName] [setting] [value]'"); 68 | return; 69 | } 70 | 71 | // Find the matching inlay config 72 | var targetConfig = Config.Inlays.Find(inlay => GetInlayCommandName(inlay) == args[0]); 73 | if (targetConfig == null) 74 | { 75 | chat.PrintError( 76 | $"Unknown inlay '{args[0]}'."); 77 | return; 78 | } 79 | 80 | switch (args[1]) 81 | { 82 | case "url": 83 | CommandSettingString(args[2], ref targetConfig.Url); 84 | // TODO: This call is duped with imgui handling. DRY. 85 | NavigateInlay(targetConfig); 86 | break; 87 | case "locked": 88 | CommandSettingBoolean(args[2], ref targetConfig.Locked); 89 | break; 90 | case "hidden": 91 | CommandSettingBoolean(args[2], ref targetConfig.Hidden); 92 | break; 93 | case "typethrough": 94 | CommandSettingBoolean(args[2], ref targetConfig.TypeThrough); 95 | break; 96 | case "clickthrough": 97 | CommandSettingBoolean(args[2], ref targetConfig.ClickThrough); 98 | break; 99 | default: 100 | chat.PrintError( 101 | $"Unknown setting '{args[1]}. Valid settings are: url,hidden,locked,clickthrough."); 102 | return; 103 | } 104 | 105 | SaveSettings(); 106 | } 107 | 108 | private void CommandSettingString(string value, ref string target) 109 | { 110 | target = value; 111 | } 112 | 113 | private void CommandSettingBoolean(string value, ref bool target) 114 | { 115 | switch (value) 116 | { 117 | case "on": 118 | target = true; 119 | break; 120 | case "off": 121 | target = false; 122 | break; 123 | case "toggle": 124 | target = !target; 125 | break; 126 | default: 127 | chat.PrintError( 128 | $"Unknown boolean value '{value}. Valid values are: on,off,toggle."); 129 | break; 130 | } 131 | } 132 | 133 | public void SetAvailableTransports(FrameTransportMode transports) 134 | { 135 | // Decode bit flags to array for easier ui crap 136 | availableTransports = Enum.GetValues(typeof(FrameTransportMode)) 137 | .Cast() 138 | .Where(transport => transport != FrameTransportMode.None && transports.HasFlag(transport)) 139 | .ToList(); 140 | 141 | // If the configured transport isn't available, pick the first so we don't end up in a weird spot. 142 | // NOTE: Might be nice to avoid saving this to disc - a one-off failure may cause a save of full fallback mode. 143 | if (availableTransports.Count > 0 && !availableTransports.Contains(Config.FrameTransportMode)) 144 | { 145 | SetActiveTransport(availableTransports[0]); 146 | } 147 | } 148 | 149 | public void HydrateInlays() 150 | { 151 | // Hydrate any inlays in the config 152 | foreach (var inlayConfig in Config.Inlays) 153 | { 154 | InlayAdded?.Invoke(this, inlayConfig); 155 | } 156 | } 157 | 158 | private InlayConfiguration AddNewInlay() 159 | { 160 | var inlayConfig = new InlayConfiguration() 161 | { 162 | Guid = Guid.NewGuid(), 163 | Name = "New inlay", 164 | Url = "about:blank", 165 | }; 166 | Config.Inlays.Add(inlayConfig); 167 | InlayAdded?.Invoke(this, inlayConfig); 168 | SaveSettings(); 169 | 170 | return inlayConfig; 171 | } 172 | 173 | private void NavigateInlay(InlayConfiguration inlayConfig) 174 | { 175 | if (inlayConfig.Url == "") { inlayConfig.Url = "about:blank"; } 176 | InlayNavigated?.Invoke(this, inlayConfig); 177 | } 178 | 179 | private void ReloadInlay(InlayConfiguration inlayConfig) { NavigateInlay(inlayConfig); } 180 | 181 | private void DebugInlay(InlayConfiguration inlayConfig) 182 | { 183 | InlayDebugged?.Invoke(this, inlayConfig); 184 | } 185 | 186 | private void RemoveInlay(InlayConfiguration inlayConfig) 187 | { 188 | InlayRemoved?.Invoke(this, inlayConfig); 189 | Config.Inlays.Remove(inlayConfig); 190 | SaveSettings(); 191 | } 192 | 193 | private void SetActiveTransport(FrameTransportMode transport) 194 | { 195 | Config.FrameTransportMode = transport; 196 | TransportChanged?.Invoke(this, null); 197 | } 198 | 199 | private void DebouncedSaveSettings() 200 | { 201 | saveDebounceTimer?.Dispose(); 202 | saveDebounceTimer = new Timer(_ => SaveSettings(), null, 1000, Timeout.Infinite); 203 | } 204 | 205 | private void SaveSettings() 206 | { 207 | saveDebounceTimer?.Dispose(); 208 | saveDebounceTimer = null; 209 | pluginInterface.SavePluginConfig(Config); 210 | } 211 | 212 | private string GetInlayCommandName(InlayConfiguration inlayConfig) 213 | { 214 | return Regex.Replace(inlayConfig.Name, @"\s+", "").ToLower(); 215 | } 216 | 217 | public void Render() 218 | { 219 | if (!open || Config == null) { return; } 220 | 221 | // Primary window container 222 | ImGui.SetNextWindowSizeConstraints(new Vector2(400, 300), new Vector2(9001, 9001)); 223 | var windowFlags = ImGuiWindowFlags.None 224 | | ImGuiWindowFlags.NoScrollbar 225 | | ImGuiWindowFlags.NoScrollWithMouse 226 | | ImGuiWindowFlags.NoCollapse; 227 | ImGui.Begin("BrowserHost Settings", ref open, windowFlags); 228 | 229 | RenderPaneSelector(); 230 | 231 | // Pane details 232 | var dirty = false; 233 | ImGui.SameLine(); 234 | ImGui.BeginChild("details"); 235 | if (selectedInlay == null) 236 | { 237 | dirty |= RenderGeneralSettings(); 238 | } 239 | else 240 | { 241 | dirty |= RenderInlaySettings(selectedInlay); 242 | } 243 | ImGui.EndChild(); 244 | 245 | if (dirty) { DebouncedSaveSettings(); } 246 | 247 | ImGui.End(); 248 | } 249 | 250 | private void RenderPaneSelector() 251 | { 252 | // Selector pane 253 | ImGui.BeginGroup(); 254 | ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0)); 255 | 256 | var selectorWidth = 100; 257 | ImGui.BeginChild("panes", new Vector2(selectorWidth, -ImGui.GetFrameHeightWithSpacing()), true); 258 | 259 | // General settings 260 | if (ImGui.Selectable($"General", selectedInlay == null)) 261 | { 262 | selectedInlay = null; 263 | } 264 | 265 | // Inlay selector list 266 | ImGui.Dummy(new Vector2(0, 5)); 267 | ImGui.PushStyleVar(ImGuiStyleVar.Alpha, 0.5f); 268 | ImGui.Text("- Inlays -"); 269 | ImGui.PopStyleVar(); 270 | foreach (var inlayConfig in Config.Inlays) 271 | { 272 | if (ImGui.Selectable($"{inlayConfig.Name}##{inlayConfig.Guid}", selectedInlay == inlayConfig)) 273 | { 274 | selectedInlay = inlayConfig; 275 | } 276 | } 277 | ImGui.EndChild(); 278 | 279 | // Selector controls 280 | ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 0); 281 | ImGui.PushFont(UiBuilder.IconFont); 282 | 283 | var buttonWidth = selectorWidth / 2; 284 | if (ImGui.Button(FontAwesomeIcon.Plus.ToIconString(), new Vector2(buttonWidth, 0))) 285 | { 286 | selectedInlay = AddNewInlay(); 287 | } 288 | 289 | ImGui.SameLine(); 290 | if (selectedInlay != null) 291 | { 292 | if (ImGui.Button(FontAwesomeIcon.Trash.ToIconString(), new Vector2(buttonWidth, 0))) 293 | { 294 | var toRemove = selectedInlay; 295 | selectedInlay = null; 296 | RemoveInlay(toRemove); 297 | } 298 | } 299 | else 300 | { 301 | ImGui.PushStyleVar(ImGuiStyleVar.Alpha, 0.5f); 302 | ImGui.Button(FontAwesomeIcon.Trash.ToIconString(), new Vector2(buttonWidth, 0)); 303 | ImGui.PopStyleVar(); 304 | } 305 | 306 | ImGui.PopFont(); 307 | ImGui.PopStyleVar(2); 308 | 309 | ImGui.EndGroup(); 310 | } 311 | 312 | private bool RenderGeneralSettings() 313 | { 314 | var dirty = false; 315 | 316 | ImGui.Text("Select an inlay on the left to edit its settings."); 317 | 318 | if (ImGui.CollapsingHeader("Command Help", ImGuiTreeNodeFlags.DefaultOpen)) 319 | { 320 | // TODO: If this ever gets more than a few options, should probably colocate help with the defintion. Attributes? 321 | ImGui.Text("/bh config"); 322 | ImGui.Text("Open this configuration window."); 323 | ImGui.Dummy(new Vector2(0, 5)); 324 | ImGui.Text("/bh inlay [inlayCommandName] [setting] [value]"); 325 | ImGui.TextWrapped( 326 | "Change a setting for an inlay.\n" + 327 | "\tinlayCommandName: The inlay to edit. Use the 'Command Name' shown in its config.\n" + 328 | "\tsetting: Value to change. Accepted settings are:\n" + 329 | "\t\turl: string\n" + 330 | "\t\tlocked: boolean\n" + 331 | "\t\thidden: boolean\n" + 332 | "\t\ttypethrough: boolean\n" + 333 | "\t\tclickthrough: boolean\n" + 334 | "\tvalue: Value to set for the setting. Accepted values are:\n" + 335 | "\t\tstring: any string value\n\t\tboolean: on, off, toggle"); 336 | } 337 | 338 | if (ImGui.CollapsingHeader("Advanced Settings")) 339 | { 340 | var options = availableTransports.Select(transport => transport.ToString()); 341 | var currentIndex = availableTransports.IndexOf(Config.FrameTransportMode); 342 | 343 | if (availableTransports.Count == 0) 344 | { 345 | options = options.Append("Initialising..."); 346 | currentIndex = 0; 347 | } 348 | 349 | if (options.Count() <= 1) { ImGui.PushStyleVar(ImGuiStyleVar.Alpha, 0.5f); } 350 | var transportChanged = ImGui.Combo("Frame transport", ref currentIndex, options.ToArray(), options.Count()); 351 | if (options.Count() <= 1) { ImGui.PopStyleVar(); } 352 | 353 | // TODO: Flipping this should probably try to rebuild existing inlays 354 | dirty |= transportChanged; 355 | if (transportChanged) 356 | { 357 | SetActiveTransport(availableTransports[currentIndex]); 358 | } 359 | 360 | if (Config.FrameTransportMode == FrameTransportMode.BitmapBuffer) 361 | { 362 | ImGui.PushStyleColor(ImGuiCol.Text, 0xFF0000FF); 363 | ImGui.TextWrapped("The bitmap buffer frame transport is a fallback, and should only be used if no other options work for you. It is not as stable as the shared texture option."); 364 | ImGui.PopStyleColor(); 365 | } 366 | } 367 | 368 | return dirty; 369 | } 370 | 371 | private bool RenderInlaySettings(InlayConfiguration inlayConfig) 372 | { 373 | var dirty = false; 374 | 375 | ImGui.PushID(inlayConfig.Guid.ToString()); 376 | 377 | dirty |= ImGui.InputText("Name", ref inlayConfig.Name, 100); 378 | 379 | ImGui.PushStyleVar(ImGuiStyleVar.Alpha, 0.5f); 380 | var commandName = GetInlayCommandName(inlayConfig); 381 | ImGui.InputText("Command Name", ref commandName, 100); 382 | ImGui.PopStyleVar(); 383 | 384 | dirty |= ImGui.InputText("URL", ref inlayConfig.Url, 1000); 385 | if (ImGui.IsItemDeactivatedAfterEdit()) { NavigateInlay(inlayConfig); } 386 | 387 | ImGui.SetNextItemWidth(100); 388 | ImGui.Columns(2, "boolInlayOptions", false); 389 | 390 | var true_ = true; 391 | if (inlayConfig.ClickThrough) { ImGui.PushStyleVar(ImGuiStyleVar.Alpha, 0.5f); } 392 | dirty |= ImGui.Checkbox("Locked", ref inlayConfig.ClickThrough ? ref true_ : ref inlayConfig.Locked); 393 | if (inlayConfig.ClickThrough) { ImGui.PopStyleVar(); } 394 | if (ImGui.IsItemHovered()) { ImGui.SetTooltip("Prevent the inlay from being resized or moved. This is implicitly set by Click Through."); } 395 | ImGui.NextColumn(); 396 | 397 | dirty |= ImGui.Checkbox("Hidden", ref inlayConfig.Hidden); 398 | if (ImGui.IsItemHovered()) { ImGui.SetTooltip("Hide the inlay. This does not stop the inlay from executing, only from being displayed."); } 399 | ImGui.NextColumn(); 400 | 401 | 402 | if (inlayConfig.ClickThrough) { ImGui.PushStyleVar(ImGuiStyleVar.Alpha, 0.5f); } 403 | dirty |= ImGui.Checkbox("Type Through", ref inlayConfig.ClickThrough ? ref true_ : ref inlayConfig.TypeThrough); 404 | if (inlayConfig.ClickThrough) { ImGui.PopStyleVar(); } 405 | if (ImGui.IsItemHovered()) { ImGui.SetTooltip("Prevent the inlay from intercepting any keyboard events. Implicitly set by Click Through."); } 406 | ImGui.NextColumn(); 407 | 408 | dirty |= ImGui.Checkbox("Click Through", ref inlayConfig.ClickThrough); 409 | if (ImGui.IsItemHovered()) { ImGui.SetTooltip("Prevent the inlay from intercepting any mouse events. Implicitly sets Locked and Type Through."); } 410 | ImGui.NextColumn(); 411 | 412 | ImGui.Columns(1); 413 | 414 | if (ImGui.Button("Reload")) { ReloadInlay(inlayConfig); } 415 | 416 | ImGui.SameLine(); 417 | if (ImGui.Button("Open Dev Tools")) { DebugInlay(inlayConfig); } 418 | 419 | ImGui.PopID(); 420 | 421 | return dirty; 422 | } 423 | } 424 | } 425 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/TextureHandlers/BitmapBufferTextureHandler.cs: -------------------------------------------------------------------------------- 1 | using BrowserHost.Common; 2 | using ImGuiNET; 3 | using ImGuiScene; 4 | using SharedMemory; 5 | using D3D = SharpDX.Direct3D; 6 | using D3D11 = SharpDX.Direct3D11; 7 | using DXGI = SharpDX.DXGI; 8 | using System; 9 | using System.Numerics; 10 | using System.Threading; 11 | using System.Collections.Concurrent; 12 | 13 | namespace BrowserHost.Plugin.TextureHandlers 14 | { 15 | class BitmapBufferTextureHandler : ITextureHandler 16 | { 17 | private Thread frameBufferThread; 18 | private CancellationTokenSource cancellationTokenSource; 19 | private D3D11.Texture2D texture; 20 | private TextureWrap textureWrap; 21 | 22 | private BufferReadWrite bitmapBuffer; 23 | private ConcurrentQueue frameQueue = new ConcurrentQueue(); 24 | 25 | public BitmapBufferTextureHandler(BitmapBufferResponse response) 26 | { 27 | cancellationTokenSource = new CancellationTokenSource(); 28 | frameBufferThread = new Thread(FrameBufferThread); 29 | frameBufferThread.Start(new ThreadArguments() 30 | { 31 | BufferName = response.FrameInfoBufferName, 32 | CancellationToken = cancellationTokenSource.Token, 33 | }); 34 | 35 | bitmapBuffer = new BufferReadWrite(response.BitmapBufferName); 36 | } 37 | 38 | public void Dispose() 39 | { 40 | cancellationTokenSource.Cancel(); 41 | cancellationTokenSource.Dispose(); 42 | if (!(texture?.IsDisposed ?? true)) { texture.Dispose(); } 43 | textureWrap?.Dispose(); 44 | bitmapBuffer.Dispose(); 45 | } 46 | 47 | public void Render() 48 | { 49 | // Render incoming frame info on the queue. Doing a queue swap to prevent edge cases where a slow game 50 | // paired with a fast renderer will loop dequeue infinitely. 51 | var currentFrameQueue = frameQueue; 52 | frameQueue = new ConcurrentQueue(); 53 | while (currentFrameQueue.TryDequeue(out BitmapFrame frame)) 54 | { 55 | RenderFrame(frame); 56 | } 57 | 58 | if (textureWrap == null) { return; } 59 | 60 | ImGui.Image(textureWrap.ImGuiHandle, new Vector2(textureWrap.Width, textureWrap.Height)); 61 | } 62 | 63 | private void RenderFrame(BitmapFrame frame) 64 | { 65 | // Make sure there's a texture to render to 66 | // TODO: Can probably afford to remove width/height from frame, and just add the buffer name. this client code can then check that the buffer name matches what it expects, and noop if it doesn't 67 | if (texture == null) 68 | { 69 | BuildTexture(frame.Width, frame.Height); 70 | } 71 | 72 | // If the details don't match our expected sizes, noop the frame to avoid a CTD. 73 | // This may "stick" and cause no rendering at all, but can be fixed by jiggling the size a bit, or reloading. 74 | if ( 75 | texture.Description.Width != frame.Width 76 | || texture.Description.Height != frame.Height 77 | || bitmapBuffer.BufferSize != frame.Length 78 | ) { 79 | return; 80 | } 81 | 82 | // Calculate multipliers for the frame 83 | var depthPitch = frame.Length; 84 | var rowPitch = frame.Length / frame.Height; 85 | var bytesPerPixel = rowPitch / frame.Width; 86 | 87 | // Build the destination region for the dirty rect we're drawing 88 | var texDesc = texture.Description; 89 | var sourceRegionOffset = (frame.DirtyX * bytesPerPixel) + (frame.DirtyY * rowPitch); 90 | var destinationRegion = new D3D11.ResourceRegion() 91 | { 92 | Top = Math.Min(frame.DirtyY, texDesc.Height), 93 | Bottom = Math.Min(frame.DirtyY + frame.DirtyHeight, texDesc.Height), 94 | Left = Math.Min(frame.DirtyX, texDesc.Width), 95 | Right = Math.Min(frame.DirtyX + frame.DirtyWidth, texDesc.Width), 96 | Front = 0, 97 | Back = 1, 98 | }; 99 | 100 | // Write data from the buffer 101 | var context = DxHandler.Device.ImmediateContext; 102 | bitmapBuffer.Read(ptr => 103 | { 104 | context.UpdateSubresource(texture, 0, destinationRegion, ptr + sourceRegionOffset, rowPitch, depthPitch); 105 | }); 106 | } 107 | 108 | private void BuildTexture(int width, int height) 109 | { 110 | // TODO: This should probably be a dynamic texture, with updates performed via mapping. Work it out. 111 | texture = new D3D11.Texture2D(DxHandler.Device, new D3D11.Texture2DDescription() 112 | { 113 | Width = width, 114 | Height = height, 115 | MipLevels = 1, 116 | ArraySize = 1, 117 | Format = DXGI.Format.B8G8R8A8_UNorm, 118 | SampleDescription = new DXGI.SampleDescription(1, 0), 119 | Usage = D3D11.ResourceUsage.Default, 120 | //Usage = D3D11.ResourceUsage.Dynamic, 121 | BindFlags = D3D11.BindFlags.ShaderResource, 122 | CpuAccessFlags = D3D11.CpuAccessFlags.None, 123 | //CpuAccessFlags = D3D11.CpuAccessFlags.Write, 124 | OptionFlags = D3D11.ResourceOptionFlags.None, 125 | }); 126 | 127 | var view = new D3D11.ShaderResourceView(DxHandler.Device, texture, new D3D11.ShaderResourceViewDescription() 128 | { 129 | Format = texture.Description.Format, 130 | Dimension = D3D.ShaderResourceViewDimension.Texture2D, 131 | Texture2D = { MipLevels = texture.Description.MipLevels }, 132 | }); 133 | 134 | textureWrap = new D3DTextureWrap(view, texture.Description.Width, texture.Description.Height); 135 | } 136 | 137 | struct ThreadArguments 138 | { 139 | public string BufferName; 140 | public CancellationToken CancellationToken; 141 | } 142 | 143 | private void FrameBufferThread(object arguments) 144 | { 145 | var args = (ThreadArguments)arguments; 146 | // Open up a reference to the frame info buffer 147 | using var frameInfoBuffer = new CircularBuffer(args.BufferName); 148 | 149 | // We're just looping the blocking read operation forever. Parent will abort the to shut down. 150 | while (true) 151 | { 152 | args.CancellationToken.ThrowIfCancellationRequested(); 153 | 154 | frameInfoBuffer.Read(out BitmapFrame frame, timeout: Timeout.Infinite); 155 | frameQueue.Enqueue(frame); 156 | } 157 | } 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/TextureHandlers/ITextureHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace BrowserHost.Plugin.TextureHandlers 4 | { 5 | interface ITextureHandler : IDisposable 6 | { 7 | public void Render(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/TextureHandlers/SharedTextureHandler.cs: -------------------------------------------------------------------------------- 1 | using ImGuiScene; 2 | using D3D = SharpDX.Direct3D; 3 | using D3D11 = SharpDX.Direct3D11; 4 | using System; 5 | using System.Numerics; 6 | using ImGuiNET; 7 | using BrowserHost.Common; 8 | 9 | namespace BrowserHost.Plugin.TextureHandlers 10 | { 11 | class SharedTextureHandler : ITextureHandler 12 | { 13 | private TextureWrap textureWrap; 14 | 15 | public SharedTextureHandler(TextureHandleResponse response) 16 | { 17 | var texture = DxHandler.Device.OpenSharedResource(response.TextureHandle); 18 | var view = new D3D11.ShaderResourceView(DxHandler.Device, texture, new D3D11.ShaderResourceViewDescription() 19 | { 20 | Format = texture.Description.Format, 21 | Dimension = D3D.ShaderResourceViewDimension.Texture2D, 22 | Texture2D = { MipLevels = texture.Description.MipLevels }, 23 | }); 24 | 25 | textureWrap = new D3DTextureWrap(view, texture.Description.Width, texture.Description.Height); 26 | } 27 | 28 | public void Dispose() 29 | { 30 | textureWrap.Dispose(); 31 | } 32 | 33 | public void Render() 34 | { 35 | if (textureWrap == null) { return; } 36 | 37 | ImGui.Image(textureWrap.ImGuiHandle, new Vector2(textureWrap.Width, textureWrap.Height)); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/WndProcHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace BrowserHost.Plugin 5 | { 6 | class WndProcHandler 7 | { 8 | public delegate (bool, long) WndProcMessageDelegate(WindowsMessage msg, ulong wParam, long lParam); 9 | public static event WndProcMessageDelegate WndProcMessage; 10 | 11 | public delegate long WndProcDelegate(IntPtr hWnd, uint msg, ulong wParam, long lParam); 12 | private static WndProcDelegate wndProcDelegate; 13 | 14 | private static IntPtr hWnd; 15 | private static IntPtr oldWndProcPtr; 16 | private static IntPtr detourPtr; 17 | 18 | public static void Initialise(IntPtr hWnd) 19 | { 20 | WndProcHandler.hWnd = hWnd; 21 | 22 | wndProcDelegate = WndProcDetour; 23 | detourPtr = Marshal.GetFunctionPointerForDelegate(wndProcDelegate); 24 | oldWndProcPtr = NativeMethods.SetWindowLongPtr(hWnd, WindowLongType.GWL_WNDPROC, detourPtr); 25 | } 26 | 27 | public static void Shutdown() 28 | { 29 | // If the current pointer doesn't match our detour, something swapped the pointer out from under us - 30 | // likely the InterfaceManager doing its own cleanup. Don't reset in that case, we'll trust the cleanup 31 | // is accurate. 32 | var curWndProcPtr = NativeMethods.GetWindowLongPtr(hWnd, WindowLongType.GWL_WNDPROC); 33 | if (oldWndProcPtr != IntPtr.Zero && curWndProcPtr == detourPtr) 34 | { 35 | NativeMethods.SetWindowLongPtr(hWnd, WindowLongType.GWL_WNDPROC, oldWndProcPtr); 36 | oldWndProcPtr = IntPtr.Zero; 37 | } 38 | } 39 | 40 | private static long WndProcDetour(IntPtr hWnd, uint msg, ulong wParam, long lParam) 41 | { 42 | // Ignore things not targeting the current window handle 43 | if (hWnd == WndProcHandler.hWnd) 44 | { 45 | var resp = WndProcMessage?.Invoke((WindowsMessage)msg, wParam, lParam); 46 | 47 | // Item1 is a bool, where true == capture event. If false, we're falling through default handling. 48 | if (resp.HasValue && resp.Value.Item1) 49 | { 50 | return resp.Value.Item2; 51 | } 52 | } 53 | 54 | return NativeMethods.CallWindowProc(oldWndProcPtr, hWnd, msg, wParam, lParam); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /BrowserHost.Plugin/images/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ackwell/BrowserHost/113910d39fc8ec3eda3806a5a210b1b5579322a7/BrowserHost.Plugin/images/icon.png -------------------------------------------------------------------------------- /BrowserHost.Plugin/images/image1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ackwell/BrowserHost/113910d39fc8ec3eda3806a5a210b1b5579322a7/BrowserHost.Plugin/images/image1.png -------------------------------------------------------------------------------- /BrowserHost.Renderer/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /BrowserHost.Renderer/BrowserHost.Renderer.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | Debug 9 | AnyCPU 10 | {A9B66761-A607-4B6C-B80E-33A96BB16D14} 11 | Exe 12 | BrowserHost.Renderer 13 | BrowserHost.Renderer 14 | v4.8 15 | 8.0 16 | 512 17 | true 18 | true 19 | ..\..\cef 20 | 21 | 22 | publish\ 23 | true 24 | Disk 25 | false 26 | Foreground 27 | 7 28 | Days 29 | false 30 | false 31 | true 32 | 0 33 | 1.0.0.%2a 34 | false 35 | false 36 | true 37 | 38 | 39 | ..\bin\Release\plugin\renderer\ 40 | x64 41 | false 42 | true 43 | TRACE 44 | none 45 | false 46 | 47 | 48 | false 49 | x64 50 | ..\bin\Debug\plugin\renderer\ 51 | TRACE;DEBUG 52 | 53 | 54 | 55 | ..\packages\CefSharp.Common.89.0.170\lib\net452\CefSharp.dll 56 | 57 | 58 | ..\packages\CefSharp.Common.89.0.170\lib\net452\CefSharp.Core.dll 59 | 60 | 61 | ..\packages\CefSharp.OffScreen.89.0.170\lib\net452\CefSharp.OffScreen.dll 62 | 63 | 64 | ..\packages\SharedMemory.2.2.3\lib\net47\SharedMemory.dll 65 | 66 | 67 | $(AppData)\XIVLauncher\addon\Hooks\dev\SharpDX.dll 68 | False 69 | 70 | 71 | $(AppData)\XIVLauncher\addon\Hooks\dev\SharpDX.Direct3D11.dll 72 | False 73 | 74 | 75 | $(AppData)\XIVLauncher\addon\Hooks\dev\SharpDX.DXGI.dll 76 | False 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | {9ec3f19a-cea0-44bd-b55c-fecf7d02cc6b} 106 | BrowserHost.Common 107 | True 108 | 109 | 110 | 111 | 112 | False 113 | Microsoft .NET Framework 4.8 %28x86 and x64%29 114 | true 115 | 116 | 117 | False 118 | .NET Framework 3.5 SP1 119 | false 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /BrowserHost.Renderer/CefHandler.cs: -------------------------------------------------------------------------------- 1 | using CefSharp; 2 | using CefSharp.OffScreen; 3 | using System.IO; 4 | 5 | namespace BrowserHost.Renderer 6 | { 7 | static class CefHandler 8 | { 9 | public static void Initialise(string cefAssemblyPath, string cefCacheDir) 10 | { 11 | var settings = new CefSettings() 12 | { 13 | BrowserSubprocessPath = Path.Combine(cefAssemblyPath, "CefSharp.BrowserSubprocess.exe"), 14 | CachePath = cefCacheDir, 15 | #if !DEBUG 16 | LogSeverity = LogSeverity.Fatal, 17 | #endif 18 | }; 19 | settings.CefCommandLineArgs["autoplay-policy"] = "no-user-gesture-required"; 20 | settings.EnableAudio(); 21 | settings.SetOffScreenRenderingBestPerformanceArgs(); 22 | 23 | Cef.Initialize(settings, performDependencyCheck: false, browserProcessHandler: null); 24 | } 25 | 26 | public static void Shutdown() 27 | { 28 | Cef.Shutdown(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /BrowserHost.Renderer/DxHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using D3D11 = SharpDX.Direct3D11; 4 | using DXGI = SharpDX.DXGI; 5 | 6 | namespace BrowserHost.Renderer 7 | { 8 | static class DxHandler 9 | { 10 | public static D3D11.Device Device { get; private set; } 11 | 12 | public static bool Initialise(long adapterLuid) 13 | { 14 | // Find the adapter matching the luid from the parent process 15 | var factory = new DXGI.Factory1(); 16 | DXGI.Adapter gameAdapter = null; 17 | foreach (var adapter in factory.Adapters) 18 | { 19 | if (adapter.Description.Luid == adapterLuid) 20 | { 21 | gameAdapter = adapter; 22 | break; 23 | } 24 | } 25 | if (gameAdapter == null) 26 | { 27 | var foundLuids = string.Join(",", factory.Adapters.Select(adapter => adapter.Description.Luid)); 28 | Console.Error.WriteLine($"FATAL: Could not find adapter matching game adapter LUID {adapterLuid}. Found: {foundLuids}."); 29 | return false; 30 | } 31 | 32 | // Use the adapter to build the device we'll use 33 | var flags = D3D11.DeviceCreationFlags.BgraSupport; 34 | #if DEBUG 35 | flags |= D3D11.DeviceCreationFlags.Debug; 36 | #endif 37 | 38 | Device = new D3D11.Device(gameAdapter, flags); 39 | 40 | return true; 41 | } 42 | 43 | public static void Shutdown() 44 | { 45 | Device.Dispose(); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /BrowserHost.Renderer/Inlay.cs: -------------------------------------------------------------------------------- 1 | using BrowserHost.Common; 2 | using BrowserHost.Renderer.RenderHandlers; 3 | using CefSharp; 4 | using CefSharp.OffScreen; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Drawing; 8 | 9 | namespace BrowserHost.Renderer 10 | { 11 | class Inlay : IDisposable 12 | { 13 | private string url; 14 | 15 | private ChromiumWebBrowser browser; 16 | public BaseRenderHandler RenderHandler; 17 | 18 | public Inlay(string url, BaseRenderHandler renderHandler) 19 | { 20 | this.url = url; 21 | RenderHandler = renderHandler; 22 | } 23 | 24 | public void Initialise() 25 | { 26 | browser = new ChromiumWebBrowser(url, automaticallyCreateBrowser: false); 27 | browser.RenderHandler = RenderHandler; 28 | var size = RenderHandler.GetViewRect(); 29 | 30 | // General browser config 31 | var windowInfo = new WindowInfo() 32 | { 33 | Width = size.Width, 34 | Height = size.Height, 35 | }; 36 | windowInfo.SetAsWindowless(IntPtr.Zero); 37 | 38 | // WindowInfo gets ignored sometimes, be super sure: 39 | browser.BrowserInitialized += (sender, args) => { browser.Size = new Size(size.Width, size.Height); }; 40 | 41 | var browserSettings = new BrowserSettings() 42 | { 43 | WindowlessFrameRate = 60, 44 | }; 45 | 46 | // Ready, boot up the browser 47 | browser.CreateBrowser(windowInfo, browserSettings); 48 | 49 | browserSettings.Dispose(); 50 | windowInfo.Dispose(); 51 | } 52 | 53 | public void Dispose() 54 | { 55 | browser.RenderHandler = null; 56 | RenderHandler.Dispose(); 57 | browser.Dispose(); 58 | } 59 | 60 | public void Navigate(string newUrl) 61 | { 62 | // If navigating to the same url, force a clean reload 63 | if (browser.Address == newUrl) 64 | { 65 | browser.Reload(true); 66 | return; 67 | } 68 | 69 | // Otherwise load regularly 70 | url = newUrl; 71 | browser.Load(newUrl); 72 | } 73 | 74 | public void Debug() 75 | { 76 | browser.ShowDevTools(); 77 | } 78 | 79 | public void HandleMouseEvent(MouseEventRequest request) 80 | { 81 | // If the browser isn't ready yet, noop 82 | if (browser == null || !browser.IsBrowserInitialized) { return; } 83 | 84 | var cursorX = (int)request.X; 85 | var cursorY = (int)request.Y; 86 | 87 | // Update the renderer's concept of the mouse cursor 88 | RenderHandler.SetMousePosition(cursorX, cursorY); 89 | 90 | var event_ = new MouseEvent(cursorX, cursorY, DecodeInputModifier(request.Modifier)); 91 | 92 | var host = browser.GetBrowserHost(); 93 | 94 | // Ensure the mouse position is up to date 95 | host.SendMouseMoveEvent(event_, request.Leaving); 96 | 97 | // Fire any relevant click events 98 | var doubleClicks = DecodeMouseButtons(request.Double); 99 | DecodeMouseButtons(request.Down) 100 | .ForEach(button => host.SendMouseClickEvent(event_, button, false, doubleClicks.Contains(button) ? 2 : 1)); 101 | DecodeMouseButtons(request.Up).ForEach(button => host.SendMouseClickEvent(event_, button, true, 1)); 102 | 103 | // CEF treats the wheel delta as mode 0, pixels. Bump up the numbers to match typical in-browser experience. 104 | var deltaMult = 100; 105 | host.SendMouseWheelEvent(event_, (int)request.WheelX * deltaMult, (int)request.WheelY * deltaMult); 106 | } 107 | 108 | public void HandleKeyEvent(KeyEventRequest request) 109 | { 110 | var type = request.Type switch 111 | { 112 | Common.KeyEventType.KeyDown => CefSharp.KeyEventType.RawKeyDown, 113 | Common.KeyEventType.KeyUp => CefSharp.KeyEventType.KeyUp, 114 | Common.KeyEventType.Character => CefSharp.KeyEventType.Char, 115 | _ => throw new ArgumentException($"Invalid KeyEventType {request.Type}") 116 | }; 117 | 118 | browser.GetBrowserHost().SendKeyEvent(new KeyEvent() 119 | { 120 | Type = type, 121 | Modifiers = DecodeInputModifier(request.Modifier), 122 | WindowsKeyCode = request.UserKeyCode, 123 | NativeKeyCode = request.NativeKeyCode, 124 | IsSystemKey = request.SystemKey, 125 | }); 126 | } 127 | 128 | public void Resize(Size size) 129 | { 130 | // Need to resize renderer first, the browser will check it (and hence the texture) when browser.Size is set. 131 | RenderHandler.Resize(size); 132 | browser.Size = size; 133 | } 134 | 135 | private List DecodeMouseButtons(MouseButton buttons) 136 | { 137 | var result = new List(); 138 | if ((buttons & MouseButton.Primary) == MouseButton.Primary) { result.Add(MouseButtonType.Left); } 139 | if ((buttons & MouseButton.Secondary) == MouseButton.Secondary) { result.Add(MouseButtonType.Right); } 140 | if ((buttons & MouseButton.Tertiary) == MouseButton.Tertiary) { result.Add(MouseButtonType.Middle); } 141 | return result; 142 | } 143 | 144 | private CefEventFlags DecodeInputModifier(InputModifier modifier) 145 | { 146 | var result = CefEventFlags.None; 147 | if ((modifier & InputModifier.Shift) == InputModifier.Shift) { result |= CefEventFlags.ShiftDown; } 148 | if ((modifier & InputModifier.Control) == InputModifier.Control) { result |= CefEventFlags.ControlDown; } 149 | if ((modifier & InputModifier.Alt) == InputModifier.Alt) { result |= CefEventFlags.AltDown; } 150 | return result; 151 | } 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /BrowserHost.Renderer/IpcBuffer.cs: -------------------------------------------------------------------------------- 1 | using SharedMemory; 2 | using System; 3 | using System.IO; 4 | using System.Runtime.Serialization.Formatters.Binary; 5 | using System.Threading.Tasks; 6 | 7 | namespace BrowserHost.Renderer 8 | { 9 | public class IpcResponse 10 | { 11 | public bool Success; 12 | public TResponse Data; 13 | } 14 | 15 | public class IpcBuffer : RpcBuffer 16 | { 17 | private static BinaryFormatter formatter = new BinaryFormatter(); 18 | 19 | // Handle conversion between wire's byte[] and nicer clr types 20 | private static Func CallbackFactory(Func callback) 21 | { 22 | return (messageId, rawRequest) => 23 | { 24 | var request = Decode(rawRequest); 25 | 26 | var response = callback(request); 27 | 28 | return response == null ? null : Encode(response); 29 | }; 30 | } 31 | 32 | public IpcBuffer(string name, Func callback) : base(name, CallbackFactory(callback)) { } 33 | 34 | public IpcResponse RemoteRequest(TOutgoing request, int timeout = 5000) 35 | { 36 | var rawRequest = Encode(request); 37 | var rawResponse = RemoteRequest(rawRequest, timeout); 38 | return new IpcResponse 39 | { 40 | Success = rawResponse.Success, 41 | Data = rawResponse.Success ? Decode(rawResponse.Data) : default, 42 | }; 43 | } 44 | 45 | public async Task> RemoteRequestAsync(TOutgoing request, int timeout = 5000) 46 | { 47 | var rawRequest = Encode(request); 48 | var rawResponse = await RemoteRequestAsync(rawRequest, timeout); 49 | return new IpcResponse 50 | { 51 | Success = rawResponse.Success, 52 | Data = rawResponse.Success ? Decode(rawResponse.Data) : default, 53 | }; 54 | } 55 | 56 | private static byte[] Encode(T value) 57 | { 58 | byte[] encoded; 59 | using (MemoryStream stream = new MemoryStream()) 60 | { 61 | formatter.Serialize(stream, value); 62 | encoded = stream.ToArray(); 63 | } 64 | return encoded; 65 | } 66 | 67 | private static T Decode(byte[] encoded) 68 | { 69 | if (encoded == null) { return default; } 70 | 71 | T value; 72 | using (MemoryStream stream = new MemoryStream(encoded)) 73 | { 74 | value = (T)formatter.Deserialize(stream); 75 | } 76 | return value; 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /BrowserHost.Renderer/Program.cs: -------------------------------------------------------------------------------- 1 | using BrowserHost.Common; 2 | using BrowserHost.Renderer.RenderHandlers; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Diagnostics; 6 | using System.Drawing; 7 | using System.IO; 8 | using System.Reflection; 9 | using System.Runtime.CompilerServices; 10 | using System.Threading; 11 | 12 | namespace BrowserHost.Renderer 13 | { 14 | class Program 15 | { 16 | private static string cefAssemblyDir; 17 | private static string dalamudAssemblyDir; 18 | 19 | private static Thread parentWatchThread; 20 | private static EventWaitHandle waitHandle; 21 | 22 | private static IpcBuffer ipcBuffer; 23 | 24 | private static Dictionary inlays = new Dictionary(); 25 | 26 | static void Main(string[] rawArgs) 27 | { 28 | Console.WriteLine("Render process running."); 29 | var args = RenderProcessArguments.Deserialise(rawArgs[0]); 30 | 31 | // Need to pull these out before Run() so the resolver can access. 32 | cefAssemblyDir = args.CefAssemblyDir; 33 | dalamudAssemblyDir = args.DalamudAssemblyDir; 34 | 35 | AppDomain.CurrentDomain.AssemblyResolve += CustomAssemblyResolver; 36 | 37 | Run(args); 38 | } 39 | 40 | // Main process logic. Seperated to ensure assembly resolution is configured. 41 | [MethodImpl(MethodImplOptions.NoInlining)] 42 | private static void Run(RenderProcessArguments args) 43 | { 44 | waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, args.KeepAliveHandleName); 45 | 46 | // Boot up a thread to make sure we shut down if parent dies 47 | parentWatchThread = new Thread(WatchParentStatus); 48 | parentWatchThread.Start(args.ParentPid); 49 | 50 | #if DEBUG 51 | AppDomain.CurrentDomain.FirstChanceException += (obj, e) => Console.Error.WriteLine(e.Exception.ToString()); 52 | #endif 53 | 54 | var dxRunning = DxHandler.Initialise(args.DxgiAdapterLuid); 55 | CefHandler.Initialise(cefAssemblyDir, args.CefCacheDir); 56 | 57 | ipcBuffer = new IpcBuffer(args.IpcChannelName, HandleIpcRequest); 58 | 59 | Console.WriteLine("Notifiying on ready state."); 60 | 61 | // We always support bitmap buffer transport 62 | var availableTransports = FrameTransportMode.BitmapBuffer; 63 | if (dxRunning) { availableTransports |= FrameTransportMode.SharedTexture; } 64 | 65 | ipcBuffer.RemoteRequest(new ReadyNotificationRequest() 66 | { 67 | availableTransports = availableTransports, 68 | }); 69 | 70 | Console.WriteLine("Waiting..."); 71 | 72 | waitHandle.WaitOne(); 73 | waitHandle.Dispose(); 74 | 75 | Console.WriteLine("Render process shutting down."); 76 | 77 | ipcBuffer.Dispose(); 78 | 79 | DxHandler.Shutdown(); 80 | CefHandler.Shutdown(); 81 | 82 | parentWatchThread.Abort(); 83 | } 84 | 85 | private static void WatchParentStatus(object pid) 86 | { 87 | Console.WriteLine($"Watching parent PID {pid}"); 88 | var process = Process.GetProcessById((int)pid); 89 | process.WaitForExit(); 90 | waitHandle.Set(); 91 | 92 | var self = Process.GetCurrentProcess(); 93 | self.WaitForExit(1000); 94 | try { self.Kill(); } 95 | catch (InvalidOperationException) { } 96 | } 97 | 98 | private static object HandleIpcRequest(DownstreamIpcRequest request) 99 | { 100 | switch (request) 101 | { 102 | case NewInlayRequest newInlayRequest: return OnNewInlayRequest(newInlayRequest); 103 | 104 | case ResizeInlayRequest resizeInlayRequest: 105 | { 106 | var inlay = inlays[resizeInlayRequest.Guid]; 107 | if (inlay == null) { return null; } 108 | inlay.Resize(new Size(resizeInlayRequest.Width, resizeInlayRequest.Height)); 109 | 110 | return BuildRenderHandlerResponse(inlay.RenderHandler); 111 | } 112 | 113 | case NavigateInlayRequest navigateInlayRequest: 114 | { 115 | var inlay = inlays[navigateInlayRequest.Guid]; 116 | inlay.Navigate(navigateInlayRequest.Url); 117 | return null; 118 | } 119 | 120 | case DebugInlayRequest debugInlayRequest: 121 | { 122 | var inlay = inlays[debugInlayRequest.Guid]; 123 | inlay.Debug(); 124 | return null; 125 | } 126 | 127 | case RemoveInlayRequest removeInlayRequest: 128 | { 129 | var inlay = inlays[removeInlayRequest.Guid]; 130 | inlays.Remove(removeInlayRequest.Guid); 131 | inlay.Dispose(); 132 | return null; 133 | } 134 | 135 | case MouseEventRequest mouseMoveRequest: 136 | { 137 | var inlay = inlays[mouseMoveRequest.Guid]; 138 | inlay?.HandleMouseEvent(mouseMoveRequest); 139 | return null; 140 | } 141 | 142 | case KeyEventRequest keyEventRequest: 143 | { 144 | var inlay = inlays[keyEventRequest.Guid]; 145 | inlay?.HandleKeyEvent(keyEventRequest); 146 | return null; 147 | } 148 | 149 | default: 150 | throw new Exception($"Unknown IPC request type {request.GetType().Name} received."); 151 | } 152 | } 153 | 154 | private static object OnNewInlayRequest(NewInlayRequest request) 155 | { 156 | var size = new Size(request.Width, request.Height); 157 | BaseRenderHandler renderHandler = request.FrameTransportMode switch 158 | { 159 | FrameTransportMode.SharedTexture => new TextureRenderHandler(size), 160 | FrameTransportMode.BitmapBuffer => new BitmapBufferRenderHandler(size), 161 | _ => throw new Exception($"Unhandled frame transport mode {request.FrameTransportMode}"), 162 | }; 163 | 164 | var inlay = new Inlay(request.Url, renderHandler); 165 | inlay.Initialise(); 166 | inlays.Add(request.Guid, inlay); 167 | 168 | renderHandler.CursorChanged += (sender, cursor) => 169 | { 170 | ipcBuffer.RemoteRequest(new SetCursorRequest() 171 | { 172 | Guid = request.Guid, 173 | Cursor = cursor 174 | }); 175 | }; 176 | 177 | return BuildRenderHandlerResponse(renderHandler); 178 | } 179 | 180 | private static object BuildRenderHandlerResponse(BaseRenderHandler renderHandler) 181 | { 182 | return renderHandler switch 183 | { 184 | TextureRenderHandler textureRenderHandler => new TextureHandleResponse() { TextureHandle = textureRenderHandler.SharedTextureHandle }, 185 | BitmapBufferRenderHandler bitmapBufferRenderHandler => new BitmapBufferResponse() 186 | { 187 | BitmapBufferName = bitmapBufferRenderHandler.BitmapBufferName, 188 | FrameInfoBufferName = bitmapBufferRenderHandler.FrameInfoBufferName, 189 | }, 190 | _ => throw new Exception($"Unhandled render handler type {renderHandler.GetType().Name}") 191 | }; 192 | } 193 | 194 | private static Assembly CustomAssemblyResolver(object sender, ResolveEventArgs args) 195 | { 196 | var assemblyName = args.Name.Split(new[] { ',' }, 2)[0] + ".dll"; 197 | 198 | string assemblyPath = null; 199 | if (assemblyName.StartsWith("CefSharp")) 200 | { 201 | assemblyPath = Path.Combine(cefAssemblyDir, assemblyName); 202 | } 203 | else if (assemblyName.StartsWith("SharpDX")) 204 | { 205 | assemblyPath = Path.Combine(dalamudAssemblyDir, assemblyName); 206 | } 207 | 208 | if (assemblyPath == null) { return null; } 209 | 210 | if (!File.Exists(assemblyPath)) 211 | { 212 | Console.Error.WriteLine($"Could not find assembly `{assemblyName}` at search path `{assemblyPath}`"); 213 | return null; 214 | } 215 | 216 | return Assembly.LoadFile(assemblyPath); 217 | } 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /BrowserHost.Renderer/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("BrowserHost.Renderer")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("BrowserHost.Renderer")] 12 | [assembly: AssemblyCopyright("Copyright © 2020")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("a9b66761-a607-4b6c-b80e-33a96bb16d14")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.4.1.2")] 35 | [assembly: AssemblyFileVersion("1.4.1.2")] 36 | -------------------------------------------------------------------------------- /BrowserHost.Renderer/RenderHandlers/BaseRenderHandler.cs: -------------------------------------------------------------------------------- 1 | using BrowserHost.Common; 2 | using CefSharp; 3 | using CefSharp.Enums; 4 | using CefSharp.OffScreen; 5 | using CefSharp.Structs; 6 | using System; 7 | 8 | namespace BrowserHost.Renderer.RenderHandlers 9 | { 10 | abstract class BaseRenderHandler : IRenderHandler 11 | { 12 | public event EventHandler CursorChanged; 13 | 14 | // Transparent background click-through state 15 | private bool cursorOnBackground; 16 | private Cursor cursor; 17 | 18 | public abstract void Dispose(); 19 | 20 | public abstract void Resize(System.Drawing.Size size); 21 | 22 | public ScreenInfo? GetScreenInfo() 23 | { 24 | return new ScreenInfo() { DeviceScaleFactor = 1.0F }; 25 | } 26 | 27 | public void SetMousePosition(int x, int y) 28 | { 29 | var alpha = GetAlphaAt(x, y); 30 | 31 | // We treat 0 alpha as click through - if changed, fire off the event 32 | var currentlyOnBackground = alpha == 0; 33 | if (currentlyOnBackground != cursorOnBackground) 34 | { 35 | cursorOnBackground = currentlyOnBackground; 36 | 37 | // EDGE CASE: if cursor transitions onto alpha:0 _and_ between two native cursor types, I guess this will be a race cond. 38 | // Not sure if should have two seperate upstreams for them, or try and prevent the race. consider. 39 | CursorChanged?.Invoke(this, currentlyOnBackground ? Cursor.BrowserHostNoCapture : cursor); 40 | } 41 | } 42 | 43 | protected abstract byte GetAlphaAt(int x, int y); 44 | 45 | #region IRenderHandler 46 | 47 | public bool GetScreenPoint(int viewX, int viewY, out int screenX, out int screenY) 48 | { 49 | screenX = viewX; 50 | screenY = viewY; 51 | 52 | return false; 53 | } 54 | 55 | public abstract Rect GetViewRect(); 56 | 57 | public abstract void OnPaint(PaintElementType type, Rect dirtyRect, IntPtr buffer, int width, int height); 58 | 59 | public void OnAcceleratedPaint(PaintElementType type, Rect dirtyRect, IntPtr sharedHandle) 60 | { 61 | // UNUSED 62 | // CEF has removed support for DX accelerated paint shared textures, pending re-implementation in 63 | // chromium's new compositor, Vis. Ref: https://bitbucket.org/chromiumembedded/cef/issues/2575/viz-implementation-for-osr 64 | } 65 | 66 | public abstract void OnPopupShow(bool show); 67 | 68 | public abstract void OnPopupSize(Rect rect); 69 | 70 | public void OnVirtualKeyboardRequested(IBrowser browser, TextInputMode inputMode) 71 | { 72 | } 73 | 74 | public void OnImeCompositionRangeChanged(Range selectedRange, Rect[] characterBounds) 75 | { 76 | } 77 | 78 | public void OnCursorChange(IntPtr cursorPtr, CursorType type, CursorInfo customCursorInfo) 79 | { 80 | cursor = EncodeCursor(type); 81 | 82 | // If we're on background, don't flag a cursor change 83 | if (!cursorOnBackground) { CursorChanged?.Invoke(this, cursor); } 84 | } 85 | 86 | public bool StartDragging(IDragData dragData, DragOperationsMask mask, int x, int y) 87 | { 88 | // Returning false to abort drag operations. 89 | return false; 90 | } 91 | 92 | public void UpdateDragCursor(DragOperationsMask operation) 93 | { 94 | } 95 | 96 | #endregion 97 | 98 | #region Cursor encoding 99 | 100 | private Cursor EncodeCursor(CursorType cursor) 101 | { 102 | switch (cursor) 103 | { 104 | // CEF calls default "pointer", and pointer "hand". Derp. 105 | case CursorType.Pointer: return Cursor.Default; 106 | case CursorType.Cross: return Cursor.Crosshair; 107 | case CursorType.Hand: return Cursor.Pointer; 108 | case CursorType.IBeam: return Cursor.Text; 109 | case CursorType.Wait: return Cursor.Wait; 110 | case CursorType.Help: return Cursor.Help; 111 | case CursorType.EastResize: return Cursor.EResize; 112 | case CursorType.NorthResize: return Cursor.NResize; 113 | case CursorType.NortheastResize: return Cursor.NEResize; 114 | case CursorType.NorthwestResize: return Cursor.NWResize; 115 | case CursorType.SouthResize: return Cursor.SResize; 116 | case CursorType.SoutheastResize: return Cursor.SEResize; 117 | case CursorType.SouthwestResize: return Cursor.SWResize; 118 | case CursorType.WestResize: return Cursor.WResize; 119 | case CursorType.NorthSouthResize: return Cursor.NSResize; 120 | case CursorType.EastWestResize: return Cursor.EWResize; 121 | case CursorType.NortheastSouthwestResize: return Cursor.NESWResize; 122 | case CursorType.NorthwestSoutheastResize: return Cursor.NWSEResize; 123 | case CursorType.ColumnResize: return Cursor.ColResize; 124 | case CursorType.RowResize: return Cursor.RowResize; 125 | 126 | // There isn't really support for panning right now. Default to all-scroll. 127 | case CursorType.MiddlePanning: 128 | case CursorType.EastPanning: 129 | case CursorType.NorthPanning: 130 | case CursorType.NortheastPanning: 131 | case CursorType.NorthwestPanning: 132 | case CursorType.SouthPanning: 133 | case CursorType.SoutheastPanning: 134 | case CursorType.SouthwestPanning: 135 | case CursorType.WestPanning: 136 | return Cursor.AllScroll; 137 | 138 | case CursorType.Move: return Cursor.Move; 139 | case CursorType.VerticalText: return Cursor.VerticalText; 140 | case CursorType.Cell: return Cursor.Cell; 141 | case CursorType.ContextMenu: return Cursor.ContextMenu; 142 | case CursorType.Alias: return Cursor.Alias; 143 | case CursorType.Progress: return Cursor.Progress; 144 | case CursorType.NoDrop: return Cursor.NoDrop; 145 | case CursorType.Copy: return Cursor.Copy; 146 | case CursorType.None: return Cursor.None; 147 | case CursorType.NotAllowed: return Cursor.NotAllowed; 148 | case CursorType.ZoomIn: return Cursor.ZoomIn; 149 | case CursorType.ZoomOut: return Cursor.ZoomOut; 150 | case CursorType.Grab: return Cursor.Grab; 151 | case CursorType.Grabbing: return Cursor.Grabbing; 152 | 153 | // Not handling custom for now 154 | case CursorType.Custom: return Cursor.Default; 155 | } 156 | 157 | // Unmapped cursor, log and default 158 | Console.WriteLine($"Switching to unmapped cursor type {cursor}."); 159 | return Cursor.Default; 160 | } 161 | 162 | #endregion 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /BrowserHost.Renderer/RenderHandlers/BitmapBufferRenderHandler.cs: -------------------------------------------------------------------------------- 1 | using BrowserHost.Common; 2 | using CefSharp; 3 | using CefSharp.Structs; 4 | using SharedMemory; 5 | using System; 6 | using System.Collections.Concurrent; 7 | using System.Runtime.ExceptionServices; 8 | using System.Runtime.InteropServices; 9 | 10 | namespace BrowserHost.Renderer.RenderHandlers 11 | { 12 | class BitmapBufferRenderHandler : BaseRenderHandler 13 | { 14 | // CEF buffers are 32-bit BGRA 15 | private const byte bytesPerPixel = 4; 16 | 17 | public string BitmapBufferName { get { return bitmapBuffer.Name; } } 18 | public string FrameInfoBufferName { get { return frameInfoBuffer.Name; } } 19 | 20 | private BufferReadWrite bitmapBuffer; 21 | private CircularBuffer frameInfoBuffer; 22 | private System.Drawing.Size size; 23 | 24 | private bool popupVisible; 25 | private Rect popupRect; 26 | private byte[] popupBuffer; 27 | 28 | private ConcurrentBag obsoleteBuffers = new ConcurrentBag(); 29 | 30 | public BitmapBufferRenderHandler(System.Drawing.Size size) 31 | { 32 | this.size = size; 33 | 34 | BuildBitmapBuffer(size); 35 | 36 | frameInfoBuffer = new CircularBuffer( 37 | $"BrowserHostFrameInfoBuffer{Guid.NewGuid()}", 38 | 5, 39 | Marshal.SizeOf(typeof(BitmapFrame)) 40 | ); 41 | } 42 | 43 | public override void Dispose() 44 | { 45 | frameInfoBuffer.Dispose(); 46 | } 47 | 48 | public override void Resize(System.Drawing.Size newSize) 49 | { 50 | // If new size is same as current, noop 51 | if ( 52 | newSize.Width == size.Width && 53 | newSize.Height == size.Height 54 | ) { 55 | return; 56 | } 57 | 58 | // Build new buffers & set up on instance 59 | size = newSize; 60 | BuildBitmapBuffer(newSize); 61 | } 62 | 63 | protected override byte GetAlphaAt(int x, int y) 64 | { 65 | var rowPitch = size.Width * bytesPerPixel; 66 | 67 | var cursorAlphaOffset = 0 68 | + (Math.Min(Math.Max(x, 0), size.Width - 1) * bytesPerPixel) 69 | + (Math.Min(Math.Max(y, 0), size.Height - 1) * rowPitch) 70 | + 3; 71 | 72 | byte alpha = 255; 73 | try 74 | { 75 | bitmapBuffer.Read(ptr => 76 | { 77 | alpha = Marshal.ReadByte(ptr, cursorAlphaOffset); 78 | }); 79 | } 80 | catch 81 | { 82 | Console.Error.WriteLine("Failed to read alpha value from bitmap buffer."); 83 | alpha = 255; 84 | } 85 | 86 | return alpha; 87 | } 88 | 89 | public override Rect GetViewRect() 90 | { 91 | return new Rect(0, 0, size.Width, size.Height); 92 | } 93 | 94 | public override void OnPaint(PaintElementType type, Rect dirtyRect, IntPtr buffer, int width, int height) 95 | { 96 | var length = bytesPerPixel * width * height; 97 | 98 | // If this is a popup render, copy it across to the buffer. 99 | if (type != PaintElementType.View) { 100 | Marshal.Copy(buffer, popupBuffer, 0, length); 101 | return; 102 | } 103 | 104 | // If the paint size does not match our buffer size, we're likely resizing and paint hasn't caught up. Noop. 105 | if (width != size.Width && height != size.Height) { return; } 106 | 107 | var frame = new BitmapFrame() 108 | { 109 | Length = length, 110 | Width = width, 111 | Height = height, 112 | DirtyX = dirtyRect.X, 113 | DirtyY = dirtyRect.Y, 114 | DirtyWidth = dirtyRect.Width, 115 | DirtyHeight = dirtyRect.Height, 116 | }; 117 | 118 | WriteToBuffers(frame, buffer, true); 119 | 120 | // Intersect with dirty? 121 | if (popupVisible) 122 | { 123 | var popupFrame = new BitmapFrame() 124 | { 125 | Length = length, 126 | Width = width, 127 | Height = height, 128 | DirtyX = popupRect.X, 129 | DirtyY = popupRect.Y, 130 | DirtyWidth = popupRect.Width, 131 | DirtyHeight = popupRect.Height, 132 | }; 133 | var handle = GCHandle.Alloc(popupBuffer, GCHandleType.Pinned); 134 | WriteToBuffers(popupFrame, handle.AddrOfPinnedObject(), false); 135 | handle.Free(); 136 | } 137 | 138 | // Render is complete, clean up obsolete buffers 139 | var obsoleteBuffers = this.obsoleteBuffers; 140 | this.obsoleteBuffers = new ConcurrentBag(); 141 | foreach (var toDispose in obsoleteBuffers) { toDispose.Dispose(); } 142 | } 143 | 144 | public override void OnPopupShow(bool show) 145 | { 146 | popupVisible = show; 147 | } 148 | 149 | public override void OnPopupSize(Rect rect) 150 | { 151 | popupRect = rect; 152 | popupBuffer = new byte[rect.Width * rect.Height * bytesPerPixel]; 153 | } 154 | 155 | private void BuildBitmapBuffer(System.Drawing.Size size) 156 | { 157 | var oldBitmapBuffer = bitmapBuffer; 158 | 159 | var bitmapBufferName = $"BrowserHostBitmapBuffer{Guid.NewGuid()}"; 160 | bitmapBuffer = new BufferReadWrite(bitmapBufferName, size.Width * size.Height * bytesPerPixel); 161 | 162 | // Mark the old buffer for disposal 163 | if (oldBitmapBuffer != null) { obsoleteBuffers.Add(oldBitmapBuffer); } 164 | } 165 | 166 | // There's a race condition wherein a resize from the plugin causes the browser to resize it's output buffer 167 | // during writing it out to the IPC, which causes an access violation. Rather than trying to prevent the race like 168 | // a sane developer, I'm just catching the error and nooping it - a dropped frame isn't a big issue. 169 | [HandleProcessCorruptedStateExceptions] 170 | private void WriteToBuffers(BitmapFrame frame, IntPtr buffer, bool offsetFromSource) 171 | { 172 | // Not using read/write locks because I'm a cowboy (and there seems to be a race cond in the locking mechanism) 173 | try 174 | { 175 | WriteDirtyRect(frame, buffer, offsetFromSource); 176 | frameInfoBuffer.Write(ref frame); 177 | } 178 | catch (AccessViolationException e) 179 | { 180 | Console.WriteLine($"Error writing to buffer, nooping frame on {bitmapBuffer.Name}: {e.Message}"); 181 | } 182 | } 183 | 184 | private void WriteDirtyRect(BitmapFrame frame, IntPtr buffer, bool offsetFromSource) 185 | { 186 | // Write each row as a dirty stripe 187 | for (var row = frame.DirtyY; row < frame.DirtyY + frame.DirtyHeight; row++) 188 | { 189 | var position = (row * frame.Width * bytesPerPixel) + (frame.DirtyX * bytesPerPixel); 190 | var bufferOffset = offsetFromSource 191 | ? position 192 | : (row - frame.DirtyY - 1) * frame.DirtyWidth * bytesPerPixel; 193 | bitmapBuffer.Write( 194 | buffer + bufferOffset, 195 | frame.DirtyWidth * bytesPerPixel, 196 | position 197 | ); 198 | } 199 | } 200 | } 201 | } 202 | -------------------------------------------------------------------------------- /BrowserHost.Renderer/RenderHandlers/TextureRenderHandler.cs: -------------------------------------------------------------------------------- 1 | using CefSharp; 2 | using CefSharp.Structs; 3 | using D3D11 = SharpDX.Direct3D11; 4 | using DXGI = SharpDX.DXGI; 5 | using System; 6 | using System.Collections.Concurrent; 7 | using System.Runtime.ExceptionServices; 8 | using System.Runtime.InteropServices; 9 | 10 | namespace BrowserHost.Renderer.RenderHandlers 11 | { 12 | class TextureRenderHandler : BaseRenderHandler 13 | { 14 | // CEF buffers are 32-bit BGRA 15 | private const byte bytesPerPixel = 4; 16 | 17 | private D3D11.Texture2D texture; 18 | private D3D11.Texture2D popupTexture; 19 | private ConcurrentBag obsoluteTextures = new ConcurrentBag(); 20 | 21 | private bool popupVisible; 22 | private Rect popupRect; 23 | 24 | private IntPtr sharedTextureHandle = IntPtr.Zero; 25 | public IntPtr SharedTextureHandle { 26 | get 27 | { 28 | if (sharedTextureHandle == IntPtr.Zero) 29 | { 30 | using (var resource = texture.QueryInterface()) 31 | { 32 | sharedTextureHandle = resource.SharedHandle; 33 | } 34 | } 35 | return sharedTextureHandle; 36 | } 37 | } 38 | 39 | // Transparent background click-through state 40 | private IntPtr bufferPtr; 41 | private int bufferWidth; 42 | private int bufferHeight; 43 | 44 | public TextureRenderHandler(System.Drawing.Size size) 45 | { 46 | texture = BuildViewTexture(size); 47 | } 48 | 49 | public override void Dispose() 50 | { 51 | texture.Dispose(); 52 | if (popupTexture != null) { popupTexture.Dispose(); } 53 | foreach (var texture in obsoluteTextures) { texture.Dispose(); } 54 | } 55 | 56 | public override void Resize(System.Drawing.Size size) 57 | { 58 | var oldTexture = texture; 59 | texture = BuildViewTexture(size); 60 | if (oldTexture != null) { obsoluteTextures.Add(oldTexture); } 61 | // Need to clear the cached handle value 62 | // TODO: Maybe I should just avoid the lazy cache and do it eagerly on texture build. 63 | sharedTextureHandle = IntPtr.Zero; 64 | } 65 | 66 | // Nasty shit needs nasty attributes. 67 | [HandleProcessCorruptedStateExceptions] 68 | protected override byte GetAlphaAt(int x, int y) 69 | { 70 | var rowPitch = bufferWidth * bytesPerPixel; 71 | 72 | // Get the offset for the alpha of the cursor's current position. Bitmap buffer is BGRA, so +3 to get alpha byte 73 | var cursorAlphaOffset = 0 74 | + (Math.Min(Math.Max(x, 0), bufferWidth - 1) * bytesPerPixel) 75 | + (Math.Min(Math.Max(y, 0), bufferHeight - 1) * rowPitch) 76 | + 3; 77 | 78 | byte alpha; 79 | try { alpha = Marshal.ReadByte(bufferPtr + cursorAlphaOffset); } 80 | catch 81 | { 82 | Console.Error.WriteLine("Failed to read alpha value from cef buffer."); 83 | return 255; 84 | } 85 | 86 | return alpha; 87 | } 88 | 89 | private D3D11.Texture2D BuildViewTexture(System.Drawing.Size size) 90 | { 91 | // Build texture. Most of these properties are defined to match how CEF exposes the render buffer. 92 | return new D3D11.Texture2D(DxHandler.Device, new D3D11.Texture2DDescription() 93 | { 94 | Width = size.Width, 95 | Height = size.Height, 96 | MipLevels = 1, 97 | ArraySize = 1, 98 | Format = DXGI.Format.B8G8R8A8_UNorm, 99 | SampleDescription = new DXGI.SampleDescription(1, 0), 100 | Usage = D3D11.ResourceUsage.Default, 101 | BindFlags = D3D11.BindFlags.ShaderResource, 102 | CpuAccessFlags = D3D11.CpuAccessFlags.None, 103 | // TODO: Look into getting SharedKeyedmutex working without a CTD from the plugin side. 104 | OptionFlags = D3D11.ResourceOptionFlags.Shared, 105 | }); 106 | } 107 | 108 | public override Rect GetViewRect() 109 | { 110 | // There's a very small chance that OnPaint's cleanup will delete the current texture midway through this function - 111 | // Try a few times just in case before failing out with an obviously-wrong value 112 | // hi adam 113 | for (var i = 0; i < 5; i++) 114 | { 115 | try { return GetViewRectInternal(); } 116 | catch (NullReferenceException) { } 117 | } 118 | return new Rect(0, 0, 1, 1); 119 | } 120 | 121 | private Rect GetViewRectInternal() 122 | { 123 | var texDesc = texture.Description; 124 | return new Rect(0, 0, texDesc.Width, texDesc.Height); 125 | } 126 | 127 | public override void OnPaint(PaintElementType type, Rect dirtyRect, IntPtr buffer, int width, int height) 128 | { 129 | var targetTexture = type switch 130 | { 131 | PaintElementType.View => texture, 132 | PaintElementType.Popup => popupTexture, 133 | _ => throw new Exception($"Unknown paint type {type}"), 134 | }; 135 | 136 | // Nasty hack; we're keeping a ref to the view buffer for pixel lookups without going through DX 137 | if (type == PaintElementType.View) 138 | { 139 | bufferPtr = buffer; 140 | bufferWidth = width; 141 | bufferHeight = height; 142 | } 143 | 144 | // Calculate offset multipliers for the current buffer 145 | var rowPitch = width * bytesPerPixel; 146 | var depthPitch = rowPitch * height; 147 | 148 | // Build the destination region for the dirty rect that we'll draw to 149 | var texDesc = targetTexture.Description; 150 | var sourceRegionPtr = buffer + (dirtyRect.X * bytesPerPixel) + (dirtyRect.Y * rowPitch); 151 | var destinationRegion = new D3D11.ResourceRegion() 152 | { 153 | Top = Math.Min(dirtyRect.Y, texDesc.Height), 154 | Bottom = Math.Min(dirtyRect.Y + dirtyRect.Height, texDesc.Height), 155 | Left = Math.Min(dirtyRect.X, texDesc.Width), 156 | Right = Math.Min(dirtyRect.X + dirtyRect.Width, texDesc.Width), 157 | Front = 0, 158 | Back = 1, 159 | }; 160 | 161 | // Draw to the target 162 | var context = targetTexture.Device.ImmediateContext; 163 | context.UpdateSubresource(targetTexture, 0, destinationRegion, sourceRegionPtr, rowPitch, depthPitch); 164 | 165 | // Only need to do composition + flush on primary texture 166 | if (type != PaintElementType.View) { return; } 167 | 168 | // Intersect with dirty? 169 | if (popupVisible) 170 | { 171 | context.CopySubresourceRegion(popupTexture, 0, null, targetTexture, 0, popupRect.X, popupRect.Y); 172 | } 173 | 174 | context.Flush(); 175 | 176 | // Rendering is complete, clean up any obsolete textures 177 | var textures = obsoluteTextures; 178 | obsoluteTextures = new ConcurrentBag(); 179 | foreach (var texture in textures) { texture.Dispose(); } 180 | } 181 | 182 | public override void OnPopupShow(bool show) 183 | { 184 | popupVisible = show; 185 | } 186 | 187 | public override void OnPopupSize(Rect rect) 188 | { 189 | popupRect = rect; 190 | 191 | // I'm really not sure if this happens. If it does, frequently - will probably need 2x shared textures and some jazz. 192 | var texDesc = texture.Description; 193 | if (rect.Width > texDesc.Width || rect.Height > texDesc.Height) 194 | { 195 | Console.Error.WriteLine($"Trying to build popup layer ({rect.Width}x{rect.Height}) larger than primary surface ({texDesc.Width}x{texDesc.Height})."); 196 | } 197 | 198 | // Get a reference to the old texture, we'll make sure to assign a new texture before disposing the old one. 199 | var oldTexture = popupTexture; 200 | 201 | // Build a texture for the new sized popup 202 | popupTexture = new D3D11.Texture2D(texture.Device, new D3D11.Texture2DDescription() 203 | { 204 | Width = rect.Width, 205 | Height = rect.Height, 206 | MipLevels = 1, 207 | ArraySize = 1, 208 | Format = DXGI.Format.B8G8R8A8_UNorm, 209 | SampleDescription = new DXGI.SampleDescription(1, 0), 210 | Usage = D3D11.ResourceUsage.Default, 211 | BindFlags = D3D11.BindFlags.ShaderResource, 212 | CpuAccessFlags = D3D11.CpuAccessFlags.None, 213 | OptionFlags = D3D11.ResourceOptionFlags.None, 214 | }); 215 | 216 | if (oldTexture != null) { oldTexture.Dispose(); } 217 | } 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /BrowserHost.Renderer/cef/VERSION: -------------------------------------------------------------------------------- 1 | 89.0.17+ge7bbb1d+chromium-89.0.4389.114 -------------------------------------------------------------------------------- /BrowserHost.Renderer/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /BrowserHost.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30309.148 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BrowserHost.Plugin", "BrowserHost.Plugin\BrowserHost.Plugin.csproj", "{D047232D-8C20-4185-AC61-78AED2A1EA74}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BrowserHost.Renderer", "BrowserHost.Renderer\BrowserHost.Renderer.csproj", "{A9B66761-A607-4B6C-B80E-33A96BB16D14}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{3218117C-1B94-424E-88CF-D85F9779AAF4}" 11 | ProjectSection(SolutionItems) = preProject 12 | .editorconfig = .editorconfig 13 | .gitignore = .gitignore 14 | COPYING = COPYING 15 | COPYING.LESSER = COPYING.LESSER 16 | README.md = README.md 17 | EndProjectSection 18 | EndProject 19 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BrowserHost.Common", "BrowserHost.Common\BrowserHost.Common.csproj", "{9EC3F19A-CEA0-44BD-B55C-FECF7D02CC6B}" 20 | EndProject 21 | Global 22 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 23 | Debug|x64 = Debug|x64 24 | Release|x64 = Release|x64 25 | EndGlobalSection 26 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 27 | {D047232D-8C20-4185-AC61-78AED2A1EA74}.Debug|x64.ActiveCfg = Debug|x64 28 | {D047232D-8C20-4185-AC61-78AED2A1EA74}.Debug|x64.Build.0 = Debug|x64 29 | {D047232D-8C20-4185-AC61-78AED2A1EA74}.Release|x64.ActiveCfg = Release|x64 30 | {D047232D-8C20-4185-AC61-78AED2A1EA74}.Release|x64.Build.0 = Release|x64 31 | {A9B66761-A607-4B6C-B80E-33A96BB16D14}.Debug|x64.ActiveCfg = Debug|x64 32 | {A9B66761-A607-4B6C-B80E-33A96BB16D14}.Debug|x64.Build.0 = Debug|x64 33 | {A9B66761-A607-4B6C-B80E-33A96BB16D14}.Release|x64.ActiveCfg = Release|x64 34 | {A9B66761-A607-4B6C-B80E-33A96BB16D14}.Release|x64.Build.0 = Release|x64 35 | {9EC3F19A-CEA0-44BD-B55C-FECF7D02CC6B}.Debug|x64.ActiveCfg = Debug|x64 36 | {9EC3F19A-CEA0-44BD-B55C-FECF7D02CC6B}.Debug|x64.Build.0 = Debug|x64 37 | {9EC3F19A-CEA0-44BD-B55C-FECF7D02CC6B}.Release|x64.ActiveCfg = Release|x64 38 | {9EC3F19A-CEA0-44BD-B55C-FECF7D02CC6B}.Release|x64.Build.0 = Release|x64 39 | EndGlobalSection 40 | GlobalSection(SolutionProperties) = preSolution 41 | HideSolutionNode = FALSE 42 | EndGlobalSection 43 | GlobalSection(ExtensibilityGlobals) = postSolution 44 | SolutionGuid = {B18F7920-551C-40E7-BD67-444E6580676D} 45 | EndGlobalSection 46 | EndGlobal 47 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | -------------------------------------------------------------------------------- /COPYING.LESSER: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | BrowserHost 2 | =========== 3 | 4 | Dalamud plugin for in-game browser rendering. Think OverlayPlugin, but it's in the game itself. 5 | --------------------------------------------------------------------------------