AutoTranslationPlugin.cs 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Reflection;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using System.Threading;
  11. using ExIni;
  12. using UnityEngine;
  13. using UnityEngine.UI;
  14. using System.Globalization;
  15. using XUnity.AutoTranslator.Plugin.Core.Extensions;
  16. using UnityEngine.EventSystems;
  17. using XUnity.AutoTranslator.Plugin.Core.Configuration;
  18. using XUnity.AutoTranslator.Plugin.Core.Utilities;
  19. using XUnity.AutoTranslator.Plugin.Core.Web;
  20. using XUnity.AutoTranslator.Plugin.Core.Hooks;
  21. using XUnity.AutoTranslator.Plugin.Core.Hooks.TextMeshPro;
  22. using XUnity.AutoTranslator.Plugin.Core.Hooks.UGUI;
  23. using XUnity.AutoTranslator.Plugin.Core.Hooks.NGUI;
  24. using UnityEngine.SceneManagement;
  25. using XUnity.AutoTranslator.Plugin.Core.Constants;
  26. using XUnity.AutoTranslator.Plugin.Core.Debugging;
  27. using Harmony;
  28. using XUnity.AutoTranslator.Plugin.Core.Parsing;
  29. using System.Diagnostics;
  30. using XUnity.AutoTranslator.Plugin.Core.UI;
  31. using XUnity.AutoTranslator.Plugin.Core.Endpoints;
  32. using XUnity.AutoTranslator.Plugin.Core.Web.Internal;
  33. namespace XUnity.AutoTranslator.Plugin.Core
  34. {
  35. /// <summary>
  36. /// Main plugin class for the AutoTranslator.
  37. /// </summary>
  38. public class AutoTranslationPlugin : MonoBehaviour
  39. {
  40. private static readonly char[][] TranslationSplitters = new char[][] { new char[] { '\t' }, new char[] { '=' } };
  41. /// <summary>
  42. /// Allow the instance to be accessed statically, as only one will exist.
  43. /// </summary>
  44. internal static AutoTranslationPlugin Current;
  45. private XuaWindow _window;
  46. /// <summary>
  47. /// These are the currently running translation jobs (being translated by an http request).
  48. /// </summary>
  49. private List<TranslationJob> _completedJobs = new List<TranslationJob>();
  50. private Dictionary<string, TranslationJob> _unstartedJobs = new Dictionary<string, TranslationJob>();
  51. private Dictionary<string, TranslationJob> _ongoingJobs = new Dictionary<string, TranslationJob>();
  52. /// <summary>
  53. /// All the translations are stored in this dictionary.
  54. /// </summary>
  55. private Dictionary<string, string> _staticTranslations = new Dictionary<string, string>();
  56. private Dictionary<string, string> _translations = new Dictionary<string, string>();
  57. private Dictionary<string, string> _reverseTranslations = new Dictionary<string, string>();
  58. /// <summary>
  59. /// These are the new translations that has not yet been persisted to the file system.
  60. /// </summary>
  61. private object _writeToFileSync = new object();
  62. private Dictionary<string, string> _newTranslations = new Dictionary<string, string>();
  63. private HashSet<string> _newUntranslated = new HashSet<string>();
  64. /// <summary>
  65. /// Keeps track of things to copy to clipboard.
  66. /// </summary>
  67. private List<string> _textsToCopyToClipboardOrdered = new List<string>();
  68. private HashSet<string> _textsToCopyToClipboard = new HashSet<string>();
  69. private float _clipboardUpdated = 0.0f;
  70. /// <summary>
  71. /// The number of http translation errors that has occurred up until now.
  72. /// </summary>
  73. private int _consecutiveErrors = 0;
  74. /// <summary>
  75. /// This is a hash set that contains all Text components that is currently being worked on by
  76. /// the translation plugin.
  77. /// </summary>
  78. private HashSet<object> _ongoingOperations = new HashSet<object>();
  79. /// <summary>
  80. /// This function will check if there are symbols of a given language contained in a string.
  81. /// </summary>
  82. private Func<string, bool> _symbolCheck;
  83. /// <summary>
  84. /// Texts currently being scheduled for translation by 'immediate' components.
  85. /// </summary>
  86. private HashSet<string> _immediatelyTranslating = new HashSet<string>();
  87. private Dictionary<string, byte[]> _translatedImages = new Dictionary<string, byte[]>( StringComparer.InvariantCultureIgnoreCase );
  88. private HashSet<string> _untranslatedImages = new HashSet<string>();
  89. private Component _advEngine;
  90. private float? _nextAdvUpdate;
  91. private HttpSecurity _httpSecurity;
  92. private List<ConfiguredEndpoint> _configuredEndpoints;
  93. private ConfiguredEndpoint _endpoint;
  94. private int[] _currentTranslationsQueuedPerSecondRollingWindow = new int[ Settings.TranslationQueueWatchWindow ];
  95. private float? _timeExceededThreshold;
  96. private float _translationsQueuedPerSecond;
  97. private bool _isInTranslatedMode = true;
  98. private bool _textHooksEnabled = true;
  99. private bool _imageHooksEnabled = true;
  100. private bool _batchLogicHasFailed = false;
  101. private int _availableBatchOperations = Settings.MaxAvailableBatchOperations;
  102. private float _batchOperationSecondCounter = 0;
  103. private string[] _previouslyQueuedText = new string[ Settings.PreviousTextStaggerCount ];
  104. private int _staggerTextCursor = 0;
  105. private int _concurrentStaggers = 0;
  106. private int _frameForLastQueuedTranslation = -1;
  107. private int _consecutiveFramesTranslated = 0;
  108. private int _secondForQueuedTranslation = -1;
  109. private int _consecutiveSecondsTranslated = 0;
  110. private bool _hasOverrideFont = false;
  111. private bool _overrideFont = false;
  112. private bool _initialized = false;
  113. private bool _temporarilyDisabled = false;
  114. private string _requireSpriteRendererCheckCausedBy = null;
  115. private int _lastSpriteUpdateFrame = -1;
  116. private bool _isCalledFromSceneManager = false;
  117. /// <summary>
  118. /// Initialized the plugin.
  119. /// </summary>
  120. public void Initialize()
  121. {
  122. // Setup 'singleton'
  123. Current = this;
  124. // Setup logger, if it was not already initialized by a plugin-version
  125. if( XuaLogger.Current == null )
  126. {
  127. XuaLogger.Current = new ConsoleLogger();
  128. }
  129. // Setup configuration
  130. try
  131. {
  132. Settings.Configure();
  133. }
  134. catch( Exception e )
  135. {
  136. XuaLogger.Current.Error( e, "An error occurred during configuration. Shutting plugin down." );
  137. Settings.IsShutdown = true;
  138. Settings.IsShutdownFatal = true;
  139. return;
  140. }
  141. // Setup console, if enabled
  142. if( Settings.EnableConsole )
  143. {
  144. DebugConsole.Enable();
  145. }
  146. // Setup hooks
  147. HooksSetup.InstallTextHooks();
  148. HooksSetup.InstallImageHooks();
  149. HooksSetup.InstallTextGetterCompatHooks();
  150. _httpSecurity = new HttpSecurity();
  151. try
  152. {
  153. var context = new InitializationContext( _httpSecurity, Settings.FromLanguage, Settings.Language );
  154. _configuredEndpoints = KnownTranslateEndpoints.CreateEndpoints( gameObject, context )
  155. .OrderBy( x => x.Error != null )
  156. .ThenBy( x => x.Endpoint.FriendlyName )
  157. .ToList();
  158. }
  159. catch( Exception e )
  160. {
  161. XuaLogger.Current.Error( e, "An error occurred while constructing endpoints. Shutting plugin down." );
  162. Settings.IsShutdown = true;
  163. Settings.IsShutdownFatal = true;
  164. return;
  165. }
  166. try
  167. {
  168. var primaryEndpoint = _configuredEndpoints.FirstOrDefault( x => x.Endpoint.Id == Settings.ServiceEndpoint );
  169. if( primaryEndpoint == null ) throw new Exception( "The primary endpoint was not properly configured." );
  170. if( primaryEndpoint.Error != null ) throw new Exception( "The primary endpoint was not properly configured.", primaryEndpoint.Error );
  171. _endpoint = primaryEndpoint;
  172. }
  173. catch( Exception e )
  174. {
  175. XuaLogger.Current.Error( e, "An unexpected error occurred during initialization of endpoint." );
  176. }
  177. // TODO: Perhaps some bleeding edge check to see if this is required?
  178. var callback = _httpSecurity.GetCertificateValidationCheck();
  179. if( callback != null )
  180. {
  181. ServicePointManager.ServerCertificateValidationCallback += callback;
  182. }
  183. // Save again because configuration may be modified by endpoints
  184. try
  185. {
  186. PluginEnvironment.Current.SaveConfig();
  187. }
  188. catch( Exception e )
  189. {
  190. XuaLogger.Current.Error( e, "An error occurred during while saving configuration." );
  191. }
  192. if( !LanguageHelper.IsFromLanguageSupported( Settings.FromLanguage ) )
  193. {
  194. XuaLogger.Current.Error( $"The plugin has been configured to use the 'FromLanguage={Settings.FromLanguage}'. This language is not supported. Shutting plugin down." );
  195. _endpoint = null;
  196. Settings.IsShutdown = true;
  197. Settings.IsShutdownFatal = true;
  198. }
  199. _symbolCheck = LanguageHelper.GetSymbolCheck( Settings.FromLanguage );
  200. if( !string.IsNullOrEmpty( Settings.OverrideFont ) )
  201. {
  202. var available = Font.GetOSInstalledFontNames();
  203. if( !available.Contains( Settings.OverrideFont ) )
  204. {
  205. XuaLogger.Current.Error( $"The specified override font is not available. Available fonts: " + string.Join( ", ", available ) );
  206. Settings.OverrideFont = null;
  207. }
  208. else
  209. {
  210. _hasOverrideFont = true;
  211. }
  212. _overrideFont = _hasOverrideFont;
  213. }
  214. try
  215. {
  216. EnableSceneLoadScan();
  217. }
  218. catch( Exception e )
  219. {
  220. XuaLogger.Current.Error( e, "An error occurred while settings up texture scene-load scans." );
  221. }
  222. LoadTranslations();
  223. LoadStaticTranslations();
  224. try
  225. {
  226. _window = new XuaWindow(
  227. new List<ToggleViewModel>
  228. {
  229. new ToggleViewModel(
  230. " Translated",
  231. "<b>TRANSLATED</b>\nThe plugin currently displays translated texts. Disabling this does not mean the plugin will no longer perform translations, just that they will not be displayed.",
  232. "<b>NOT TRANSLATED</b>\nThe plugin currently displays untranslated texts.",
  233. ToggleTranslation, () => _isInTranslatedMode )
  234. },
  235. _configuredEndpoints.Select( x =>
  236. new TranslatorDropdownOptionViewModel( () => x == _endpoint, x, OnEndpointSelected ) ).ToList(),
  237. new List<ButtonViewModel>
  238. {
  239. new ButtonViewModel( "Reboot", "<b>REBOOT PLUGIN</b>\nReboots the plugin if it has been shutdown. This only works if the plugin was shut down due to consequtive errors towards the translation endpoint.", RebootPlugin, () => Settings.IsShutdown && !Settings.IsShutdownFatal ),
  240. new ButtonViewModel( "Reload", "<b>RELOAD TRANSLATION</b>\nReloads all translation text files and texture files from disk.", ReloadTranslations, null ),
  241. new ButtonViewModel( "Hook", "<b>MANUAL HOOK</b>\nTraverses the unity object tree for looking for anything that can be translated. Performs a translation if something is found.", ManualHook, null )
  242. },
  243. new List<LabelViewModel>
  244. {
  245. new LabelViewModel( "Version: ", () => PluginData.Version ),
  246. new LabelViewModel( "Status: ", () => Settings.IsShutdown ? "Shutdown" : "Running" ),
  247. new LabelViewModel( "Served translations: ", () => $"{Settings.TranslationCount} / {Settings.MaxTranslationsBeforeShutdown}" ),
  248. new LabelViewModel( "Queued translations: ", () => $"{(_unstartedJobs.Count + _ongoingJobs.Count)} / {Settings.MaxUnstartedJobs}" ),
  249. new LabelViewModel( "Error'ed translations: ", () => $"{_consecutiveErrors} / {Settings.MaxErrors}" ),
  250. } );
  251. }
  252. catch( Exception e )
  253. {
  254. XuaLogger.Current.Error( e, "An error occurred while setting up UI." );
  255. }
  256. UnityTextParsers.Initialize( text => IsTranslatable( text ) && IsBelowMaxLength( text ) );
  257. // start a thread that will periodically removed unused references
  258. var t1 = new Thread( MaintenanceLoop );
  259. t1.IsBackground = true;
  260. t1.Start();
  261. // start a thread that will periodically save new translations
  262. var t2 = new Thread( SaveTranslationsLoop );
  263. t2.IsBackground = true;
  264. t2.Start();
  265. }
  266. private void OnEndpointSelected( ConfiguredEndpoint endpoint )
  267. {
  268. if( _endpoint != endpoint )
  269. {
  270. _endpoint = endpoint;
  271. if( Settings.IsShutdown && !Settings.IsShutdownFatal )
  272. {
  273. RebootPlugin();
  274. ManualHook();
  275. }
  276. Settings.SetEndpoint( _endpoint.Endpoint.Id );
  277. }
  278. }
  279. private IEnumerable<string> GetTranslationFiles()
  280. {
  281. return Directory.GetFiles( Path.Combine( PluginEnvironment.Current.DataPath, Settings.TranslationDirectory ).Parameterize(), $"*.txt", SearchOption.AllDirectories )
  282. .Select( x => x.Replace( "/", "\\" ) );
  283. }
  284. private IEnumerable<string> GetTextureFiles()
  285. {
  286. return Directory.GetFiles( Path.Combine( PluginEnvironment.Current.DataPath, Settings.TextureDirectory ).Parameterize(), $"*.png", SearchOption.AllDirectories )
  287. .Select( x => x.Replace( "/", "\\" ) );
  288. }
  289. private void MaintenanceLoop( object state )
  290. {
  291. while( true )
  292. {
  293. try
  294. {
  295. ObjectReferenceMapper.Cull();
  296. }
  297. catch( Exception e )
  298. {
  299. XuaLogger.Current.Error( e, "An unexpected error occurred while removing GC'ed resources." );
  300. }
  301. Thread.Sleep( 1000 * 60 );
  302. }
  303. }
  304. private void SaveTranslationsLoop( object state )
  305. {
  306. try
  307. {
  308. while( true )
  309. {
  310. if( _newTranslations.Count > 0 )
  311. {
  312. lock( _writeToFileSync )
  313. {
  314. if( _newTranslations.Count > 0 )
  315. {
  316. using( var stream = File.Open( Settings.AutoTranslationsFilePath, FileMode.Append, FileAccess.Write ) )
  317. using( var writer = new StreamWriter( stream, Encoding.UTF8 ) )
  318. {
  319. foreach( var kvp in _newTranslations )
  320. {
  321. writer.WriteLine( TextHelper.Encode( kvp.Key ) + '=' + TextHelper.Encode( kvp.Value ) );
  322. }
  323. writer.Flush();
  324. }
  325. _newTranslations.Clear();
  326. }
  327. }
  328. }
  329. else
  330. {
  331. Thread.Sleep( 5000 );
  332. }
  333. }
  334. }
  335. catch( Exception e )
  336. {
  337. XuaLogger.Current.Error( e, "An error occurred while saving translations to disk." );
  338. }
  339. }
  340. private void EnableSceneLoadScan()
  341. {
  342. XuaLogger.Current.Info( "Probing whether OnLevelWasLoaded or SceneManager is supported in this version of Unity. Any warnings related to OnLevelWasLoaded coming from Unity can safely be ignored." );
  343. if( Features.SupportsSceneManager )
  344. {
  345. XuaLogger.Current.Info( "SceneManager is supported in this version of Unity." );
  346. EnableSceneLoadScanInternal();
  347. }
  348. else
  349. {
  350. XuaLogger.Current.Info( "SceneManager is not supported in this version of Unity. Falling back to OnLevelWasLoaded and Application level API." );
  351. }
  352. }
  353. private void EnableSceneLoadScanInternal()
  354. {
  355. // do this in a different class to avoid having an anonymous method with references to the "Scene" class
  356. SceneManagerLoader.EnableSceneLoadScanInternal( this );
  357. }
  358. internal void OnLevelWasLoadedFromSceneManager( int id )
  359. {
  360. try
  361. {
  362. _isCalledFromSceneManager = true;
  363. OnLevelWasLoaded( id );
  364. }
  365. finally
  366. {
  367. _isCalledFromSceneManager = false;
  368. }
  369. }
  370. private void OnLevelWasLoaded( int id )
  371. {
  372. if( !Features.SupportsSceneManager || ( Features.SupportsSceneManager && _isCalledFromSceneManager ) )
  373. {
  374. if( Settings.EnableTextureScanOnSceneLoad && ( Settings.EnableTextureDumping || Settings.EnableTextureTranslation ) )
  375. {
  376. XuaLogger.Current.Info( "Performing texture lookup during scene load..." );
  377. var startTime = Time.realtimeSinceStartup;
  378. ManualHookForTextures();
  379. var endTime = Time.realtimeSinceStartup;
  380. XuaLogger.Current.Info( $"Finished texture lookup (took {Math.Round( endTime - startTime, 2 )} seconds)" );
  381. }
  382. }
  383. }
  384. /// <summary>
  385. /// Loads the translations found in Translation.{lang}.txt
  386. /// </summary>
  387. private void LoadTranslations()
  388. {
  389. try
  390. {
  391. lock( _writeToFileSync )
  392. {
  393. Directory.CreateDirectory( Path.Combine( PluginEnvironment.Current.DataPath, Settings.TranslationDirectory ).Parameterize() );
  394. Directory.CreateDirectory( Path.GetDirectoryName( Settings.AutoTranslationsFilePath ) );
  395. var mainTranslationFile = Settings.AutoTranslationsFilePath;
  396. LoadTranslationsInFile( mainTranslationFile );
  397. foreach( var fullFileName in GetTranslationFiles().Reverse().Except( new[] { mainTranslationFile } ) )
  398. {
  399. LoadTranslationsInFile( fullFileName );
  400. }
  401. }
  402. if( Settings.EnableTextureTranslation || Settings.EnableTextureDumping )
  403. {
  404. _translatedImages.Clear();
  405. _untranslatedImages.Clear();
  406. Directory.CreateDirectory( Path.Combine( PluginEnvironment.Current.DataPath, Settings.TextureDirectory ).Parameterize() );
  407. foreach( var fullFileName in GetTextureFiles() )
  408. {
  409. RegisterImageFromFile( fullFileName );
  410. }
  411. }
  412. }
  413. catch( Exception e )
  414. {
  415. XuaLogger.Current.Error( e, "An error occurred while loading translations." );
  416. }
  417. }
  418. private void RegisterImageFromFile( string fullFileName )
  419. {
  420. var fileName = Path.GetFileNameWithoutExtension( fullFileName );
  421. var startHash = fileName.LastIndexOf( "[" );
  422. var endHash = fileName.LastIndexOf( "]" );
  423. if( endHash > -1 && startHash > -1 && endHash > startHash )
  424. {
  425. var takeFrom = startHash + 1;
  426. // load based on whether or not the key is image hashed
  427. var parts = fileName.Substring( takeFrom, endHash - takeFrom ).Split( '-' );
  428. string key;
  429. string originalHash;
  430. if( parts.Length == 1 )
  431. {
  432. key = parts[ 0 ];
  433. originalHash = parts[ 0 ];
  434. }
  435. else if( parts.Length == 2 )
  436. {
  437. key = parts[ 0 ];
  438. originalHash = parts[ 1 ];
  439. }
  440. else
  441. {
  442. XuaLogger.Current.Warn( $"Image not loaded (unknown hash): {fullFileName}." );
  443. return;
  444. }
  445. var data = File.ReadAllBytes( fullFileName );
  446. var currentHash = HashHelper.Compute( data );
  447. var isModified = StringComparer.InvariantCultureIgnoreCase.Compare( originalHash, currentHash ) != 0;
  448. // only load images that someone has modified!
  449. if( Settings.LoadUnmodifiedTextures || isModified )
  450. {
  451. RegisterTranslatedImage( key, data );
  452. XuaLogger.Current.Debug( $"Image loaded: {fullFileName}." );
  453. }
  454. else
  455. {
  456. RegisterUntranslatedImage( key );
  457. XuaLogger.Current.Warn( $"Image not loaded (unmodified): {fullFileName}." );
  458. }
  459. //if( Settings.DeleteUnmodifiedTextures && !isModified )
  460. //{
  461. // try
  462. // {
  463. // File.Delete( fullFileName );
  464. // Logger.Current.Warn( $"Image deleted (unmodified): {fullFileName}." );
  465. // }
  466. // catch( Exception e )
  467. // {
  468. // Logger.Current.Warn( e, $"An error occurred while trying to delete unmodified image: {fullFileName}." );
  469. // }
  470. //}
  471. }
  472. else
  473. {
  474. XuaLogger.Current.Warn( $"Image not loaded (no hash): {fullFileName}." );
  475. }
  476. }
  477. private void RegisterImageFromData( string textureName, string key, byte[] data )
  478. {
  479. var name = textureName.SanitizeForFileSystem();
  480. var root = Path.Combine( PluginEnvironment.Current.DataPath, Settings.TextureDirectory ).Parameterize();
  481. var originalHash = HashHelper.Compute( data );
  482. // allow hash and key to be the same; only store one of them then!
  483. string fileName;
  484. if( key == originalHash )
  485. {
  486. fileName = name + " [" + key + "].png";
  487. }
  488. else
  489. {
  490. fileName = name + " [" + key + "-" + originalHash + "].png";
  491. }
  492. var fullName = Path.Combine( root, fileName );
  493. File.WriteAllBytes( fullName, data );
  494. XuaLogger.Current.Info( "Dumped texture file: " + fileName );
  495. if( Settings.LoadUnmodifiedTextures )
  496. {
  497. RegisterTranslatedImage( key, data );
  498. }
  499. else
  500. {
  501. RegisterUntranslatedImage( key );
  502. }
  503. }
  504. private void RegisterTranslatedImage( string key, byte[] data )
  505. {
  506. _translatedImages[ key ] = data;
  507. }
  508. private void RegisterUntranslatedImage( string key )
  509. {
  510. _untranslatedImages.Add( key );
  511. }
  512. private void LoadTranslationsInFile( string fullFileName )
  513. {
  514. if( File.Exists( fullFileName ) )
  515. {
  516. XuaLogger.Current.Debug( $"Loading texts: {fullFileName}." );
  517. string[] translations = File.ReadAllLines( fullFileName, Encoding.UTF8 );
  518. foreach( string translation in translations )
  519. {
  520. for( int i = 0 ; i < TranslationSplitters.Length ; i++ )
  521. {
  522. var splitter = TranslationSplitters[ i ];
  523. string[] kvp = translation.Split( splitter, StringSplitOptions.None );
  524. if( kvp.Length == 2 )
  525. {
  526. string key = TextHelper.Decode( kvp[ 0 ].TrimIfConfigured() );
  527. string value = TextHelper.Decode( kvp[ 1 ] );
  528. if( !string.IsNullOrEmpty( key ) && !string.IsNullOrEmpty( value ) && IsTranslatable( key ) )
  529. {
  530. AddTranslation( key, value );
  531. break;
  532. }
  533. }
  534. }
  535. }
  536. }
  537. }
  538. private void LoadStaticTranslations()
  539. {
  540. if( Settings.UseStaticTranslations && Settings.FromLanguage == Settings.DefaultFromLanguage && Settings.Language == Settings.DefaultLanguage )
  541. {
  542. var tab = new char[] { '\t' };
  543. var equals = new char[] { '=' };
  544. var splitters = new char[][] { tab, equals };
  545. // load static translations from previous titles
  546. string[] translations = Properties.Resources.StaticTranslations.Split( new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries );
  547. foreach( string translation in translations )
  548. {
  549. for( int i = 0 ; i < splitters.Length ; i++ )
  550. {
  551. var splitter = splitters[ i ];
  552. string[] kvp = translation.Split( splitter, StringSplitOptions.None );
  553. if( kvp.Length >= 2 )
  554. {
  555. string key = TextHelper.Decode( kvp[ 0 ].TrimIfConfigured() );
  556. string value = TextHelper.Decode( kvp[ 1 ].TrimIfConfigured() );
  557. if( !string.IsNullOrEmpty( key ) && !string.IsNullOrEmpty( value ) )
  558. {
  559. _staticTranslations[ key ] = value;
  560. break;
  561. }
  562. }
  563. }
  564. }
  565. }
  566. }
  567. private TranslationJob GetOrCreateTranslationJobFor( object ui, TranslationKey key, TranslationContext context )
  568. {
  569. var lookupKey = key.GetDictionaryLookupKey();
  570. if( _unstartedJobs.TryGetValue( lookupKey, out TranslationJob unstartedJob ) )
  571. {
  572. unstartedJob.Associate( context );
  573. return unstartedJob;
  574. }
  575. if( _ongoingJobs.TryGetValue( lookupKey, out TranslationJob ongoingJob ) )
  576. {
  577. ongoingJob.Associate( context );
  578. return ongoingJob;
  579. }
  580. foreach( var completedJob in _completedJobs )
  581. {
  582. if( completedJob.Key.GetDictionaryLookupKey() == lookupKey )
  583. {
  584. completedJob.Associate( context );
  585. return completedJob;
  586. }
  587. }
  588. XuaLogger.Current.Debug( "Queued: '" + lookupKey + "'" );
  589. ongoingJob = new TranslationJob( key );
  590. if( ui != null )
  591. {
  592. ongoingJob.OriginalSources.Add( ui );
  593. }
  594. ongoingJob.Associate( context );
  595. _unstartedJobs.Add( lookupKey, ongoingJob );
  596. CheckStaggerText( lookupKey );
  597. CheckConsecutiveFrames();
  598. CheckConsecutiveSeconds();
  599. CheckThresholds();
  600. return ongoingJob;
  601. }
  602. private void CheckConsecutiveSeconds()
  603. {
  604. var currentSecond = (int)Time.time;
  605. var lastSecond = currentSecond - 1;
  606. if( lastSecond == _secondForQueuedTranslation )
  607. {
  608. // we also queued something last frame, lets increment our counter
  609. _consecutiveSecondsTranslated++;
  610. if( _consecutiveSecondsTranslated > Settings.MaximumConsecutiveSecondsTranslated )
  611. {
  612. // Shutdown, this wont be tolerated!!!
  613. _unstartedJobs.Clear();
  614. _completedJobs.Clear();
  615. _ongoingJobs.Clear();
  616. Settings.IsShutdown = true;
  617. Settings.IsShutdownFatal = true;
  618. XuaLogger.Current.Error( $"SPAM DETECTED: Translations were queued every second for more than {Settings.MaximumConsecutiveSecondsTranslated} consecutive seconds. Shutting down plugin." );
  619. }
  620. }
  621. else if( currentSecond == _secondForQueuedTranslation )
  622. {
  623. // do nothing, there may be multiple translations per frame, that wont increase this counter
  624. }
  625. else
  626. {
  627. // but if multiple Update frames has passed, we will reset the counter
  628. _consecutiveSecondsTranslated = 0;
  629. }
  630. _secondForQueuedTranslation = currentSecond;
  631. }
  632. private void CheckConsecutiveFrames()
  633. {
  634. var currentFrame = Time.frameCount;
  635. var lastFrame = currentFrame - 1;
  636. if( lastFrame == _frameForLastQueuedTranslation )
  637. {
  638. // we also queued something last frame, lets increment our counter
  639. _consecutiveFramesTranslated++;
  640. if( _consecutiveFramesTranslated > Settings.MaximumConsecutiveFramesTranslated )
  641. {
  642. // Shutdown, this wont be tolerated!!!
  643. _unstartedJobs.Clear();
  644. _completedJobs.Clear();
  645. _ongoingJobs.Clear();
  646. Settings.IsShutdown = true;
  647. Settings.IsShutdownFatal = true;
  648. XuaLogger.Current.Error( $"SPAM DETECTED: Translations were queued every frame for more than {Settings.MaximumConsecutiveFramesTranslated} consecutive frames. Shutting down plugin." );
  649. }
  650. }
  651. else if( currentFrame == _frameForLastQueuedTranslation )
  652. {
  653. // do nothing, there may be multiple translations per frame, that wont increase this counter
  654. }
  655. else if( _consecutiveFramesTranslated > 0 )
  656. {
  657. // but if multiple Update frames has passed, we will reset the counter
  658. _consecutiveFramesTranslated--;
  659. }
  660. _frameForLastQueuedTranslation = currentFrame;
  661. }
  662. private void PeriodicResetFrameCheck()
  663. {
  664. var currentSecond = (int)Time.time;
  665. if( currentSecond % 100 == 0 )
  666. {
  667. _consecutiveFramesTranslated = 0;
  668. }
  669. }
  670. private void CheckStaggerText( string untranslatedText )
  671. {
  672. bool wasProblematic = false;
  673. for( int i = 0 ; i < _previouslyQueuedText.Length ; i++ )
  674. {
  675. var previouslyQueuedText = _previouslyQueuedText[ i ];
  676. if( previouslyQueuedText != null )
  677. {
  678. if( untranslatedText.RemindsOf( previouslyQueuedText ) )
  679. {
  680. wasProblematic = true;
  681. break;
  682. }
  683. }
  684. }
  685. if( wasProblematic )
  686. {
  687. _concurrentStaggers++;
  688. if( _concurrentStaggers > Settings.MaximumStaggers )
  689. {
  690. _unstartedJobs.Clear();
  691. _completedJobs.Clear();
  692. _ongoingJobs.Clear();
  693. Settings.IsShutdown = true;
  694. Settings.IsShutdownFatal = true;
  695. XuaLogger.Current.Error( $"SPAM DETECTED: Text that is 'scrolling in' is being translated. Disable that feature. Shutting down plugin." );
  696. }
  697. }
  698. else
  699. {
  700. _concurrentStaggers = 0;
  701. }
  702. _previouslyQueuedText[ _staggerTextCursor % _previouslyQueuedText.Length ] = untranslatedText;
  703. _staggerTextCursor++;
  704. }
  705. private void CheckThresholds()
  706. {
  707. if( _unstartedJobs.Count > Settings.MaxUnstartedJobs )
  708. {
  709. _unstartedJobs.Clear();
  710. _completedJobs.Clear();
  711. _ongoingJobs.Clear();
  712. Settings.IsShutdown = true;
  713. Settings.IsShutdownFatal = true;
  714. XuaLogger.Current.Error( $"SPAM DETECTED: More than {Settings.MaxUnstartedJobs} queued for translations due to unknown reasons. Shutting down plugin." );
  715. }
  716. var previousIdx = ( (int)( Time.time - Time.deltaTime ) ) % Settings.TranslationQueueWatchWindow;
  717. var newIdx = ( (int)Time.time ) % Settings.TranslationQueueWatchWindow;
  718. if( previousIdx != newIdx )
  719. {
  720. _currentTranslationsQueuedPerSecondRollingWindow[ newIdx ] = 0;
  721. }
  722. _currentTranslationsQueuedPerSecondRollingWindow[ newIdx ]++;
  723. var translationsInWindow = _currentTranslationsQueuedPerSecondRollingWindow.Sum();
  724. _translationsQueuedPerSecond = (float)translationsInWindow / Settings.TranslationQueueWatchWindow;
  725. if( _translationsQueuedPerSecond > Settings.MaxTranslationsQueuedPerSecond )
  726. {
  727. if( !_timeExceededThreshold.HasValue )
  728. {
  729. _timeExceededThreshold = Time.time;
  730. }
  731. if( Time.time - _timeExceededThreshold.Value > Settings.MaxSecondsAboveTranslationThreshold )
  732. {
  733. _unstartedJobs.Clear();
  734. _completedJobs.Clear();
  735. _ongoingJobs.Clear();
  736. Settings.IsShutdown = true;
  737. Settings.IsShutdownFatal = true;
  738. XuaLogger.Current.Error( $"SPAM DETECTED: More than {Settings.MaxTranslationsQueuedPerSecond} translations per seconds queued for a {Settings.MaxSecondsAboveTranslationThreshold} second period. Shutting down plugin." );
  739. }
  740. }
  741. else
  742. {
  743. _timeExceededThreshold = null;
  744. }
  745. }
  746. private void IncrementBatchOperations()
  747. {
  748. _batchOperationSecondCounter += Time.deltaTime;
  749. if( _batchOperationSecondCounter > Settings.IncreaseBatchOperationsEvery )
  750. {
  751. if( _availableBatchOperations < Settings.MaxAvailableBatchOperations )
  752. {
  753. _availableBatchOperations++;
  754. }
  755. _batchOperationSecondCounter = 0;
  756. }
  757. }
  758. private void ResetThresholdTimerIfRequired()
  759. {
  760. var previousIdx = ( (int)( Time.time - Time.deltaTime ) ) % Settings.TranslationQueueWatchWindow;
  761. var newIdx = ( (int)Time.time ) % Settings.TranslationQueueWatchWindow;
  762. if( previousIdx != newIdx )
  763. {
  764. _currentTranslationsQueuedPerSecondRollingWindow[ newIdx ] = 0;
  765. }
  766. var translationsInWindow = _currentTranslationsQueuedPerSecondRollingWindow.Sum();
  767. _translationsQueuedPerSecond = (float)translationsInWindow / Settings.TranslationQueueWatchWindow;
  768. if( _translationsQueuedPerSecond <= Settings.MaxTranslationsQueuedPerSecond )
  769. {
  770. _timeExceededThreshold = null;
  771. }
  772. }
  773. private bool IsImageRegistered( string key )
  774. {
  775. return _translatedImages.ContainsKey( key ) || _untranslatedImages.Contains( key );
  776. }
  777. private bool TryGetTranslatedImage( string key, out byte[] data )
  778. {
  779. return _translatedImages.TryGetValue( key, out data );
  780. }
  781. private void AddTranslation( string key, string value )
  782. {
  783. _translations[ key ] = value;
  784. _reverseTranslations[ value ] = key;
  785. }
  786. private void AddTranslation( TranslationKey key, string value )
  787. {
  788. var lookup = key.GetDictionaryLookupKey();
  789. _translations[ lookup ] = value;
  790. _reverseTranslations[ value ] = lookup;
  791. }
  792. private void UpdateSpriteRenderers()
  793. {
  794. if( Settings.EnableSpriteRendererHooking && ( Settings.EnableTextureTranslation || Settings.EnableTextureDumping ) )
  795. {
  796. if( _requireSpriteRendererCheckCausedBy != null )
  797. {
  798. try
  799. {
  800. var start = Time.realtimeSinceStartup;
  801. var spriteRenderers = GameObject.FindObjectsOfType<SpriteRenderer>();
  802. foreach( var sr in spriteRenderers )
  803. {
  804. // simulate a hook
  805. Hook_ImageChangedOnComponent( sr, null, false, false );
  806. }
  807. var end = Time.realtimeSinceStartup;
  808. var delta = Math.Round( end - start, 2 );
  809. XuaLogger.Current.Debug( $"Update SpriteRenderers caused by {_requireSpriteRendererCheckCausedBy} component (took " + delta + " seconds)" );
  810. }
  811. finally
  812. {
  813. _requireSpriteRendererCheckCausedBy = null;
  814. }
  815. }
  816. }
  817. }
  818. private void QueueNewUntranslatedForClipboard( TranslationKey key )
  819. {
  820. if( Settings.CopyToClipboard && Features.SupportsClipboard )
  821. {
  822. if( !_textsToCopyToClipboard.Contains( key.RelevantText ) )
  823. {
  824. _textsToCopyToClipboard.Add( key.RelevantText );
  825. _textsToCopyToClipboardOrdered.Add( key.RelevantText );
  826. _clipboardUpdated = Time.realtimeSinceStartup;
  827. }
  828. }
  829. }
  830. private void QueueNewUntranslatedForDisk( TranslationKey key )
  831. {
  832. _newUntranslated.Add( key.GetDictionaryLookupKey() );
  833. }
  834. private void QueueNewTranslationForDisk( TranslationKey key, string value )
  835. {
  836. lock( _writeToFileSync )
  837. {
  838. _newTranslations[ key.GetDictionaryLookupKey() ] = value;
  839. }
  840. }
  841. private void QueueNewTranslationForDisk( string key, string value )
  842. {
  843. lock( _writeToFileSync )
  844. {
  845. _newTranslations[ key ] = value;
  846. }
  847. }
  848. private bool TryGetTranslation( TranslationKey key, out string value )
  849. {
  850. return TryGetTranslation( key.GetDictionaryLookupKey(), out value );
  851. }
  852. private bool TryGetTranslation( string key, out string value )
  853. {
  854. var result = _translations.TryGetValue( key, out value );
  855. if( result )
  856. {
  857. return result;
  858. }
  859. else if( _staticTranslations.Count > 0 )
  860. {
  861. if( _staticTranslations.TryGetValue( key, out value ) )
  862. {
  863. QueueNewTranslationForDisk( key, value );
  864. AddTranslation( key, value );
  865. return true;
  866. }
  867. }
  868. return result;
  869. }
  870. internal bool TryGetReverseTranslation( string value, out string key )
  871. {
  872. return _reverseTranslations.TryGetValue( value, out key );
  873. }
  874. internal string Hook_TextChanged_WithResult( object ui, string text )
  875. {
  876. if( !ui.IsKnownTextType() ) return null;
  877. if( _textHooksEnabled && !_temporarilyDisabled )
  878. {
  879. return TranslateOrQueueWebJob( ui, text, false );
  880. }
  881. return null;
  882. }
  883. internal string ExternalHook_TextChanged_WithResult( object ui, string text )
  884. {
  885. if( !ui.IsKnownTextType() ) return null;
  886. if( _textHooksEnabled && !_temporarilyDisabled )
  887. {
  888. return TranslateOrQueueWebJob( ui, text, true );
  889. }
  890. return null;
  891. }
  892. internal void Hook_TextChanged( object ui, bool onEnable )
  893. {
  894. if( _textHooksEnabled && !_temporarilyDisabled )
  895. {
  896. TranslateOrQueueWebJob( ui, null, false );
  897. }
  898. if( onEnable )
  899. {
  900. CheckSpriteRenderer( ui );
  901. }
  902. }
  903. internal void Hook_ImageChangedOnComponent( object source, Texture2D texture, bool isPrefixHooked, bool onEnable )
  904. {
  905. if( !_imageHooksEnabled ) return;
  906. if( !source.IsKnownImageType() ) return;
  907. HandleImage( source, texture, isPrefixHooked );
  908. if( onEnable )
  909. {
  910. CheckSpriteRenderer( source );
  911. }
  912. }
  913. internal void Hook_ImageChanged( Texture2D texture, bool isPrefixHooked )
  914. {
  915. if( !_imageHooksEnabled ) return;
  916. if( texture == null ) return;
  917. HandleImage( null, texture, isPrefixHooked );
  918. }
  919. private void SetTranslatedText( object ui, string translatedText, TextTranslationInfo info )
  920. {
  921. info?.SetTranslatedText( translatedText );
  922. if( _isInTranslatedMode )
  923. {
  924. SetText( ui, translatedText, true, info );
  925. }
  926. }
  927. internal void Hook_HandleComponent( object ui )
  928. {
  929. if( _hasOverrideFont )
  930. {
  931. var info = ui.GetOrCreateTextTranslationInfo();
  932. if( _overrideFont )
  933. {
  934. info?.ChangeFont( ui );
  935. }
  936. else
  937. {
  938. info?.UnchangeFont( ui );
  939. }
  940. }
  941. if( Settings.ForceUIResizing )
  942. {
  943. var info = ui.GetOrCreateTextTranslationInfo();
  944. if( info?.IsCurrentlySettingText == false )
  945. {
  946. // force UI resizing is highly problematic for NGUI because text should somehow
  947. // be set after changing "resize" properties... brilliant stuff
  948. if( ui.GetType() != ClrTypes.UILabel )
  949. {
  950. info?.ResizeUI( ui );
  951. }
  952. }
  953. }
  954. }
  955. private void CheckSpriteRenderer( object ui )
  956. {
  957. if( Settings.EnableSpriteRendererHooking )
  958. {
  959. var currentFrame = Time.frameCount;
  960. var lastFrame = currentFrame - 1;
  961. if( lastFrame != _lastSpriteUpdateFrame && currentFrame != _lastSpriteUpdateFrame )
  962. {
  963. _requireSpriteRendererCheckCausedBy = ui?.GetType().Name;
  964. }
  965. _lastSpriteUpdateFrame = currentFrame;
  966. }
  967. }
  968. /// <summary>
  969. /// Sets the text of a UI text, while ensuring this will not fire a text changed event.
  970. /// </summary>
  971. private void SetText( object ui, string text, bool isTranslated, TextTranslationInfo info )
  972. {
  973. if( !info?.IsCurrentlySettingText ?? true )
  974. {
  975. try
  976. {
  977. _textHooksEnabled = false;
  978. if( info != null )
  979. {
  980. info.IsCurrentlySettingText = true;
  981. }
  982. if( Settings.EnableUIResizing || Settings.ForceUIResizing )
  983. {
  984. if( isTranslated || Settings.ForceUIResizing )
  985. {
  986. info?.ResizeUI( ui );
  987. }
  988. else
  989. {
  990. info?.UnresizeUI( ui );
  991. }
  992. }
  993. // NGUI only behaves if you set the text after the resize behaviour
  994. ui.SetText( text );
  995. info?.ResetScrollIn( ui );
  996. }
  997. catch( TargetInvocationException )
  998. {
  999. // might happen with NGUI
  1000. }
  1001. catch( NullReferenceException )
  1002. {
  1003. // This is likely happened due to a scene change.
  1004. }
  1005. catch( Exception e )
  1006. {
  1007. XuaLogger.Current.Error( e, "An error occurred while setting text on a component." );
  1008. }
  1009. finally
  1010. {
  1011. _textHooksEnabled = true;
  1012. if( info != null )
  1013. {
  1014. info.IsCurrentlySettingText = false;
  1015. }
  1016. }
  1017. }
  1018. }
  1019. /// <summary>
  1020. /// Determines if a text should be translated.
  1021. /// </summary>
  1022. private bool IsTranslatable( string str )
  1023. {
  1024. return _symbolCheck( str )
  1025. //&& str.Length <= Settings.MaxCharactersPerTranslation
  1026. && !_reverseTranslations.ContainsKey( str )
  1027. && !Settings.IgnoreTextStartingWith.Any( x => str.StartsWithStrict( x ) );
  1028. }
  1029. private bool IsBelowMaxLength( string str )
  1030. {
  1031. return str.Length <= Settings.MaxCharactersPerTranslation;
  1032. }
  1033. private bool IsBelowMaxLengthStrict( string str )
  1034. {
  1035. return str.Length <= ( Settings.MaxCharactersPerTranslation / 2 );
  1036. }
  1037. private bool ShouldTranslateImageComponent( object ui )
  1038. {
  1039. var component = ui as Component;
  1040. if( component != null )
  1041. {
  1042. // dummy check
  1043. var go = component.gameObject;
  1044. var ignore = go.HasIgnoredName();
  1045. if( ignore )
  1046. {
  1047. return false;
  1048. }
  1049. var behaviour = component as Behaviour;
  1050. if( behaviour?.isActiveAndEnabled == false )
  1051. {
  1052. return false;
  1053. }
  1054. }
  1055. return true;
  1056. }
  1057. private bool ShouldTranslateTextComponent( object ui, bool ignoreComponentState )
  1058. {
  1059. var component = ui as Component;
  1060. if( component != null )
  1061. {
  1062. // dummy check
  1063. var go = component.gameObject;
  1064. var ignore = go.HasIgnoredName();
  1065. if( ignore )
  1066. {
  1067. return false;
  1068. }
  1069. if( !ignoreComponentState )
  1070. {
  1071. var behaviour = component as Behaviour;
  1072. if( behaviour?.isActiveAndEnabled == false )
  1073. {
  1074. return false;
  1075. }
  1076. }
  1077. var inputField = component.gameObject.GetFirstComponentInSelfOrAncestor( ClrTypes.InputField )
  1078. ?? component.gameObject.GetFirstComponentInSelfOrAncestor( ClrTypes.TMP_InputField );
  1079. return inputField == null;
  1080. }
  1081. return true;
  1082. }
  1083. private string TranslateOrQueueWebJob( object ui, string text, bool ignoreComponentState )
  1084. {
  1085. var info = ui.GetOrCreateTextTranslationInfo();
  1086. if( _ongoingOperations.Contains( ui ) )
  1087. {
  1088. return TranslateImmediate( ui, text, info, ignoreComponentState );
  1089. }
  1090. var supportsStabilization = ui.SupportsStabilization();
  1091. if( Settings.Delay == 0 || !supportsStabilization )
  1092. {
  1093. return TranslateOrQueueWebJobImmediate( ui, text, info, supportsStabilization, ignoreComponentState );
  1094. }
  1095. else
  1096. {
  1097. StartCoroutine(
  1098. DelayForSeconds( Settings.Delay, () =>
  1099. {
  1100. TranslateOrQueueWebJobImmediate( ui, text, info, supportsStabilization, ignoreComponentState );
  1101. } ) );
  1102. }
  1103. return null;
  1104. }
  1105. private static bool IsCurrentlySetting( TextTranslationInfo info )
  1106. {
  1107. if( info == null ) return false;
  1108. return info.IsCurrentlySettingText;
  1109. }
  1110. private void HandleImage( object source, Texture2D texture, bool isPrefixHooked )
  1111. {
  1112. if( Settings.EnableTextureDumping )
  1113. {
  1114. try
  1115. {
  1116. DumpTexture( source, texture );
  1117. }
  1118. catch( Exception e )
  1119. {
  1120. XuaLogger.Current.Error( e, "An error occurred while dumping texture." );
  1121. }
  1122. }
  1123. if( Settings.EnableTextureTranslation )
  1124. {
  1125. try
  1126. {
  1127. TranslateTexture( source, texture, isPrefixHooked, null );
  1128. }
  1129. catch( Exception e )
  1130. {
  1131. XuaLogger.Current.Error( e, "An error occurred while translating texture." );
  1132. }
  1133. }
  1134. }
  1135. private void TranslateTexture( object ui, TextureReloadContext context )
  1136. {
  1137. if( ui is Texture2D texture2d )
  1138. {
  1139. TranslateTexture( null, texture2d, false, context );
  1140. }
  1141. else
  1142. {
  1143. TranslateTexture( ui, null, false, context );
  1144. }
  1145. }
  1146. private void TranslateTexture( object source, Texture2D texture, bool isPrefixHooked, TextureReloadContext context )
  1147. {
  1148. try
  1149. {
  1150. _imageHooksEnabled = false;
  1151. texture = texture ?? source.GetTexture();
  1152. if( texture == null ) return;
  1153. var tti = texture.GetOrCreateTextureTranslationInfo();
  1154. var iti = source.GetOrCreateImageTranslationInfo();
  1155. var key = tti.GetKey( texture );
  1156. if( string.IsNullOrEmpty( key ) ) return;
  1157. bool hasContext = context != null;
  1158. bool forceReload = false;
  1159. if( hasContext )
  1160. {
  1161. forceReload = context.RegisterTextureInContextAndDetermineWhetherToReload( texture );
  1162. }
  1163. if( TryGetTranslatedImage( key, out var newData ) )
  1164. {
  1165. if( _isInTranslatedMode )
  1166. {
  1167. // handle texture
  1168. if( !tti.IsTranslated || forceReload )
  1169. {
  1170. try
  1171. {
  1172. texture.LoadImageEx( newData, tti.IsNonReadable( texture ) );
  1173. }
  1174. finally
  1175. {
  1176. tti.IsTranslated = true;
  1177. }
  1178. }
  1179. // handle containing component
  1180. if( iti != null )
  1181. {
  1182. if( !iti.IsTranslated || hasContext )
  1183. {
  1184. try
  1185. {
  1186. if( !isPrefixHooked )
  1187. {
  1188. source.SetAllDirtyEx();
  1189. }
  1190. }
  1191. finally
  1192. {
  1193. iti.IsTranslated = true;
  1194. }
  1195. }
  1196. }
  1197. }
  1198. }
  1199. else
  1200. {
  1201. // if we cannot find the texture, and the texture is considered translated... hmmm someone has removed a file
  1202. // handle texture
  1203. var originalData = tti.GetOriginalData( texture );
  1204. if( originalData != null )
  1205. {
  1206. if( tti.IsTranslated )
  1207. {
  1208. try
  1209. {
  1210. texture.LoadImageEx( originalData, tti.IsNonReadable( texture ) );
  1211. }
  1212. finally
  1213. {
  1214. tti.IsTranslated = true;
  1215. }
  1216. }
  1217. // handle containing component
  1218. if( iti != null )
  1219. {
  1220. if( iti.IsTranslated )
  1221. {
  1222. try
  1223. {
  1224. if( !isPrefixHooked )
  1225. {
  1226. source.SetAllDirtyEx();
  1227. }
  1228. }
  1229. finally
  1230. {
  1231. iti.IsTranslated = true;
  1232. }
  1233. }
  1234. }
  1235. }
  1236. }
  1237. if( !_isInTranslatedMode )
  1238. {
  1239. var originalData = tti.GetOriginalData( texture );
  1240. if( originalData != null )
  1241. {
  1242. // handle texture
  1243. if( tti.IsTranslated )
  1244. {
  1245. try
  1246. {
  1247. texture.LoadImageEx( originalData, tti.IsNonReadable( texture ) );
  1248. }
  1249. finally
  1250. {
  1251. tti.IsTranslated = false;
  1252. }
  1253. }
  1254. // handle containing component
  1255. if( iti != null )
  1256. {
  1257. if( iti.IsTranslated )
  1258. {
  1259. try
  1260. {
  1261. if( !isPrefixHooked )
  1262. {
  1263. source.SetAllDirtyEx();
  1264. }
  1265. }
  1266. finally
  1267. {
  1268. iti.IsTranslated = false;
  1269. }
  1270. }
  1271. }
  1272. }
  1273. }
  1274. if( forceReload )
  1275. {
  1276. XuaLogger.Current.Info( $"Reloaded texture: {texture.name} ({key})." );
  1277. }
  1278. }
  1279. finally
  1280. {
  1281. _imageHooksEnabled = true;
  1282. }
  1283. }
  1284. private void DumpTexture( object source, Texture2D texture )
  1285. {
  1286. try
  1287. {
  1288. _imageHooksEnabled = false;
  1289. texture = texture ?? source.GetTexture();
  1290. if( texture == null ) return;
  1291. var info = texture.GetOrCreateTextureTranslationInfo();
  1292. if( info.HasDumpedAlternativeTexture ) return;
  1293. try
  1294. {
  1295. if( ShouldTranslate( texture ) )
  1296. {
  1297. var key = info.GetKey( texture );
  1298. if( string.IsNullOrEmpty( key ) ) return;
  1299. if( !IsImageRegistered( key ) )
  1300. {
  1301. var name = texture.GetTextureName();
  1302. //var format = "[" + texture.format.ToString() + "] ";
  1303. var originalData = info.GetOrCreateOriginalData( texture );
  1304. RegisterImageFromData( name, key, originalData );
  1305. }
  1306. }
  1307. }
  1308. finally
  1309. {
  1310. info.HasDumpedAlternativeTexture = true;
  1311. }
  1312. }
  1313. finally
  1314. {
  1315. _imageHooksEnabled = true;
  1316. }
  1317. }
  1318. private bool ShouldTranslate( Texture2D texture )
  1319. {
  1320. // convert to int so engine versions that does not have specific enums still work
  1321. var format = (int)texture.format;
  1322. // 1 = Alpha8
  1323. // 9 = R16
  1324. // 63 = R8
  1325. return format != 1
  1326. && format != 9
  1327. && format != 63;
  1328. }
  1329. private string TranslateImmediate( object ui, string text, TextTranslationInfo info, bool ignoreComponentState )
  1330. {
  1331. // Get the trimmed text
  1332. text = ( text ?? ui.GetText() ).TrimIfConfigured();
  1333. if( !string.IsNullOrEmpty( text ) && IsTranslatable( text ) && ShouldTranslateTextComponent( ui, ignoreComponentState ) && !IsCurrentlySetting( info ) )
  1334. {
  1335. info?.Reset( text );
  1336. var textKey = new TranslationKey( ui, text, ui.IsSpammingComponent(), false );
  1337. // if we already have translation loaded in our _translatios dictionary, simply load it and set text
  1338. string translation;
  1339. if( TryGetTranslation( textKey, out translation ) )
  1340. {
  1341. if( !string.IsNullOrEmpty( translation ) )
  1342. {
  1343. SetTranslatedText( ui, textKey.Untemplate( translation ), info );
  1344. return translation;
  1345. }
  1346. }
  1347. else
  1348. {
  1349. if( UnityTextParsers.GameLogTextParser.CanApply( ui ) )
  1350. {
  1351. var result = UnityTextParsers.GameLogTextParser.Parse( text );
  1352. if( result.Succeeded )
  1353. {
  1354. translation = TranslateOrQueueWebJobImmediateByParserResult( ui, result, false );
  1355. if( translation != null )
  1356. {
  1357. SetTranslatedText( ui, translation, info );
  1358. return translation;
  1359. }
  1360. }
  1361. }
  1362. }
  1363. }
  1364. return null;
  1365. }
  1366. /// <summary>
  1367. /// Translates the string of a UI text or queues it up to be translated
  1368. /// by the HTTP translation service.
  1369. /// </summary>
  1370. private string TranslateOrQueueWebJobImmediate( object ui, string text, TextTranslationInfo info, bool supportsStabilization, bool ignoreComponentState, TranslationContext context = null )
  1371. {
  1372. text = text ?? ui.GetText();
  1373. // make sure text exists
  1374. var originalText = text;
  1375. if( context == null )
  1376. {
  1377. // Get the trimmed text
  1378. text = text.TrimIfConfigured();
  1379. }
  1380. // Ensure that we actually want to translate this text and its owning UI element.
  1381. if( !string.IsNullOrEmpty( text ) && IsTranslatable( text ) && ShouldTranslateTextComponent( ui, ignoreComponentState ) && !IsCurrentlySetting( info ) )
  1382. {
  1383. //Logger.Current.Debug( "START: " + ui.GetType().Name + ": " + text );
  1384. info?.Reset( originalText );
  1385. var isSpammer = ui.IsSpammingComponent();
  1386. var textKey = new TranslationKey( ui, text, isSpammer, context != null );
  1387. // if we already have translation loaded in our _translatios dictionary, simply load it and set text
  1388. string translation;
  1389. if( TryGetTranslation( textKey, out translation ) )
  1390. {
  1391. QueueNewUntranslatedForClipboard( textKey );
  1392. if( !string.IsNullOrEmpty( translation ) )
  1393. {
  1394. if( context == null ) // never set text if operation is contextualized (only a part translation)
  1395. {
  1396. SetTranslatedText( ui, textKey.Untemplate( translation ), info );
  1397. }
  1398. return translation;
  1399. }
  1400. }
  1401. else
  1402. {
  1403. if( context == null )
  1404. {
  1405. if( UnityTextParsers.GameLogTextParser.CanApply( ui ) )
  1406. {
  1407. var result = UnityTextParsers.GameLogTextParser.Parse( text );
  1408. if( result.Succeeded )
  1409. {
  1410. translation = TranslateOrQueueWebJobImmediateByParserResult( ui, result, false );
  1411. if( translation != null )
  1412. {
  1413. SetTranslatedText( ui, translation, info );
  1414. return translation;
  1415. }
  1416. }
  1417. }
  1418. else if( UnityTextParsers.RichTextParser.CanApply( ui ) && IsBelowMaxLength( text ) )
  1419. {
  1420. var result = UnityTextParsers.RichTextParser.Parse( text );
  1421. if( result.Succeeded )
  1422. {
  1423. var isWhitelisted = ui.IsWhitelistedForImmediateRichTextTranslation();
  1424. translation = TranslateOrQueueWebJobImmediateByParserResult( ui, result, isWhitelisted );
  1425. if( translation != null )
  1426. {
  1427. SetTranslatedText( ui, translation, info );
  1428. return translation;
  1429. }
  1430. else if( isWhitelisted )
  1431. {
  1432. return null;
  1433. }
  1434. }
  1435. }
  1436. }
  1437. if( supportsStabilization && context == null ) // never stabilize a text that is contextualized or that does not support stabilization
  1438. {
  1439. // if we dont know what text to translate it to, we need to figure it out.
  1440. // this might take a while, so add the UI text component to the ongoing operations
  1441. // list, so we dont start multiple operations for it, as its text might be constantly
  1442. // changing.
  1443. _ongoingOperations.Add( ui );
  1444. // start a coroutine, that will execute once the string of the UI text has stopped
  1445. // changing. For all texts except 'story' texts, this will add a delay for exactly
  1446. // 0.5s to the translation. This is barely noticable.
  1447. //
  1448. // on the other hand, for 'story' texts, this will take the time that it takes
  1449. // for the text to stop 'scrolling' in.
  1450. try
  1451. {
  1452. StartCoroutine(
  1453. WaitForTextStablization(
  1454. ui: ui,
  1455. delay: 1.0f, // 1 second to prevent '1 second tickers' from getting translated
  1456. maxTries: 60, // 50 tries, about 1 minute
  1457. currentTries: 0,
  1458. onMaxTriesExceeded: () =>
  1459. {
  1460. _ongoingOperations.Remove( ui );
  1461. },
  1462. onTextStabilized: stabilizedText =>
  1463. {
  1464. _ongoingOperations.Remove( ui );
  1465. originalText = stabilizedText;
  1466. stabilizedText = stabilizedText.TrimIfConfigured();
  1467. if( !string.IsNullOrEmpty( stabilizedText ) && IsTranslatable( stabilizedText ) )
  1468. {
  1469. var stabilizedTextKey = new TranslationKey( ui, stabilizedText, false );
  1470. QueueNewUntranslatedForClipboard( stabilizedTextKey );
  1471. info?.Reset( originalText );
  1472. // once the text has stabilized, attempt to look it up
  1473. if( TryGetTranslation( stabilizedTextKey, out translation ) )
  1474. {
  1475. if( !string.IsNullOrEmpty( translation ) )
  1476. {
  1477. // stabilized, no need to untemplate
  1478. SetTranslatedText( ui, translation, info );
  1479. }
  1480. }
  1481. else
  1482. {
  1483. if( context == null )
  1484. {
  1485. if( UnityTextParsers.GameLogTextParser.CanApply( ui ) )
  1486. {
  1487. var result = UnityTextParsers.GameLogTextParser.Parse( stabilizedText );
  1488. if( result.Succeeded )
  1489. {
  1490. var translatedText = TranslateOrQueueWebJobImmediateByParserResult( ui, result, true );
  1491. if( translatedText != null )
  1492. {
  1493. // stabilized, no need to untemplate
  1494. SetTranslatedText( ui, translatedText, info );
  1495. }
  1496. return;
  1497. }
  1498. }
  1499. else if( UnityTextParsers.RichTextParser.CanApply( ui ) && IsBelowMaxLength( stabilizedText ) )
  1500. {
  1501. var result = UnityTextParsers.RichTextParser.Parse( stabilizedText );
  1502. if( result.Succeeded )
  1503. {
  1504. var translatedText = TranslateOrQueueWebJobImmediateByParserResult( ui, result, true );
  1505. if( translatedText != null )
  1506. {
  1507. // stabilized, no need to untemplate
  1508. SetTranslatedText( ui, translatedText, info );
  1509. }
  1510. return;
  1511. }
  1512. }
  1513. }
  1514. // Lets try not to spam a service that might not be there...
  1515. if( _endpoint != null )
  1516. {
  1517. if( IsBelowMaxLength( stabilizedText ) )
  1518. {
  1519. if( !Settings.IsShutdown )
  1520. {
  1521. var job = GetOrCreateTranslationJobFor( ui, stabilizedTextKey, context );
  1522. job.Components.Add( ui );
  1523. }
  1524. }
  1525. }
  1526. else
  1527. {
  1528. QueueNewUntranslatedForDisk( stabilizedTextKey );
  1529. }
  1530. }
  1531. }
  1532. } ) );
  1533. }
  1534. catch( Exception )
  1535. {
  1536. _ongoingOperations.Remove( ui );
  1537. }
  1538. }
  1539. else if( !isSpammer || ( isSpammer && IsBelowMaxLengthStrict( text ) ) )
  1540. {
  1541. if( context != null )
  1542. {
  1543. // if there is a context, this is a part-translation, which means it is not a candidate for scrolling-in text
  1544. if( _endpoint != null )
  1545. {
  1546. if( !Settings.IsShutdown )
  1547. {
  1548. // once the text has stabilized, attempt to look it up
  1549. var job = GetOrCreateTranslationJobFor( ui, textKey, context );
  1550. }
  1551. }
  1552. else
  1553. {
  1554. QueueNewUntranslatedForDisk( textKey );
  1555. }
  1556. }
  1557. else
  1558. {
  1559. StartCoroutine(
  1560. WaitForTextStablization(
  1561. textKey: textKey,
  1562. delay: 1.0f,
  1563. onTextStabilized: () =>
  1564. {
  1565. // Lets try not to spam a service that might not be there...
  1566. if( _endpoint != null )
  1567. {
  1568. // once the text has stabilized, attempt to look it up
  1569. if( !Settings.IsShutdown )
  1570. {
  1571. if( !TryGetTranslation( textKey, out translation ) )
  1572. {
  1573. var job = GetOrCreateTranslationJobFor( ui, textKey, context );
  1574. }
  1575. }
  1576. }
  1577. else
  1578. {
  1579. QueueNewUntranslatedForDisk( textKey );
  1580. }
  1581. } ) );
  1582. }
  1583. }
  1584. }
  1585. }
  1586. return null;
  1587. }
  1588. private string TranslateOrQueueWebJobImmediateByParserResult( object ui, ParserResult result, bool allowStartJob )
  1589. {
  1590. Dictionary<string, string> translations = new Dictionary<string, string>();
  1591. // attempt to lookup ALL strings immediately; return result if possible; queue operations
  1592. foreach( var kvp in result.Arguments )
  1593. {
  1594. var key = kvp.Key;
  1595. var value = kvp.Value.TrimIfConfigured();
  1596. if( !string.IsNullOrEmpty( value ) && IsTranslatable( value ) && IsBelowMaxLength( value ) )
  1597. {
  1598. string partTranslation;
  1599. if( TryGetTranslation( value, out partTranslation ) )
  1600. {
  1601. translations.Add( key, partTranslation );
  1602. }
  1603. else if( allowStartJob )
  1604. {
  1605. // incomplete, must start job
  1606. var context = new TranslationContext( ui, result );
  1607. TranslateOrQueueWebJobImmediate( ui, value, null, false, true, context );
  1608. }
  1609. }
  1610. else
  1611. {
  1612. // the value will do
  1613. translations.Add( key, value );
  1614. }
  1615. }
  1616. if( result.Arguments.Count == translations.Count )
  1617. {
  1618. return result.Untemplate( translations );
  1619. }
  1620. else
  1621. {
  1622. return null; // could not perform complete translation
  1623. }
  1624. }
  1625. /// <summary>
  1626. /// Utility method that allows me to wait to call an action, until
  1627. /// the text has stopped changing. This is important for 'story'
  1628. /// mode text, which 'scrolls' into place slowly.
  1629. /// </summary>
  1630. private IEnumerator WaitForTextStablization( object ui, float delay, int maxTries, int currentTries, Action<string> onTextStabilized, Action onMaxTriesExceeded )
  1631. {
  1632. yield return 0; // wait a single frame to allow any external plugins to complete their hooking logic
  1633. bool succeeded = false;
  1634. while( currentTries < maxTries ) // shortcircuit
  1635. {
  1636. var beforeText = ui.GetText();
  1637. yield return new WaitForSeconds( delay );
  1638. var afterText = ui.GetText();
  1639. //Logger.Current.Debug( "WAITING: " + ui.GetType().Name + ": " + afterText );
  1640. if( beforeText == afterText )
  1641. {
  1642. onTextStabilized( afterText );
  1643. succeeded = true;
  1644. break;
  1645. }
  1646. currentTries++;
  1647. }
  1648. if( !succeeded )
  1649. {
  1650. onMaxTriesExceeded();
  1651. }
  1652. }
  1653. /// <summary>
  1654. /// Utility method that allows me to wait to call an action, until
  1655. /// the text has stopped changing. This is important for 'story'
  1656. /// mode text, which 'scrolls' into place slowly. This version is
  1657. /// for global text, where the component cannot tell us if the text
  1658. /// has changed itself.
  1659. /// </summary>
  1660. private IEnumerator WaitForTextStablization( TranslationKey textKey, float delay, Action onTextStabilized, Action onFailed = null )
  1661. {
  1662. var text = textKey.GetDictionaryLookupKey();
  1663. if( !_immediatelyTranslating.Contains( text ) )
  1664. {
  1665. _immediatelyTranslating.Add( text );
  1666. try
  1667. {
  1668. yield return new WaitForSeconds( delay );
  1669. bool succeeded = true;
  1670. foreach( var otherImmediatelyTranslating in _immediatelyTranslating )
  1671. {
  1672. if( text != otherImmediatelyTranslating )
  1673. {
  1674. if( text.RemindsOf( otherImmediatelyTranslating ) )
  1675. {
  1676. succeeded = false;
  1677. break;
  1678. }
  1679. }
  1680. }
  1681. if( succeeded )
  1682. {
  1683. onTextStabilized();
  1684. }
  1685. else
  1686. {
  1687. onFailed?.Invoke();
  1688. }
  1689. }
  1690. finally
  1691. {
  1692. _immediatelyTranslating.Remove( text );
  1693. }
  1694. }
  1695. }
  1696. private IEnumerator DelayForSeconds( float delay, Action onContinue )
  1697. {
  1698. yield return new WaitForSeconds( delay );
  1699. onContinue();
  1700. }
  1701. private IEnumerator EnableBatchingAfterDelay()
  1702. {
  1703. yield return new WaitForSeconds( 60 );
  1704. _batchLogicHasFailed = false;
  1705. XuaLogger.Current.Error( "Re-enabled batching." );
  1706. }
  1707. void Awake()
  1708. {
  1709. if( !_initialized )
  1710. {
  1711. _initialized = true;
  1712. try
  1713. {
  1714. Initialize();
  1715. ManualHook();
  1716. }
  1717. catch( Exception e )
  1718. {
  1719. XuaLogger.Current.Error( e, "An unexpected error occurred during plugin initialization." );
  1720. }
  1721. }
  1722. }
  1723. void Start()
  1724. {
  1725. try
  1726. {
  1727. HooksSetup.InstallOverrideTextHooks();
  1728. }
  1729. catch( Exception e )
  1730. {
  1731. XuaLogger.Current.Error( e, "An unexpected error occurred during plugin start." );
  1732. }
  1733. }
  1734. void Update()
  1735. {
  1736. try
  1737. {
  1738. // perform this check every 100 frames!
  1739. if( Time.frameCount % 100 == 0 )
  1740. {
  1741. ConnectionTrackingWebClient.CheckServicePoints();
  1742. }
  1743. if( Features.SupportsClipboard )
  1744. {
  1745. CopyToClipboard();
  1746. }
  1747. if( !Settings.IsShutdown )
  1748. {
  1749. UpdateSpriteRenderers();
  1750. PeriodicResetFrameCheck();
  1751. IncrementBatchOperations();
  1752. ResetThresholdTimerIfRequired();
  1753. KickoffTranslations();
  1754. FinishTranslations();
  1755. if( ClrTypes.AdvEngine != null && _nextAdvUpdate.HasValue && Time.time > _nextAdvUpdate )
  1756. {
  1757. _nextAdvUpdate = null;
  1758. UpdateUtageText();
  1759. }
  1760. }
  1761. if( Input.anyKey )
  1762. {
  1763. var isAltPressed = Input.GetKey( KeyCode.LeftAlt ) || Input.GetKey( KeyCode.RightAlt );
  1764. if( Settings.EnablePrintHierarchy && isAltPressed && Input.GetKeyDown( KeyCode.Y ) )
  1765. {
  1766. PrintObjects();
  1767. }
  1768. else if( isAltPressed && Input.GetKeyDown( KeyCode.T ) )
  1769. {
  1770. ToggleTranslation();
  1771. }
  1772. else if( isAltPressed && Input.GetKeyDown( KeyCode.F ) )
  1773. {
  1774. ToggleFont();
  1775. }
  1776. else if( isAltPressed && Input.GetKeyDown( KeyCode.D ) )
  1777. {
  1778. DumpUntranslated();
  1779. }
  1780. else if( isAltPressed && Input.GetKeyDown( KeyCode.R ) )
  1781. {
  1782. ReloadTranslations();
  1783. }
  1784. else if( isAltPressed && Input.GetKeyDown( KeyCode.U ) )
  1785. {
  1786. ManualHook();
  1787. }
  1788. else if( isAltPressed && Input.GetKeyDown( KeyCode.Q ) )
  1789. {
  1790. RebootPlugin();
  1791. }
  1792. else if( isAltPressed && ( Input.GetKeyDown( KeyCode.Alpha0 ) || Input.GetKeyDown( KeyCode.Keypad0 ) ) )
  1793. {
  1794. if( _window != null )
  1795. {
  1796. _window.IsShown = !_window.IsShown;
  1797. }
  1798. }
  1799. }
  1800. }
  1801. catch( Exception e )
  1802. {
  1803. XuaLogger.Current.Error( e, "An error occurred in Update callback. " );
  1804. }
  1805. }
  1806. void OnGUI()
  1807. {
  1808. if( _window != null )
  1809. {
  1810. try
  1811. {
  1812. DisableAutoTranslator();
  1813. if( _window.IsShown ) _window.OnGUI();
  1814. }
  1815. catch( Exception e )
  1816. {
  1817. XuaLogger.Current.Error( e, "An error occurred in XUnity.AutoTranslator UI. Disabling the UI." );
  1818. _window = null;
  1819. }
  1820. finally
  1821. {
  1822. EnableAutoTranslator();
  1823. }
  1824. }
  1825. }
  1826. private void RebootPlugin()
  1827. {
  1828. if( Settings.IsShutdown )
  1829. {
  1830. if( !Settings.IsShutdownFatal )
  1831. {
  1832. _consecutiveErrors = 0;
  1833. Settings.IsShutdown = false;
  1834. XuaLogger.Current.Info( "Rebooted Auto Translator." );
  1835. }
  1836. else
  1837. {
  1838. XuaLogger.Current.Info( "Cannot reboot Auto Translator because the error that caused the shutdown is bad behaviour by the game." );
  1839. }
  1840. }
  1841. else
  1842. {
  1843. XuaLogger.Current.Info( "Cannot reboot Auto Translator because it has not been shut down." );
  1844. }
  1845. }
  1846. private void KickoffTranslations()
  1847. {
  1848. if( _endpoint == null ) return;
  1849. if( Settings.EnableBatching && _endpoint.Endpoint.MaxTranslationsPerRequest > 1 && !_batchLogicHasFailed && _unstartedJobs.Count > 1 && _availableBatchOperations > 0 )
  1850. {
  1851. while( _unstartedJobs.Count > 0 && _availableBatchOperations > 0 )
  1852. {
  1853. if( _endpoint.IsBusy ) break;
  1854. var kvps = _unstartedJobs.Take( _endpoint.Endpoint.MaxTranslationsPerRequest ).ToList();
  1855. var untranslatedTexts = new List<string>();
  1856. var jobs = new List<TranslationJob>();
  1857. foreach( var kvp in kvps )
  1858. {
  1859. var key = kvp.Key;
  1860. var job = kvp.Value;
  1861. _unstartedJobs.Remove( key );
  1862. if( !job.AnyComponentsStillHasOriginalUntranslatedTextOrContextual() ) continue;
  1863. jobs.Add( job );
  1864. untranslatedTexts.Add( job.Key.GetDictionaryLookupKey() );
  1865. _ongoingJobs[ key ] = job;
  1866. }
  1867. if( jobs.Count > 0 )
  1868. {
  1869. _availableBatchOperations--;
  1870. var jobsArray = jobs.ToArray();
  1871. foreach( var untranslatedText in untranslatedTexts )
  1872. {
  1873. XuaLogger.Current.Debug( "Started: '" + untranslatedText + "'" );
  1874. }
  1875. StartCoroutine(
  1876. _endpoint.Translate(
  1877. untranslatedTexts.ToArray(),
  1878. Settings.FromLanguage,
  1879. Settings.Language,
  1880. translatedText => OnBatchTranslationCompleted( jobsArray, translatedText ),
  1881. ( msg, e ) => OnTranslationFailed( jobsArray, msg, e ) ) );
  1882. }
  1883. }
  1884. }
  1885. else
  1886. {
  1887. while( _unstartedJobs.Count > 0 )
  1888. {
  1889. if( _endpoint.IsBusy ) break;
  1890. var kvp = _unstartedJobs.FirstOrDefault();
  1891. var key = kvp.Key;
  1892. var job = kvp.Value;
  1893. _unstartedJobs.Remove( key );
  1894. // lets see if the text should still be translated before kicking anything off
  1895. if( !job.AnyComponentsStillHasOriginalUntranslatedTextOrContextual() ) continue;
  1896. _ongoingJobs[ key ] = job;
  1897. var untranslatedText = job.Key.GetDictionaryLookupKey();
  1898. XuaLogger.Current.Debug( "Started: " + untranslatedText );
  1899. StartCoroutine(
  1900. _endpoint.Translate(
  1901. new[] { untranslatedText },
  1902. Settings.FromLanguage,
  1903. Settings.Language,
  1904. translatedText => OnSingleTranslationCompleted( job, translatedText ),
  1905. ( msg, e ) => OnTranslationFailed( new[] { job }, msg, e ) ) );
  1906. }
  1907. }
  1908. }
  1909. private void OnBatchTranslationCompleted( TranslationJob[] jobs, string[] translatedTexts )
  1910. {
  1911. _consecutiveErrors = 0;
  1912. var succeeded = jobs.Length == translatedTexts.Length;
  1913. if( succeeded )
  1914. {
  1915. for( int i = 0 ; i < jobs.Length ; i++ )
  1916. {
  1917. Settings.TranslationCount++;
  1918. var job = jobs[ i ];
  1919. var translatedText = translatedTexts[ i ];
  1920. if( !string.IsNullOrEmpty( translatedText ) )
  1921. {
  1922. if( Settings.ForceSplitTextAfterCharacters > 0 )
  1923. {
  1924. translatedText = translatedText.SplitToLines( Settings.ForceSplitTextAfterCharacters, '\n', ' ', ' ' );
  1925. }
  1926. job.TranslatedText = job.Key.RepairTemplate( translatedText );
  1927. QueueNewTranslationForDisk( job.Key, translatedText );
  1928. _completedJobs.Add( job );
  1929. }
  1930. AddTranslation( job.Key, job.TranslatedText );
  1931. job.State = TranslationJobState.Succeeded;
  1932. _ongoingJobs.Remove( job.Key.GetDictionaryLookupKey() );
  1933. XuaLogger.Current.Debug( $"Completed: '{job.Key.GetDictionaryLookupKey()}' => '{translatedText}'" );
  1934. }
  1935. }
  1936. else
  1937. {
  1938. if( !_batchLogicHasFailed )
  1939. {
  1940. StartCoroutine( EnableBatchingAfterDelay() );
  1941. }
  1942. _batchLogicHasFailed = true;
  1943. for( int i = 0 ; i < jobs.Length ; i++ )
  1944. {
  1945. Settings.TranslationCount++;
  1946. var job = jobs[ i ];
  1947. var key = job.Key.GetDictionaryLookupKey();
  1948. if( !_unstartedJobs.ContainsKey( key ) )
  1949. {
  1950. _unstartedJobs[ key ] = job;
  1951. }
  1952. _ongoingJobs.Remove( key );
  1953. }
  1954. XuaLogger.Current.Error( "A batch operation failed. Disabling batching and restarting failed jobs." );
  1955. }
  1956. if( !Settings.IsShutdown )
  1957. {
  1958. if( Settings.TranslationCount > Settings.MaxTranslationsBeforeShutdown )
  1959. {
  1960. Settings.IsShutdown = true;
  1961. Settings.IsShutdownFatal = true;
  1962. XuaLogger.Current.Error( $"Maximum translations ({Settings.MaxTranslationsBeforeShutdown}) per session reached. Shutting plugin down." );
  1963. _unstartedJobs.Clear();
  1964. _completedJobs.Clear();
  1965. _ongoingJobs.Clear();
  1966. }
  1967. }
  1968. }
  1969. private void OnSingleTranslationCompleted( TranslationJob job, string[] translatedTextArray )
  1970. {
  1971. var translatedText = translatedTextArray[ 0 ];
  1972. Settings.TranslationCount++;
  1973. XuaLogger.Current.Debug( $"Completed: '{job.Key.GetDictionaryLookupKey()}' => '{translatedText}'" );
  1974. _consecutiveErrors = 0;
  1975. if( !string.IsNullOrEmpty( translatedText ) )
  1976. {
  1977. if( Settings.ForceSplitTextAfterCharacters > 0 )
  1978. {
  1979. translatedText = translatedText.SplitToLines( Settings.ForceSplitTextAfterCharacters, '\n', ' ', ' ' );
  1980. }
  1981. job.TranslatedText = job.Key.RepairTemplate( translatedText );
  1982. QueueNewTranslationForDisk( job.Key, translatedText );
  1983. _completedJobs.Add( job );
  1984. }
  1985. AddTranslation( job.Key, job.TranslatedText );
  1986. job.State = TranslationJobState.Succeeded;
  1987. _ongoingJobs.Remove( job.Key.GetDictionaryLookupKey() );
  1988. if( !Settings.IsShutdown )
  1989. {
  1990. if( Settings.TranslationCount > Settings.MaxTranslationsBeforeShutdown )
  1991. {
  1992. Settings.IsShutdown = true;
  1993. Settings.IsShutdownFatal = true;
  1994. XuaLogger.Current.Error( $"Maximum translations ({Settings.MaxTranslationsBeforeShutdown}) per session reached. Shutting plugin down." );
  1995. _unstartedJobs.Clear();
  1996. _completedJobs.Clear();
  1997. _ongoingJobs.Clear();
  1998. }
  1999. }
  2000. }
  2001. private void OnTranslationFailed( TranslationJob[] jobs, string error, Exception e )
  2002. {
  2003. if( e == null )
  2004. {
  2005. XuaLogger.Current.Error( error );
  2006. }
  2007. else
  2008. {
  2009. XuaLogger.Current.Error( e, error );
  2010. }
  2011. _consecutiveErrors++;
  2012. if( jobs.Length == 1 )
  2013. {
  2014. Settings.TranslationCount++; // counts as a translation
  2015. foreach( var job in jobs )
  2016. {
  2017. job.State = TranslationJobState.Failed;
  2018. _ongoingJobs.Remove( job.Key.GetDictionaryLookupKey() );
  2019. }
  2020. }
  2021. else
  2022. {
  2023. if( !_batchLogicHasFailed )
  2024. {
  2025. StartCoroutine( EnableBatchingAfterDelay() );
  2026. }
  2027. _batchLogicHasFailed = true;
  2028. for( int i = 0 ; i < jobs.Length ; i++ )
  2029. {
  2030. Settings.TranslationCount++;
  2031. var job = jobs[ i ];
  2032. var key = job.Key.GetDictionaryLookupKey();
  2033. if( !_unstartedJobs.ContainsKey( key ) )
  2034. {
  2035. _unstartedJobs[ key ] = job;
  2036. }
  2037. _ongoingJobs.Remove( key );
  2038. }
  2039. XuaLogger.Current.Error( "A batch operation failed. Disabling batching and restarting failed jobs." );
  2040. }
  2041. if( !Settings.IsShutdown )
  2042. {
  2043. if( _consecutiveErrors >= Settings.MaxErrors )
  2044. {
  2045. Settings.IsShutdown = true;
  2046. XuaLogger.Current.Error( $"{Settings.MaxErrors} or more consecutive errors occurred. Shutting down plugin." );
  2047. _unstartedJobs.Clear();
  2048. _completedJobs.Clear();
  2049. _ongoingJobs.Clear();
  2050. }
  2051. }
  2052. }
  2053. private void FinishTranslations()
  2054. {
  2055. if( _completedJobs.Count > 0 )
  2056. {
  2057. for( int i = _completedJobs.Count - 1 ; i >= 0 ; i-- )
  2058. {
  2059. var job = _completedJobs[ i ];
  2060. _completedJobs.RemoveAt( i );
  2061. foreach( var component in job.Components )
  2062. {
  2063. // update the original text, but only if it has not been chaanged already for some reason (could be other translator plugin or game itself)
  2064. try
  2065. {
  2066. var text = component.GetText().TrimIfConfigured();
  2067. if( text == job.Key.OriginalText )
  2068. {
  2069. var info = component.GetOrCreateTextTranslationInfo();
  2070. SetTranslatedText( component, job.TranslatedText, info );
  2071. }
  2072. }
  2073. catch( NullReferenceException )
  2074. {
  2075. // might fail if compoent is no longer associated to game
  2076. }
  2077. }
  2078. // handle each context
  2079. foreach( var context in job.Contexts )
  2080. {
  2081. // are all jobs within this context completed? If so, we can set the text
  2082. if( context.Jobs.All( x => x.State == TranslationJobState.Succeeded ) )
  2083. {
  2084. try
  2085. {
  2086. var text = context.Component.GetText().TrimIfConfigured();
  2087. var result = context.Result;
  2088. Dictionary<string, string> translations = new Dictionary<string, string>();
  2089. var translatedText = TranslateOrQueueWebJobImmediateByParserResult( context.Component, result, false );
  2090. if( !string.IsNullOrEmpty( translatedText ) )
  2091. {
  2092. if( result.PersistCombinedResult && !_translations.ContainsKey( context.Result.OriginalText ) )
  2093. {
  2094. AddTranslation( context.Result.OriginalText, translatedText );
  2095. QueueNewTranslationForDisk( context.Result.OriginalText, translatedText );
  2096. }
  2097. if( text == result.OriginalText )
  2098. {
  2099. if( translatedText != null )
  2100. {
  2101. var info = context.Component.GetOrCreateTextTranslationInfo();
  2102. SetTranslatedText( context.Component, translatedText, info );
  2103. }
  2104. }
  2105. }
  2106. }
  2107. catch( NullReferenceException )
  2108. {
  2109. }
  2110. }
  2111. }
  2112. // Utage support
  2113. if( ClrTypes.AdvEngine != null
  2114. && job.OriginalSources.Any( x => ClrTypes.AdvCommand.IsAssignableFrom( x.GetType() ) ) )
  2115. {
  2116. _nextAdvUpdate = Time.time + 0.5f;
  2117. }
  2118. }
  2119. }
  2120. }
  2121. private void UpdateUtageText()
  2122. {
  2123. // After an object is destroyed, an equality check with null will return true. The variable does not go to null, you can still call GetInstanceID() on it, but the "==" operator is overloaded and behaves as expected.
  2124. if( _advEngine == null || _advEngine?.gameObject == null )
  2125. {
  2126. _advEngine = (Component)GameObject.FindObjectOfType( Constants.ClrTypes.AdvEngine );
  2127. }
  2128. if( _advEngine != null )
  2129. {
  2130. AccessTools.Method( Constants.ClrTypes.AdvEngine, "ChangeLanguage" )?.Invoke( _advEngine, new object[ 0 ] );
  2131. }
  2132. }
  2133. private void ReloadTranslations()
  2134. {
  2135. LoadTranslations();
  2136. var context = new TextureReloadContext();
  2137. foreach( var kvp in ObjectReferenceMapper.GetAllRegisteredObjects() )
  2138. {
  2139. var ui = kvp.Key;
  2140. try
  2141. {
  2142. if( ui is Component component )
  2143. {
  2144. if( component.gameObject?.activeSelf ?? false )
  2145. {
  2146. var tti = kvp.Value as TextTranslationInfo;
  2147. if( tti != null && !string.IsNullOrEmpty( tti.OriginalText ) )
  2148. {
  2149. var key = new TranslationKey( kvp.Key, tti.OriginalText, false );
  2150. if( TryGetTranslation( key, out string translatedText ) && !string.IsNullOrEmpty( translatedText ) )
  2151. {
  2152. SetTranslatedText( kvp.Key, translatedText, tti ); // no need to untemplatize the translated text
  2153. }
  2154. }
  2155. }
  2156. }
  2157. if( Settings.EnableTextureTranslation )
  2158. {
  2159. TranslateTexture( ui, context );
  2160. }
  2161. }
  2162. catch( Exception )
  2163. {
  2164. // not super pretty, no...
  2165. ObjectReferenceMapper.Remove( ui );
  2166. }
  2167. }
  2168. }
  2169. private string CalculateDumpFileName()
  2170. {
  2171. int idx = 0;
  2172. string fileName = null;
  2173. do
  2174. {
  2175. idx++;
  2176. fileName = $"UntranslatedDump{idx}.txt";
  2177. }
  2178. while( File.Exists( fileName ) );
  2179. return fileName;
  2180. }
  2181. private void DumpUntranslated()
  2182. {
  2183. if( _newUntranslated.Count > 0 )
  2184. {
  2185. using( var stream = File.Open( CalculateDumpFileName(), FileMode.Append, FileAccess.Write ) )
  2186. using( var writer = new StreamWriter( stream, Encoding.UTF8 ) )
  2187. {
  2188. foreach( var untranslated in _newUntranslated )
  2189. {
  2190. writer.WriteLine( TextHelper.Encode( untranslated ) + '=' );
  2191. }
  2192. writer.Flush();
  2193. }
  2194. _newUntranslated.Clear();
  2195. }
  2196. }
  2197. private void ToggleFont()
  2198. {
  2199. if( _hasOverrideFont )
  2200. {
  2201. _overrideFont = !_overrideFont;
  2202. var objects = ObjectReferenceMapper.GetAllRegisteredObjects();
  2203. XuaLogger.Current.Info( $"Toggling fonts of {objects.Count} objects." );
  2204. if( _overrideFont )
  2205. {
  2206. // make sure we use the translated version of all texts
  2207. foreach( var kvp in objects )
  2208. {
  2209. var tti = kvp.Value as TextTranslationInfo;
  2210. if( tti != null )
  2211. {
  2212. var ui = kvp.Key;
  2213. try
  2214. {
  2215. if( ( ui as Component )?.gameObject?.activeSelf ?? false )
  2216. {
  2217. tti?.ChangeFont( ui );
  2218. }
  2219. }
  2220. catch( Exception )
  2221. {
  2222. // not super pretty, no...
  2223. ObjectReferenceMapper.Remove( ui );
  2224. }
  2225. }
  2226. }
  2227. }
  2228. else
  2229. {
  2230. // make sure we use the original version of all texts
  2231. foreach( var kvp in objects )
  2232. {
  2233. var tti = kvp.Value as TextTranslationInfo;
  2234. var ui = kvp.Key;
  2235. try
  2236. {
  2237. if( ( ui as Component )?.gameObject?.activeSelf ?? false )
  2238. {
  2239. tti?.UnchangeFont( ui );
  2240. }
  2241. }
  2242. catch( Exception )
  2243. {
  2244. // not super pretty, no...
  2245. ObjectReferenceMapper.Remove( ui );
  2246. }
  2247. }
  2248. }
  2249. }
  2250. }
  2251. private void ToggleTranslation()
  2252. {
  2253. _isInTranslatedMode = !_isInTranslatedMode;
  2254. var objects = ObjectReferenceMapper.GetAllRegisteredObjects();
  2255. XuaLogger.Current.Info( $"Toggling translations of {objects.Count} objects." );
  2256. if( _isInTranslatedMode )
  2257. {
  2258. // make sure we use the translated version of all texts
  2259. foreach( var kvp in objects )
  2260. {
  2261. var ui = kvp.Key;
  2262. try
  2263. {
  2264. if( ui is Component component )
  2265. {
  2266. if( component.gameObject?.activeSelf ?? false )
  2267. {
  2268. var tti = kvp.Value as TextTranslationInfo;
  2269. if( tti != null && tti.IsTranslated )
  2270. {
  2271. SetText( ui, tti.TranslatedText, true, tti );
  2272. }
  2273. }
  2274. }
  2275. if( Settings.EnableTextureTranslation && Settings.EnableTextureToggling )
  2276. {
  2277. TranslateTexture( ui, null );
  2278. }
  2279. }
  2280. catch( Exception )
  2281. {
  2282. // not super pretty, no...
  2283. ObjectReferenceMapper.Remove( ui );
  2284. }
  2285. }
  2286. }
  2287. else
  2288. {
  2289. // make sure we use the original version of all texts
  2290. foreach( var kvp in objects )
  2291. {
  2292. var ui = kvp.Key;
  2293. try
  2294. {
  2295. if( ui is Component component )
  2296. {
  2297. if( component.gameObject?.activeSelf ?? false )
  2298. {
  2299. var tti = kvp.Value as TextTranslationInfo;
  2300. if( tti != null && tti.IsTranslated )
  2301. {
  2302. SetText( ui, tti.OriginalText, true, tti );
  2303. }
  2304. }
  2305. }
  2306. if( Settings.EnableTextureTranslation && Settings.EnableTextureToggling )
  2307. {
  2308. TranslateTexture( ui, null );
  2309. }
  2310. }
  2311. catch( Exception )
  2312. {
  2313. // not super pretty, no...
  2314. ObjectReferenceMapper.Remove( ui );
  2315. }
  2316. }
  2317. }
  2318. }
  2319. private void CopyToClipboard()
  2320. {
  2321. if( Settings.CopyToClipboard
  2322. && _textsToCopyToClipboardOrdered.Count > 0
  2323. && Time.realtimeSinceStartup - _clipboardUpdated > Settings.ClipboardDebounceTime )
  2324. {
  2325. try
  2326. {
  2327. var builder = new StringBuilder();
  2328. foreach( var text in _textsToCopyToClipboardOrdered )
  2329. {
  2330. if( text.Length + builder.Length > Settings.MaxClipboardCopyCharacters ) break;
  2331. builder.AppendLine( text );
  2332. }
  2333. TextEditor editor = (TextEditor)GUIUtility.GetStateObject( typeof( TextEditor ), GUIUtility.keyboardControl );
  2334. editor.text = builder.ToString();
  2335. editor.SelectAll();
  2336. editor.Copy();
  2337. }
  2338. catch( Exception e )
  2339. {
  2340. XuaLogger.Current.Error( e, "An error while copying text to clipboard." );
  2341. }
  2342. finally
  2343. {
  2344. _textsToCopyToClipboard.Clear();
  2345. _textsToCopyToClipboardOrdered.Clear();
  2346. }
  2347. }
  2348. }
  2349. private void PrintObjects()
  2350. {
  2351. using( var stream = File.Open( Path.Combine( Environment.CurrentDirectory, "hierarchy.txt" ), FileMode.Create ) )
  2352. using( var writer = new StreamWriter( stream ) )
  2353. {
  2354. foreach( var root in GetAllRoots() )
  2355. {
  2356. TraverseChildren( writer, root, "" );
  2357. }
  2358. writer.Flush();
  2359. }
  2360. }
  2361. private void ManualHook()
  2362. {
  2363. ManualHookForComponents();
  2364. ManualHookForTextures();
  2365. }
  2366. private void ManualHookForComponents()
  2367. {
  2368. foreach( var root in GetAllRoots() )
  2369. {
  2370. TraverseChildrenManualHook( root );
  2371. }
  2372. }
  2373. private void ManualHookForTextures()
  2374. {
  2375. if( Settings.EnableTextureScanOnSceneLoad && ( Settings.EnableTextureTranslation || Settings.EnableTextureDumping ) )
  2376. {
  2377. // scan all textures and update
  2378. var textures = Resources.FindObjectsOfTypeAll<Texture2D>();
  2379. foreach( var texture in textures )
  2380. {
  2381. Hook_ImageChanged( texture, false );
  2382. }
  2383. //// scan all components and set dirty
  2384. //var components = GameObject.FindObjectsOfType<Component>();
  2385. //foreach( var component in components )
  2386. //{
  2387. // component.SetAllDirtyEx();
  2388. //}
  2389. }
  2390. }
  2391. private IEnumerable<GameObject> GetAllRoots()
  2392. {
  2393. var objects = GameObject.FindObjectsOfType<GameObject>();
  2394. foreach( var obj in objects )
  2395. {
  2396. if( obj.transform != null && obj.transform.parent == null )
  2397. {
  2398. yield return obj;
  2399. }
  2400. }
  2401. }
  2402. private void TraverseChildren( StreamWriter writer, GameObject obj, string identation )
  2403. {
  2404. if( obj != null )
  2405. {
  2406. var layer = LayerMask.LayerToName( obj.layer );
  2407. var components = string.Join( ", ", obj.GetComponents<Component>().Select( x => x?.GetType()?.Name ).Where( x => x != null ).ToArray() );
  2408. var line = string.Format( "{0,-50} {1,100}",
  2409. identation + obj.name + " [" + layer + "]",
  2410. components );
  2411. writer.WriteLine( line );
  2412. if( obj.transform != null )
  2413. {
  2414. for( int i = 0 ; i < obj.transform.childCount ; i++ )
  2415. {
  2416. var child = obj.transform.GetChild( i );
  2417. TraverseChildren( writer, child.gameObject, identation + " " );
  2418. }
  2419. }
  2420. }
  2421. }
  2422. private void TraverseChildrenManualHook( GameObject obj )
  2423. {
  2424. if( obj != null )
  2425. {
  2426. var components = obj.GetComponents<Component>();
  2427. foreach( var component in components )
  2428. {
  2429. if( component.IsKnownTextType() )
  2430. {
  2431. Hook_TextChanged( component, false );
  2432. }
  2433. if( Settings.EnableTextureTranslation || Settings.EnableTextureDumping )
  2434. {
  2435. if( component.IsKnownImageType() )
  2436. {
  2437. Hook_ImageChangedOnComponent( component, null, false, false );
  2438. }
  2439. }
  2440. }
  2441. if( obj.transform != null )
  2442. {
  2443. for( int i = 0 ; i < obj.transform.childCount ; i++ )
  2444. {
  2445. var child = obj.transform.GetChild( i );
  2446. TraverseChildrenManualHook( child.gameObject );
  2447. }
  2448. }
  2449. }
  2450. }
  2451. /// <summary>
  2452. /// Temporarily disables the Auto Translator functionality.
  2453. /// </summary>
  2454. public void DisableAutoTranslator()
  2455. {
  2456. _temporarilyDisabled = true;
  2457. }
  2458. /// <summary>
  2459. /// Re-enables the Auto Translator functionality after
  2460. /// having disabled it thorugh DisableAutoTranslator
  2461. /// </summary>
  2462. public void EnableAutoTranslator()
  2463. {
  2464. _temporarilyDisabled = false;
  2465. }
  2466. void OnApplicationQuit()
  2467. {
  2468. if( _configuredEndpoints == null ) return;
  2469. foreach( var ce in _configuredEndpoints )
  2470. {
  2471. try
  2472. {
  2473. if( ce.Endpoint is IDisposable disposable ) disposable.Dispose();
  2474. }
  2475. catch( Exception e )
  2476. {
  2477. XuaLogger.Current.Error( e, "An error occurred while disposing endpoint." );
  2478. }
  2479. }
  2480. }
  2481. }
  2482. internal static class SceneManagerLoader
  2483. {
  2484. public static void EnableSceneLoadScanInternal( AutoTranslationPlugin plugin )
  2485. {
  2486. // specified in own method, because of chance that this has changed through Unity lifetime
  2487. SceneManager.sceneLoaded += ( arg1, arg2 ) => plugin.OnLevelWasLoadedFromSceneManager( arg1.buildIndex );
  2488. }
  2489. }
  2490. }