Client LuaCsForBarotrauma
ModUtils.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Diagnostics;
4 using System.IO;
5 using System.Linq;
6 using System.Text;
7 using System.Xml.Serialization;
8 using Barotrauma;
11 using Microsoft.CodeAnalysis;
12 using Microsoft.Xna.Framework;
13 
14 namespace Barotrauma;
15 
16 public static class ModUtils
17 {
18  #region LOGGING
19 
20  public static class Logging
21  {
22  public static void PrintMessage(string s)
23  {
24 #if SERVER
25  LuaCsLogger.LogMessage($"[Server] {s}");
26 #else
27  LuaCsLogger.LogMessage($"[Client] {s}");
28 #endif
29  }
30 
31  public static void PrintWarning(string s)
32  {
33 #if SERVER
34  LuaCsLogger.Log($"[Server] {s}", Color.Yellow);
35 #else
36  LuaCsLogger.Log($"[Client] {s}", Color.Yellow);
37 #endif
38  }
39 
40  public static void PrintError(string s)
41  {
42 #if SERVER
43  LuaCsLogger.LogError($"[Server] {s}");
44 #else
45  LuaCsLogger.LogError($"[Client] {s}");
46 #endif
47  }
48  }
49 
50  #endregion
51 
52  #region FILE_IO
53 
54  // ReSharper disable once InconsistentNaming
55  public static class IO
56  {
57  public static IEnumerable<string> FindAllFilesInDirectory(string folder, string pattern,
58  SearchOption option)
59  {
60  try
61  {
62  return Directory.GetFiles(folder, pattern, option);
63  }
64  catch (DirectoryNotFoundException e)
65  {
66  return new string[] { };
67  }
68  }
69 
70  public static string PrepareFilePathString(string filePath) =>
71  PrepareFilePathString(Path.GetDirectoryName(filePath)!, Path.GetFileName(filePath));
72 
73  public static string PrepareFilePathString(string path, string fileName) =>
74  Path.Combine(SanitizePath(path), SanitizeFileName(fileName));
75 
76  public static string SanitizeFileName(string fileName)
77  {
78  foreach (char c in Barotrauma.IO.Path.GetInvalidFileNameCharsCrossPlatform())
79  fileName = fileName.Replace(c, '_');
80  return fileName;
81  }
82 
88  public static string GetContentPackageDir(ContentPackage package)
89  {
90  return SanitizePath(Path.GetFullPath(package.Dir));
91  }
92 
93  public static string SanitizePath(string path)
94  {
95  foreach (char c in Path.GetInvalidPathChars())
96  path = path.Replace(c.ToString(), "_");
97  return path.CleanUpPath();
98  }
99 
100  public static IOActionResultState GetOrCreateFileText(string filePath, out string fileText, Func<string> fileDataFactory = null, bool createFile = true)
101  {
102  fileText = null;
103  string fp = Path.GetFullPath(SanitizePath(filePath));
104 
105  IOActionResultState ioActionResultState = IOActionResultState.Success;
106  if (createFile)
107  {
108  ioActionResultState = CreateFilePath(SanitizePath(filePath), out fp, fileDataFactory);
109  }
110  else if (!File.Exists(fp))
111  {
112  return IOActionResultState.FileNotFound;
113  }
114 
115  if (ioActionResultState == IOActionResultState.Success)
116  {
117  try
118  {
119  fileText = File.ReadAllText(fp!);
120  return IOActionResultState.Success;
121  }
122  catch (ArgumentNullException ane)
123  {
124  ModUtils.Logging.PrintError($"ModUtils::CreateFilePath() | Exception: An argument is null. path: {fp ?? "null"} | Exception Details: {ane.Message}");
125  return IOActionResultState.FilePathNull;
126  }
127  catch (ArgumentException ae)
128  {
129  ModUtils.Logging.PrintError($"ModUtils::CreateFilePath() | Exception: An argument is invalid. path: {fp ?? "null"} | Exception Details: {ae.Message}");
130  return IOActionResultState.FilePathInvalid;
131  }
132  catch (DirectoryNotFoundException dnfe)
133  {
134  ModUtils.Logging.PrintError($"ModUtils::CreateFilePath() | Exception: Cannot find directory. path: {fp ?? "null"} | Exception Details: {dnfe.Message}");
135  return IOActionResultState.DirectoryMissing;
136  }
137  catch (PathTooLongException ptle)
138  {
139  ModUtils.Logging.PrintError($"ModUtils::CreateFilePath() | Exception: path length is over 200 characters. path: {fp ?? "null"} | Exception Details: {ptle.Message}");
140  return IOActionResultState.PathTooLong;
141  }
142  catch (NotSupportedException nse)
143  {
144  ModUtils.Logging.PrintError($"ModUtils::CreateFilePath() | Exception: Operation not supported on your platform/environment (permissions?). path: {fp ?? "null"} | Exception Details: {nse.Message}");
145  return IOActionResultState.InvalidOperation;
146  }
147  catch (IOException ioe)
148  {
149  ModUtils.Logging.PrintError($"ModUtils::CreateFilePath() | Exception: IO tasks failed (Operation not supported). path: {fp ?? "null"} | Exception Details: {ioe.Message}");
150  return IOActionResultState.IOFailure;
151  }
152  catch (Exception e)
153  {
154  ModUtils.Logging.PrintError($"ModUtils::CreateFilePath() | Exception: Unknown/Other Exception. path: {fp ?? "null"} | ExceptionMessage: {e.Message}");
155  return IOActionResultState.UnknownError;
156  }
157  }
158 
159  return ioActionResultState;
160  }
161 
162  public static IOActionResultState CreateFilePath(string filePath, out string formattedFilePath, Func<string> fileDataFactory = null)
163  {
164  string file = Path.GetFileName(filePath);
165  string path = Path.GetDirectoryName(filePath)!;
166 
167  formattedFilePath = IO.PrepareFilePathString(path, file);
168  try
169  {
170  if (!Directory.Exists(path))
171  Directory.CreateDirectory(path);
172  if (!File.Exists(formattedFilePath))
173  File.WriteAllText(formattedFilePath, fileDataFactory is null ? "" : fileDataFactory.Invoke());
174  return IOActionResultState.Success;
175  }
176  catch (ArgumentNullException ane)
177  {
178  ModUtils.Logging.PrintError($"ModUtils::CreateFilePath() | Exception: An argument is null. path: {formattedFilePath ?? "null"} | Exception Details: {ane.Message}");
179  return IOActionResultState.FilePathNull;
180  }
181  catch (ArgumentException ae)
182  {
183  ModUtils.Logging.PrintError($"ModUtils::CreateFilePath() | Exception: An argument is invalid. path: {formattedFilePath ?? "null"} | Exception Details: {ae.Message}");
184  return IOActionResultState.FilePathInvalid;
185  }
186  catch (DirectoryNotFoundException dnfe)
187  {
188  ModUtils.Logging.PrintError($"ModUtils::CreateFilePath() | Exception: Cannot find directory. path: {path ?? "null"} | Exception Details: {dnfe.Message}");
189  return IOActionResultState.DirectoryMissing;
190  }
191  catch (PathTooLongException ptle)
192  {
193  ModUtils.Logging.PrintError($"ModUtils::CreateFilePath() | Exception: path length is over 200 characters. path: {formattedFilePath ?? "null"} | Exception Details: {ptle.Message}");
194  return IOActionResultState.PathTooLong;
195  }
196  catch (NotSupportedException nse)
197  {
198  ModUtils.Logging.PrintError($"ModUtils::CreateFilePath() | Exception: Operation not supported on your platform/environment (permissions?). path: {formattedFilePath ?? "null"} | Exception Details: {nse.Message}");
199  return IOActionResultState.InvalidOperation;
200  }
201  catch (IOException ioe)
202  {
203  ModUtils.Logging.PrintError($"ModUtils::CreateFilePath() | Exception: IO tasks failed (Operation not supported). path: {formattedFilePath ?? "null"} | Exception Details: {ioe.Message}");
204  return IOActionResultState.IOFailure;
205  }
206  catch (Exception e)
207  {
208  ModUtils.Logging.PrintError($"ModUtils::CreateFilePath() | Exception: Unknown/Other Exception. path: {path ?? "null"} | Exception Details: {e.Message}");
209  return IOActionResultState.UnknownError;
210  }
211  }
212 
213  public static IOActionResultState WriteFileText(string filePath, string fileText)
214  {
215  IOActionResultState ioActionResultState = CreateFilePath(filePath, out var fp);
216  if (ioActionResultState == IOActionResultState.Success)
217  {
218  try
219  {
220  File.WriteAllText(fp!, fileText);
221  return IOActionResultState.Success;
222  }
223  catch (ArgumentNullException ane)
224  {
225  ModUtils.Logging.PrintError($"ModUtils::WriteFileText() | Exception: An argument is null. path: {fp ?? "null"} | Exception Details: {ane.Message}");
226  return IOActionResultState.FilePathNull;
227  }
228  catch (ArgumentException ae)
229  {
230  ModUtils.Logging.PrintError($"ModUtils::WriteFileText() | Exception: An argument is invalid. path: {fp ?? "null"} | Exception Details: {ae.Message}");
231  return IOActionResultState.FilePathInvalid;
232  }
233  catch (DirectoryNotFoundException dnfe)
234  {
235  ModUtils.Logging.PrintError($"ModUtils::WriteFileText() | Exception: Cannot find directory. path: {fp ?? "null"} | Exception Details: {dnfe.Message}");
236  return IOActionResultState.DirectoryMissing;
237  }
238  catch (PathTooLongException ptle)
239  {
240  ModUtils.Logging.PrintError($"ModUtils::WriteFileText() | Exception: path length is over 200 characters. path: {fp ?? "null"} | Exception Details: {ptle.Message}");
241  return IOActionResultState.PathTooLong;
242  }
243  catch (NotSupportedException nse)
244  {
245  ModUtils.Logging.PrintError($"ModUtils::WriteFileText() | Exception: Operation not supported on your platform/environment (permissions?). path: {fp ?? "null"} | Exception Details: {nse.Message}");
246  return IOActionResultState.InvalidOperation;
247  }
248  catch (IOException ioe)
249  {
250  ModUtils.Logging.PrintError($"ModUtils::WriteFileText() | Exception: IO tasks failed (Operation not supported). path: {fp ?? "null"} | Exception Details: {ioe.Message}");
251  return IOActionResultState.IOFailure;
252  }
253  catch (Exception e)
254  {
255  ModUtils.Logging.PrintError($"ModUtils::WriteFileText() | Exception: Unknown/Other Exception. path: {fp ?? "null"} | ExceptionMessage: {e.Message}");
256  return IOActionResultState.UnknownError;
257  }
258  }
259 
260  return ioActionResultState;
261  }
262 
272  public static bool LoadOrCreateTypeXml<T>(out T instance,
273  string filepath, Func<T> typeFactory = null, bool createFile = true) where T : class, new()
274  {
275  instance = null;
276  filepath = filepath.CleanUpPath();
277  if (IOActionResultState.Success == GetOrCreateFileText(
278  filepath, out string fileText, typeFactory is not null ? () =>
279  {
280  using StringWriter sw = new StringWriter();
281  T t = typeFactory?.Invoke();
282  if (t is not null)
283  {
284  XmlSerializer s = new XmlSerializer(typeof(T));
285  s.Serialize(sw, t);
286  return sw.ToString();
287  }
288  return "";
289  } : null, createFile))
290  {
291  XmlSerializer s = new XmlSerializer(typeof(T));
292  try
293  {
294  using TextReader tr = new StringReader(fileText);
295  instance = (T)s.Deserialize(tr);
296  return true;
297  }
298  catch(InvalidOperationException ioe)
299  {
300  ModUtils.Logging.PrintError($"Error while parsing type data for {typeof(T)}.");
301  #if DEBUG
302  ModUtils.Logging.PrintError($"Exception: {ioe.Message}. Details: {ioe.InnerException?.Message}");
303  #endif
304  instance = null;
305  return false;
306  }
307  }
308 
309  return false;
310  }
311 
312  public enum IOActionResultState
313  {
314  Success, FileNotFound, FilePathNull, FilePathInvalid, DirectoryMissing, PathTooLong, InvalidOperation, IOFailure, UnknownError
315  }
316  }
317 
318  #endregion
319 
320  #region GAME
321 
322  public static class Game
323  {
328  public static bool IsRoundInProgress()
329  {
330 #if CLIENT
331  if (Screen.Selected is not null
333  return false;
334 #endif
335  return GameMain.GameSession is not null && Level.Loaded is not null;
336  }
337 
338  }
339 
340  #endregion
341 }
static GameSession?? GameSession
Definition: GameMain.cs:88
static void LogError(string message, LuaCsMessageOrigin origin)
static void LogMessage(string message, Color? serverColor=null, Color? clientColor=null)
static void Log(string message, Color? color=null, ServerLog.MessageType messageType=ServerLog.MessageType.ServerMessage)