AutoTranslationPlugin.cs 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  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.IMGUI;
  24. using XUnity.AutoTranslator.Plugin.Core.Hooks.NGUI;
  25. using UnityEngine.SceneManagement;
  26. using XUnity.AutoTranslator.Plugin.Core.Constants;
  27. using XUnity.AutoTranslator.Plugin.Core.Debugging;
  28. using XUnity.AutoTranslator.Plugin.Core.Batching;
  29. using Harmony;
  30. using XUnity.AutoTranslator.Plugin.Core.Parsing;
  31. namespace XUnity.AutoTranslator.Plugin.Core
  32. {
  33. public class AutoTranslationPlugin : MonoBehaviour
  34. {
  35. /// <summary>
  36. /// Allow the instance to be accessed statically, as only one will exist.
  37. /// </summary>
  38. public static AutoTranslationPlugin Current;
  39. /// <summary>
  40. /// These are the currently running translation jobs (being translated by an http request).
  41. /// </summary>
  42. private List<TranslationJob> _completedJobs = new List<TranslationJob>();
  43. private Dictionary<string, TranslationJob> _unstartedJobs = new Dictionary<string, TranslationJob>();
  44. private Dictionary<string, TranslationJob> _ongoingJobs = new Dictionary<string, TranslationJob>();
  45. /// <summary>
  46. /// All the translations are stored in this dictionary.
  47. /// </summary>
  48. private Dictionary<string, string> _staticTranslations = new Dictionary<string, string>();
  49. private Dictionary<string, string> _translations = new Dictionary<string, string>();
  50. private Dictionary<string, string> _reverseTranslations = new Dictionary<string, string>();
  51. /// <summary>
  52. /// These are the new translations that has not yet been persisted to the file system.
  53. /// </summary>
  54. private object _writeToFileSync = new object();
  55. private Dictionary<string, string> _newTranslations = new Dictionary<string, string>();
  56. private HashSet<string> _newUntranslated = new HashSet<string>();
  57. /// <summary>
  58. /// Keeps track of things to copy to clipboard.
  59. /// </summary>
  60. private List<string> _textsToCopyToClipboardOrdered = new List<string>();
  61. private HashSet<string> _textsToCopyToClipboard = new HashSet<string>();
  62. private float _clipboardUpdated = Time.realtimeSinceStartup;
  63. /// <summary>
  64. /// The number of http translation errors that has occurred up until now.
  65. /// </summary>
  66. private int _consecutiveErrors = 0;
  67. /// <summary>
  68. /// This is a hash set that contains all Text components that is currently being worked on by
  69. /// the translation plugin.
  70. /// </summary>
  71. private HashSet<object> _ongoingOperations = new HashSet<object>();
  72. /// <summary>
  73. /// This function will check if there are symbols of a given language contained in a string.
  74. /// </summary>
  75. private Func<string, bool> _symbolCheck;
  76. private object _advEngine;
  77. private float? _nextAdvUpdate;
  78. private IKnownEndpoint _endpoint;
  79. private int[] _currentTranslationsQueuedPerSecondRollingWindow = new int[ Settings.TranslationQueueWatchWindow ];
  80. private float? _timeExceededThreshold;
  81. private float _translationsQueuedPerSecond;
  82. private bool _isInTranslatedMode = true;
  83. private bool _hooksEnabled = true;
  84. private bool _batchLogicHasFailed = false;
  85. private int _availableBatchOperations = Settings.MaxAvailableBatchOperations;
  86. private float _batchOperationSecondCounter = 0;
  87. private string _previouslyQueuedText = null;
  88. private int _concurrentStaggers = 0;
  89. private int _frameForLastQueuedTranslation = -1;
  90. private int _consecutiveFramesQueued = 0;
  91. public void Initialize()
  92. {
  93. Current = this;
  94. Logger.Current = new ConsoleLogger();
  95. Settings.Configure();
  96. if( Settings.EnableConsole ) DebugConsole.Enable();
  97. HooksSetup.InstallHooks();
  98. try
  99. {
  100. _endpoint = KnownEndpoints.FindEndpoint( Settings.ServiceEndpoint );
  101. }
  102. catch( Exception e )
  103. {
  104. Logger.Current.Error( e, "An unexpected error occurred during initialization of endpoint." );
  105. }
  106. if( !TextHelper.IsFromLanguageSupported( Settings.FromLanguage ) )
  107. {
  108. Logger.Current.Error( $"The plugin has been configured to use the 'FromLanguage={Settings.FromLanguage}'. This language is not supported. Shutting plugin down." );
  109. _endpoint = null;
  110. Settings.IsShutdown = true;
  111. }
  112. _symbolCheck = TextHelper.GetSymbolCheck( Settings.FromLanguage );
  113. LoadTranslations();
  114. LoadStaticTranslations();
  115. // start a thread that will periodically removed unused references
  116. var t1 = new Thread( MaintenanceLoop );
  117. t1.IsBackground = true;
  118. t1.Start();
  119. // start a thread that will periodically save new translations
  120. var t2 = new Thread( SaveTranslationsLoop );
  121. t2.IsBackground = true;
  122. t2.Start();
  123. }
  124. private string[] GetTranslationFiles()
  125. {
  126. return Directory.GetFiles( Path.Combine( Config.Current.DataPath, Settings.TranslationDirectory ), $"*.txt", SearchOption.AllDirectories ) // FIXME: Add $"*{Language}.txt"
  127. .Union( new[] { Settings.AutoTranslationsFilePath } )
  128. .Select( x => x.Replace( "/", "\\" ) )
  129. .Distinct()
  130. .OrderBy( x => x )
  131. .ToArray();
  132. }
  133. private void MaintenanceLoop( object state )
  134. {
  135. while( true )
  136. {
  137. try
  138. {
  139. ObjectExtensions.Cull();
  140. }
  141. catch( Exception e )
  142. {
  143. Logger.Current.Error( e, "An unexpected error occurred while removing GC'ed resources." );
  144. }
  145. Thread.Sleep( 1000 * 60 );
  146. }
  147. }
  148. private void SaveTranslationsLoop( object state )
  149. {
  150. try
  151. {
  152. while( true )
  153. {
  154. if( _newTranslations.Count > 0 )
  155. {
  156. lock( _writeToFileSync )
  157. {
  158. if( _newTranslations.Count > 0 )
  159. {
  160. using( var stream = File.Open( Settings.AutoTranslationsFilePath, FileMode.Append, FileAccess.Write ) )
  161. using( var writer = new StreamWriter( stream, Encoding.UTF8 ) )
  162. {
  163. foreach( var kvp in _newTranslations )
  164. {
  165. writer.WriteLine( TextHelper.Encode( kvp.Key ) + '=' + TextHelper.Encode( kvp.Value ) );
  166. }
  167. writer.Flush();
  168. }
  169. _newTranslations.Clear();
  170. }
  171. }
  172. }
  173. else
  174. {
  175. Thread.Sleep( 5000 );
  176. }
  177. }
  178. }
  179. catch( Exception e )
  180. {
  181. Logger.Current.Error( e, "An error occurred while saving translations to disk." );
  182. }
  183. }
  184. /// <summary>
  185. /// Loads the translations found in Translation.{lang}.txt
  186. /// </summary>
  187. private void LoadTranslations()
  188. {
  189. try
  190. {
  191. lock( _writeToFileSync )
  192. {
  193. Directory.CreateDirectory( Path.Combine( Config.Current.DataPath, Settings.TranslationDirectory ) );
  194. Directory.CreateDirectory( Path.GetDirectoryName( Path.Combine( Config.Current.DataPath, Settings.OutputFile ) ) );
  195. var tab = new char[] { '\t' };
  196. var equals = new char[] { '=' };
  197. var splitters = new char[][] { tab, equals };
  198. foreach( var fullFileName in GetTranslationFiles() )
  199. {
  200. if( File.Exists( fullFileName ) )
  201. {
  202. string[] translations = File.ReadAllLines( fullFileName, Encoding.UTF8 );
  203. foreach( string translation in translations )
  204. {
  205. for( int i = 0 ; i < splitters.Length ; i++ )
  206. {
  207. var splitter = splitters[ i ];
  208. string[] kvp = translation.Split( splitter, StringSplitOptions.None );
  209. if( kvp.Length >= 2 )
  210. {
  211. string key = TextHelper.Decode( kvp[ 0 ].TrimIfConfigured() );
  212. string value = TextHelper.Decode( kvp[ 1 ].TrimIfConfigured() );
  213. if( !string.IsNullOrEmpty( key ) && !string.IsNullOrEmpty( value ) )
  214. {
  215. AddTranslation( key, value );
  216. break;
  217. }
  218. }
  219. }
  220. }
  221. }
  222. }
  223. }
  224. }
  225. catch( Exception e )
  226. {
  227. Logger.Current.Error( e, "An error occurred while loading translations." );
  228. }
  229. }
  230. private void LoadStaticTranslations()
  231. {
  232. if( Settings.UseStaticTranslations && Settings.FromLanguage == Settings.DefaultFromLanguage && Settings.Language == Settings.DefaultLanguage )
  233. {
  234. var tab = new char[] { '\t' };
  235. var equals = new char[] { '=' };
  236. var splitters = new char[][] { tab, equals };
  237. // load static translations from previous titles
  238. string[] translations = Properties.Resources.StaticTranslations.Split( new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries );
  239. foreach( string translation in translations )
  240. {
  241. for( int i = 0 ; i < splitters.Length ; i++ )
  242. {
  243. var splitter = splitters[ i ];
  244. string[] kvp = translation.Split( splitter, StringSplitOptions.None );
  245. if( kvp.Length >= 2 )
  246. {
  247. string key = TextHelper.Decode( kvp[ 0 ].TrimIfConfigured() );
  248. string value = TextHelper.Decode( kvp[ 1 ].TrimIfConfigured() );
  249. if( !string.IsNullOrEmpty( key ) && !string.IsNullOrEmpty( value ) )
  250. {
  251. _staticTranslations[ key ] = value;
  252. break;
  253. }
  254. }
  255. }
  256. }
  257. }
  258. }
  259. private TranslationJob GetOrCreateTranslationJobFor( object ui, TranslationKey key, TranslationContext context )
  260. {
  261. var lookupKey = key.GetDictionaryLookupKey();
  262. if( _unstartedJobs.TryGetValue( lookupKey, out TranslationJob unstartedJob ) )
  263. {
  264. unstartedJob.Associate( context );
  265. return unstartedJob;
  266. }
  267. if( _ongoingJobs.TryGetValue( lookupKey, out TranslationJob ongoingJob ) )
  268. {
  269. ongoingJob.Associate( context );
  270. return ongoingJob;
  271. }
  272. foreach( var completedJob in _completedJobs )
  273. {
  274. if( completedJob.Key.GetDictionaryLookupKey() == lookupKey )
  275. {
  276. completedJob.Associate( context );
  277. return completedJob;
  278. }
  279. }
  280. Logger.Current.Debug( "Queued translation for: " + lookupKey );
  281. ongoingJob = new TranslationJob( key );
  282. if( ui != null )
  283. {
  284. ongoingJob.OriginalSources.Add( ui );
  285. }
  286. ongoingJob.Associate( context );
  287. _unstartedJobs.Add( lookupKey, ongoingJob );
  288. CheckStaggerText( lookupKey );
  289. CheckConsecutiveFrames();
  290. CheckThresholds();
  291. return ongoingJob;
  292. }
  293. public void CheckConsecutiveFrames()
  294. {
  295. var currentFrame = Time.frameCount;
  296. var lastFrame = currentFrame - 1;
  297. if( lastFrame == _frameForLastQueuedTranslation )
  298. {
  299. // we also queued something last frame, lets increment our counter
  300. _consecutiveFramesQueued++;
  301. if( _consecutiveFramesQueued > Settings.MaximumConcurrentFrameTranslations )
  302. {
  303. // Shutdown, this wont be tolerated!!!
  304. _unstartedJobs.Clear();
  305. _completedJobs.Clear();
  306. _ongoingJobs.Clear();
  307. Settings.IsShutdown = true;
  308. Logger.Current.Error( $"SPAM DETECTED: Translations were queued every frame for more than {Settings.MaximumConcurrentFrameTranslations} consecutive frames. Shutting down plugin." );
  309. }
  310. }
  311. else if( currentFrame == _frameForLastQueuedTranslation )
  312. {
  313. // do nothing, there may be multiple translations per frame, that wont increase this counter
  314. }
  315. else
  316. {
  317. // but if multiple Update frames has passed, we will reset the counter
  318. _consecutiveFramesQueued = 0;
  319. }
  320. _frameForLastQueuedTranslation = currentFrame;
  321. }
  322. private void CheckStaggerText( string untranslatedText )
  323. {
  324. if( _previouslyQueuedText != null )
  325. {
  326. if( untranslatedText.StartsWith( _previouslyQueuedText ) )
  327. {
  328. _concurrentStaggers++;
  329. if( _concurrentStaggers > Settings.MaximumStaggers )
  330. {
  331. _unstartedJobs.Clear();
  332. _completedJobs.Clear();
  333. _ongoingJobs.Clear();
  334. Settings.IsShutdown = true;
  335. Logger.Current.Error( $"SPAM DETECTED: Text that is 'scrolling in' is being translated. Disable that feature. Shutting down plugin." );
  336. }
  337. }
  338. else
  339. {
  340. _concurrentStaggers = 0;
  341. }
  342. }
  343. _previouslyQueuedText = untranslatedText;
  344. }
  345. private void CheckThresholds()
  346. {
  347. if( _unstartedJobs.Count > Settings.MaxUnstartedJobs )
  348. {
  349. _unstartedJobs.Clear();
  350. _completedJobs.Clear();
  351. _ongoingJobs.Clear();
  352. Settings.IsShutdown = true;
  353. Logger.Current.Error( $"SPAM DETECTED: More than {Settings.MaxUnstartedJobs} queued for translations due to unknown reasons. Shutting down plugin." );
  354. }
  355. var previousIdx = ( (int)( Time.time - Time.deltaTime ) ) % Settings.TranslationQueueWatchWindow;
  356. var newIdx = ( (int)Time.time ) % Settings.TranslationQueueWatchWindow;
  357. if( previousIdx != newIdx )
  358. {
  359. _currentTranslationsQueuedPerSecondRollingWindow[ newIdx ] = 0;
  360. }
  361. _currentTranslationsQueuedPerSecondRollingWindow[ newIdx ]++;
  362. var translationsInWindow = _currentTranslationsQueuedPerSecondRollingWindow.Sum();
  363. _translationsQueuedPerSecond = (float)translationsInWindow / Settings.TranslationQueueWatchWindow;
  364. if( _translationsQueuedPerSecond > Settings.MaxTranslationsQueuedPerSecond )
  365. {
  366. if( !_timeExceededThreshold.HasValue )
  367. {
  368. _timeExceededThreshold = Time.time;
  369. }
  370. if( Time.time - _timeExceededThreshold.Value > Settings.MaxSecondsAboveTranslationThreshold )
  371. {
  372. _unstartedJobs.Clear();
  373. _completedJobs.Clear();
  374. _ongoingJobs.Clear();
  375. Settings.IsShutdown = true;
  376. Logger.Current.Error( $"SPAM DETECTED: More than {Settings.MaxTranslationsQueuedPerSecond} translations per seconds queued for a {Settings.MaxSecondsAboveTranslationThreshold} second period. Shutting down plugin." );
  377. }
  378. }
  379. else
  380. {
  381. _timeExceededThreshold = null;
  382. }
  383. }
  384. private void IncrementBatchOperations()
  385. {
  386. _batchOperationSecondCounter += Time.deltaTime;
  387. if( _batchOperationSecondCounter > Settings.IncreaseBatchOperationsEvery )
  388. {
  389. if( _availableBatchOperations < Settings.MaxAvailableBatchOperations )
  390. {
  391. _availableBatchOperations++;
  392. }
  393. _batchOperationSecondCounter = 0;
  394. }
  395. }
  396. private void ResetThresholdTimerIfRequired()
  397. {
  398. var previousIdx = ( (int)( Time.time - Time.deltaTime ) ) % Settings.TranslationQueueWatchWindow;
  399. var newIdx = ( (int)Time.time ) % Settings.TranslationQueueWatchWindow;
  400. if( previousIdx != newIdx )
  401. {
  402. _currentTranslationsQueuedPerSecondRollingWindow[ newIdx ] = 0;
  403. }
  404. var translationsInWindow = _currentTranslationsQueuedPerSecondRollingWindow.Sum();
  405. _translationsQueuedPerSecond = (float)translationsInWindow / Settings.TranslationQueueWatchWindow;
  406. if( _translationsQueuedPerSecond <= Settings.MaxTranslationsQueuedPerSecond )
  407. {
  408. _timeExceededThreshold = null;
  409. }
  410. }
  411. private void AddTranslation( string key, string value )
  412. {
  413. _translations[ key ] = value;
  414. _reverseTranslations[ value ] = key;
  415. }
  416. private void AddTranslation( TranslationKey key, string value )
  417. {
  418. _translations[ key.GetDictionaryLookupKey() ] = value;
  419. _reverseTranslations[ value ] = key.GetDictionaryLookupKey();
  420. }
  421. private void QueueNewUntranslatedForClipboard( TranslationKey key )
  422. {
  423. if( Settings.CopyToClipboard )
  424. {
  425. if( !_textsToCopyToClipboard.Contains( key.RelevantText ) )
  426. {
  427. _textsToCopyToClipboard.Add( key.RelevantText );
  428. _textsToCopyToClipboardOrdered.Add( key.RelevantText );
  429. _clipboardUpdated = Time.realtimeSinceStartup;
  430. }
  431. }
  432. }
  433. private void QueueNewUntranslatedForDisk( TranslationKey key )
  434. {
  435. _newUntranslated.Add( key.GetDictionaryLookupKey() );
  436. }
  437. private void QueueNewTranslationForDisk( TranslationKey key, string value )
  438. {
  439. lock( _writeToFileSync )
  440. {
  441. _newTranslations[ key.GetDictionaryLookupKey() ] = value;
  442. }
  443. }
  444. private void QueueNewTranslationForDisk( string key, string value )
  445. {
  446. lock( _writeToFileSync )
  447. {
  448. _newTranslations[ key ] = value;
  449. }
  450. }
  451. private bool TryGetTranslation( TranslationKey key, out string value )
  452. {
  453. var lookup = key.GetDictionaryLookupKey();
  454. var result = _translations.TryGetValue( lookup, out value );
  455. if( result )
  456. {
  457. return result;
  458. }
  459. else if( _staticTranslations.Count > 0 )
  460. {
  461. if( _staticTranslations.TryGetValue( lookup, out value ) )
  462. {
  463. QueueNewTranslationForDisk( lookup, value );
  464. AddTranslation( lookup, value );
  465. return true;
  466. }
  467. }
  468. return result;
  469. }
  470. public bool TryGetReverseTranslation( string value, out string key )
  471. {
  472. return _reverseTranslations.TryGetValue( value, out key );
  473. }
  474. public string Hook_TextChanged_WithResult( object ui, string text )
  475. {
  476. if( !ui.IsKnownType() ) return null;
  477. if( _hooksEnabled )
  478. {
  479. return TranslateOrQueueWebJob( ui, text, true );
  480. }
  481. return null;
  482. }
  483. public void Hook_TextChanged( object ui )
  484. {
  485. if( _hooksEnabled )
  486. {
  487. TranslateOrQueueWebJob( ui, null, false );
  488. }
  489. }
  490. public void Hook_TextInitialized( object ui )
  491. {
  492. if( _hooksEnabled )
  493. {
  494. TranslateOrQueueWebJob( ui, null, true );
  495. }
  496. }
  497. private void SetTranslatedText( object ui, string translatedText, TranslationInfo info )
  498. {
  499. info?.SetTranslatedText( translatedText );
  500. if( _isInTranslatedMode )
  501. {
  502. SetText( ui, translatedText, true, info );
  503. }
  504. }
  505. /// <summary>
  506. /// Sets the text of a UI text, while ensuring this will not fire a text changed event.
  507. /// </summary>
  508. private void SetText( object ui, string text, bool isTranslated, TranslationInfo info )
  509. {
  510. if( !info?.IsCurrentlySettingText ?? true )
  511. {
  512. try
  513. {
  514. // TODO: Disable ANY Hook
  515. _hooksEnabled = false;
  516. if( info != null )
  517. {
  518. info.IsCurrentlySettingText = true;
  519. }
  520. ui.SetText( text );
  521. if( Settings.EnableUIResizing )
  522. {
  523. if( isTranslated )
  524. {
  525. info?.ResizeUI( ui );
  526. }
  527. else
  528. {
  529. info?.UnresizeUI( ui );
  530. }
  531. }
  532. }
  533. catch( NullReferenceException )
  534. {
  535. // This is likely happened due to a scene change.
  536. }
  537. catch( Exception e )
  538. {
  539. Logger.Current.Error( e, "An error occurred while setting text on a component." );
  540. }
  541. finally
  542. {
  543. _hooksEnabled = true;
  544. if( info != null )
  545. {
  546. info.IsCurrentlySettingText = false;
  547. }
  548. }
  549. }
  550. }
  551. /// <summary>
  552. /// Determines if a text should be translated.
  553. /// </summary>
  554. private bool IsTranslatable( string str )
  555. {
  556. return _symbolCheck( str ) && str.Length <= Settings.MaxCharactersPerTranslation && !_reverseTranslations.ContainsKey( str );
  557. }
  558. public bool ShouldTranslate( object ui )
  559. {
  560. var cui = ui as Component;
  561. if( cui != null )
  562. {
  563. var go = cui.gameObject;
  564. var isDummy = go.IsDummy();
  565. if( isDummy )
  566. {
  567. return false;
  568. }
  569. var inputField = cui.gameObject.GetFirstComponentInSelfOrAncestor( Constants.Types.InputField )
  570. ?? cui.gameObject.GetFirstComponentInSelfOrAncestor( Constants.Types.TMP_InputField );
  571. return inputField == null;
  572. }
  573. return true;
  574. }
  575. private string TranslateOrQueueWebJob( object ui, string text, bool isAwakening )
  576. {
  577. var info = ui.GetTranslationInfo( isAwakening );
  578. if( !info?.IsAwake ?? false )
  579. {
  580. return null;
  581. }
  582. if( _ongoingOperations.Contains( ui ) )
  583. {
  584. return TranslateImmediate( ui, text, info );
  585. }
  586. var supportsStabilization = ui.SupportsStabilization();
  587. if( Settings.Delay == 0 || !supportsStabilization )
  588. {
  589. return TranslateOrQueueWebJobImmediate( ui, text, info, supportsStabilization );
  590. }
  591. else
  592. {
  593. StartCoroutine(
  594. DelayForSeconds( Settings.Delay, () =>
  595. {
  596. TranslateOrQueueWebJobImmediate( ui, text, info, supportsStabilization );
  597. } ) );
  598. }
  599. return null;
  600. }
  601. public static bool IsCurrentlySetting( TranslationInfo info )
  602. {
  603. if( info == null ) return false;
  604. return info.IsCurrentlySettingText;
  605. }
  606. private string TranslateImmediate( object ui, string text, TranslationInfo info )
  607. {
  608. // Get the trimmed text
  609. text = ( text ?? ui.GetText() ).TrimIfConfigured();
  610. if( !string.IsNullOrEmpty( text ) && IsTranslatable( text ) && ShouldTranslate( ui ) && !IsCurrentlySetting( info ) )
  611. {
  612. info?.Reset( text );
  613. var textKey = new TranslationKey( text, ui.IsSpammingComponent(), false );
  614. // if we already have translation loaded in our _translatios dictionary, simply load it and set text
  615. string translation;
  616. if( TryGetTranslation( textKey, out translation ) )
  617. {
  618. if( !string.IsNullOrEmpty( translation ) )
  619. {
  620. SetTranslatedText( ui, textKey.Untemplate( translation ), info );
  621. return translation;
  622. }
  623. }
  624. }
  625. return null;
  626. }
  627. /// <summary>
  628. /// Translates the string of a UI text or queues it up to be translated
  629. /// by the HTTP translation service.
  630. /// </summary>
  631. private string TranslateOrQueueWebJobImmediate( object ui, string text, TranslationInfo info, bool supportsStabilization, TranslationContext context = null )
  632. {
  633. // Get the trimmed text
  634. text = ( text ?? ui.GetText() ).TrimIfConfigured();
  635. // Ensure that we actually want to translate this text and its owning UI element.
  636. if( !string.IsNullOrEmpty( text ) && IsTranslatable( text ) && ShouldTranslate( ui ) && !IsCurrentlySetting( info ) )
  637. {
  638. info?.Reset( text );
  639. var textKey = new TranslationKey( text, ui.IsSpammingComponent(), context != null );
  640. // if we already have translation loaded in our _translatios dictionary, simply load it and set text
  641. string translation;
  642. if( TryGetTranslation( textKey, out translation ) )
  643. {
  644. QueueNewUntranslatedForClipboard( textKey );
  645. if( !string.IsNullOrEmpty( translation ) )
  646. {
  647. SetTranslatedText( ui, textKey.Untemplate( translation ), info );
  648. return translation;
  649. }
  650. }
  651. else
  652. {
  653. if( context == null && ui.SupportsRichText() )
  654. {
  655. var parser = UnityTextParsers.GetTextParserByGameEngine();
  656. if( parser != null )
  657. {
  658. var result = parser.Parse( text );
  659. if( result.HasRichSyntax )
  660. {
  661. translation = TranslateOrQueueWebJobImmediateByParserResult( ui, result, true );
  662. if( translation != null )
  663. {
  664. SetTranslatedText( ui, translation, info ); // get rid of textKey here!!
  665. }
  666. return translation;
  667. }
  668. }
  669. }
  670. if( supportsStabilization && context == null ) // never stabilize a text that is contextualized or that does not support stabilization
  671. {
  672. // if we dont know what text to translate it to, we need to figure it out.
  673. // this might take a while, so add the UI text component to the ongoing operations
  674. // list, so we dont start multiple operations for it, as its text might be constantly
  675. // changing.
  676. _ongoingOperations.Add( ui );
  677. // start a coroutine, that will execute once the string of the UI text has stopped
  678. // changing. For all texts except 'story' texts, this will add a delay for exactly
  679. // 0.5s to the translation. This is barely noticable.
  680. //
  681. // on the other hand, for 'story' texts, this will take the time that it takes
  682. // for the text to stop 'scrolling' in.
  683. try
  684. {
  685. StartCoroutine(
  686. WaitForTextStablization(
  687. ui: ui,
  688. delay: 1.0f, // 1 second to prevent '1 second tickers' from getting translated
  689. maxTries: 60, // 50 tries, about 1 minute
  690. currentTries: 0,
  691. onMaxTriesExceeded: () =>
  692. {
  693. _ongoingOperations.Remove( ui );
  694. },
  695. onTextStabilized: stabilizedText =>
  696. {
  697. _ongoingOperations.Remove( ui );
  698. if( !string.IsNullOrEmpty( stabilizedText ) && IsTranslatable( stabilizedText ) )
  699. {
  700. var stabilizedTextKey = new TranslationKey( stabilizedText, false );
  701. QueueNewUntranslatedForClipboard( stabilizedTextKey );
  702. info?.Reset( stabilizedText );
  703. // once the text has stabilized, attempt to look it up
  704. if( TryGetTranslation( stabilizedTextKey, out translation ) )
  705. {
  706. if( !string.IsNullOrEmpty( translation ) )
  707. {
  708. // stabilized, no need to untemplate
  709. SetTranslatedText( ui, translation, info );
  710. }
  711. }
  712. else
  713. {
  714. if( context == null && ui.SupportsRichText() )
  715. {
  716. var parser = UnityTextParsers.GetTextParserByGameEngine();
  717. if( parser != null )
  718. {
  719. var result = parser.Parse( stabilizedText );
  720. if( result.HasRichSyntax )
  721. {
  722. var translatedText = TranslateOrQueueWebJobImmediateByParserResult( ui, result, true );
  723. if( translatedText != null )
  724. {
  725. // stabilized, no need to untemplate
  726. SetTranslatedText( ui, translatedText, info );
  727. }
  728. return;
  729. }
  730. }
  731. }
  732. // Lets try not to spam a service that might not be there...
  733. if( _endpoint != null )
  734. {
  735. if( _consecutiveErrors < Settings.MaxErrors && !Settings.IsShutdown )
  736. {
  737. var job = GetOrCreateTranslationJobFor( ui, stabilizedTextKey, context );
  738. job.Components.Add( ui );
  739. }
  740. }
  741. else
  742. {
  743. QueueNewUntranslatedForDisk( stabilizedTextKey );
  744. }
  745. }
  746. }
  747. } ) );
  748. }
  749. catch( Exception )
  750. {
  751. _ongoingOperations.Remove( ui );
  752. }
  753. }
  754. else
  755. {
  756. // Lets try not to spam a service that might not be there...
  757. if( _endpoint != null )
  758. {
  759. if( _consecutiveErrors < Settings.MaxErrors && !Settings.IsShutdown )
  760. {
  761. var job = GetOrCreateTranslationJobFor( ui, textKey, context );
  762. }
  763. }
  764. else
  765. {
  766. QueueNewUntranslatedForDisk( textKey );
  767. }
  768. }
  769. }
  770. }
  771. return null;
  772. }
  773. private string TranslateOrQueueWebJobImmediateByParserResult( object ui, ParserResult result, bool allowStartJob )
  774. {
  775. Dictionary<string, string> translations = new Dictionary<string, string>();
  776. // attempt to lookup ALL strings immediately; return result if possible; queue operations
  777. foreach( var kvp in result.Arguments )
  778. {
  779. var key = kvp.Key;
  780. var value = kvp.Value.TrimIfConfigured();
  781. if( !string.IsNullOrEmpty( value ) && IsTranslatable( value ) )
  782. {
  783. var valueKey = new TranslationKey( value, false, true );
  784. string partTranslation;
  785. if( TryGetTranslation( valueKey, out partTranslation ) )
  786. {
  787. translations.Add( key, partTranslation );
  788. }
  789. else if( allowStartJob )
  790. {
  791. // incomplete, must start job
  792. var context = new TranslationContext( ui, result );
  793. TranslateOrQueueWebJobImmediate( null, value, null, false, context );
  794. }
  795. }
  796. else
  797. {
  798. // the value will do
  799. translations.Add( key, value );
  800. }
  801. }
  802. if( result.Arguments.Count == translations.Count )
  803. {
  804. return result.Untemplate( translations );
  805. }
  806. else
  807. {
  808. return null; // could not perform complete translation
  809. }
  810. }
  811. /// <summary>
  812. /// Utility method that allows me to wait to call an action, until
  813. /// the text has stopped changing. This is important for 'story'
  814. /// mode text, which 'scrolls' into place slowly.
  815. /// </summary>
  816. public IEnumerator WaitForTextStablization( object ui, float delay, int maxTries, int currentTries, Action<string> onTextStabilized, Action onMaxTriesExceeded )
  817. {
  818. yield return 0; // wait a single frame to allow any external plugins to complete their hooking logic
  819. bool succeeded = false;
  820. while( currentTries < maxTries ) // shortcircuit
  821. {
  822. var beforeText = ui.GetText();
  823. yield return new WaitForSeconds( delay );
  824. var afterText = ui.GetText();
  825. if( beforeText == afterText )
  826. {
  827. onTextStabilized( afterText.TrimIfConfigured() );
  828. succeeded = true;
  829. break;
  830. }
  831. currentTries++;
  832. }
  833. if( !succeeded )
  834. {
  835. onMaxTriesExceeded();
  836. }
  837. }
  838. public IEnumerator DelayForSeconds( float delay, Action onContinue )
  839. {
  840. yield return new WaitForSeconds( delay );
  841. onContinue();
  842. }
  843. public void Update()
  844. {
  845. try
  846. {
  847. if( _endpoint != null )
  848. {
  849. _endpoint.OnUpdate();
  850. }
  851. CopyToClipboard();
  852. if( !Settings.IsShutdown )
  853. {
  854. IncrementBatchOperations();
  855. ResetThresholdTimerIfRequired();
  856. KickoffTranslations();
  857. FinishTranslations();
  858. if( _nextAdvUpdate.HasValue && Time.time > _nextAdvUpdate )
  859. {
  860. _nextAdvUpdate = null;
  861. UpdateUtageText();
  862. }
  863. }
  864. if( Input.anyKey )
  865. {
  866. if( Settings.EnablePrintHierarchy && ( Input.GetKey( KeyCode.LeftAlt ) || Input.GetKey( KeyCode.RightAlt ) ) && Input.GetKeyDown( KeyCode.Y ) )
  867. {
  868. PrintObjects();
  869. }
  870. else if( ( Input.GetKey( KeyCode.LeftAlt ) || Input.GetKey( KeyCode.RightAlt ) ) && Input.GetKeyDown( KeyCode.T ) )
  871. {
  872. ToggleTranslation();
  873. }
  874. else if( ( Input.GetKey( KeyCode.LeftAlt ) || Input.GetKey( KeyCode.RightAlt ) ) && Input.GetKeyDown( KeyCode.D ) )
  875. {
  876. DumpUntranslated();
  877. }
  878. else if( ( Input.GetKey( KeyCode.LeftAlt ) || Input.GetKey( KeyCode.RightAlt ) ) && Input.GetKeyDown( KeyCode.R ) )
  879. {
  880. ReloadTranslations();
  881. }
  882. }
  883. }
  884. catch( Exception e )
  885. {
  886. Logger.Current.Error( e, "An error occurred in Update callback. " );
  887. }
  888. }
  889. // create this as a field instead of local var, to prevent new creation on EVERY game loop
  890. private readonly List<string> _kickedOff = new List<string>();
  891. private void KickoffTranslations()
  892. {
  893. if( _endpoint == null ) return;
  894. if( Settings.EnableBatching && _endpoint.SupportsLineSplitting && !_batchLogicHasFailed && _unstartedJobs.Count > 1 && _availableBatchOperations > 0 )
  895. {
  896. while( _unstartedJobs.Count > 0 && _availableBatchOperations > 0 )
  897. {
  898. if( _endpoint.IsBusy ) break;
  899. var kvps = _unstartedJobs.Take( Settings.BatchSize ).ToList();
  900. var batch = new TranslationBatch();
  901. foreach( var kvp in kvps )
  902. {
  903. var key = kvp.Key;
  904. var job = kvp.Value;
  905. _kickedOff.Add( key );
  906. if( !job.AnyComponentsStillHasOriginalUntranslatedTextOrContextual() ) continue;
  907. batch.Add( job );
  908. _ongoingJobs[ key ] = job;
  909. }
  910. if( !batch.IsEmpty )
  911. {
  912. _availableBatchOperations--;
  913. StartCoroutine( _endpoint.Translate( batch.GetFullTranslationKey(), Settings.FromLanguage, Settings.Language, translatedText => OnBatchTranslationCompleted( batch, translatedText ),
  914. () => OnTranslationFailed( batch ) ) );
  915. }
  916. }
  917. }
  918. else
  919. {
  920. foreach( var kvp in _unstartedJobs )
  921. {
  922. if( _endpoint.IsBusy ) break;
  923. var key = kvp.Key;
  924. var job = kvp.Value;
  925. _kickedOff.Add( key );
  926. // lets see if the text should still be translated before kicking anything off
  927. if( !job.AnyComponentsStillHasOriginalUntranslatedTextOrContextual() ) continue;
  928. _ongoingJobs[ key ] = job;
  929. StartCoroutine( _endpoint.Translate( job.Key.GetDictionaryLookupKey(), Settings.FromLanguage, Settings.Language, translatedText => OnSingleTranslationCompleted( job, translatedText ),
  930. () => OnTranslationFailed( job ) ) );
  931. }
  932. }
  933. for( int i = 0 ; i < _kickedOff.Count ; i++ )
  934. {
  935. _unstartedJobs.Remove( _kickedOff[ i ] );
  936. }
  937. _kickedOff.Clear();
  938. }
  939. public void OnBatchTranslationCompleted( TranslationBatch batch, string translatedTextBatch )
  940. {
  941. Settings.TranslationCount++;
  942. if( !Settings.IsShutdown )
  943. {
  944. if( Settings.TranslationCount > Settings.MaxTranslationsBeforeShutdown )
  945. {
  946. Settings.IsShutdown = true;
  947. Logger.Current.Error( $"Maximum translations ({Settings.MaxTranslationsBeforeShutdown}) per session reached. Shutting plugin down." );
  948. }
  949. }
  950. _consecutiveErrors = 0;
  951. var succeeded = batch.MatchWithTranslations( translatedTextBatch );
  952. if( succeeded )
  953. {
  954. foreach( var tracker in batch.Trackers )
  955. {
  956. var job = tracker.Job;
  957. var translatedText = tracker.RawTranslatedText;
  958. if( !string.IsNullOrEmpty( translatedText ) )
  959. {
  960. if( Settings.ForceSplitTextAfterCharacters > 0 )
  961. {
  962. translatedText = translatedText.SplitToLines( Settings.ForceSplitTextAfterCharacters, '\n', ' ', ' ' );
  963. }
  964. job.TranslatedText = job.Key.RepairTemplate( translatedText );
  965. QueueNewTranslationForDisk( job.Key, translatedText );
  966. _completedJobs.Add( job );
  967. }
  968. AddTranslation( job.Key, job.TranslatedText );
  969. job.State = TranslationJobState.Succeeded;
  970. _ongoingJobs.Remove( job.Key.GetDictionaryLookupKey() );
  971. }
  972. }
  973. else
  974. {
  975. // might as well re-add all translation jobs, and never do this again!
  976. _batchLogicHasFailed = true;
  977. foreach( var tracker in batch.Trackers )
  978. {
  979. var key = tracker.Job.Key.GetDictionaryLookupKey();
  980. if( !_unstartedJobs.ContainsKey( key ) )
  981. {
  982. _unstartedJobs[ key ] = tracker.Job;
  983. }
  984. _ongoingJobs.Remove( key );
  985. }
  986. Logger.Current.Error( "A batch operation failed. Disabling batching and restarting failed jobs." );
  987. }
  988. }
  989. private void OnSingleTranslationCompleted( TranslationJob job, string translatedText )
  990. {
  991. Settings.TranslationCount++;
  992. if( !Settings.IsShutdown )
  993. {
  994. if( Settings.TranslationCount > Settings.MaxTranslationsBeforeShutdown )
  995. {
  996. Settings.IsShutdown = true;
  997. Logger.Current.Error( $"Maximum translations ({Settings.MaxTranslationsBeforeShutdown}) per session reached. Shutting plugin down." );
  998. }
  999. }
  1000. _consecutiveErrors = 0;
  1001. if( !string.IsNullOrEmpty( translatedText ) )
  1002. {
  1003. if( Settings.ForceSplitTextAfterCharacters > 0 )
  1004. {
  1005. translatedText = translatedText.SplitToLines( Settings.ForceSplitTextAfterCharacters, '\n', ' ', ' ' );
  1006. }
  1007. job.TranslatedText = job.Key.RepairTemplate( translatedText );
  1008. QueueNewTranslationForDisk( job.Key, translatedText );
  1009. _completedJobs.Add( job );
  1010. }
  1011. AddTranslation( job.Key, job.TranslatedText );
  1012. job.State = TranslationJobState.Succeeded;
  1013. _ongoingJobs.Remove( job.Key.GetDictionaryLookupKey() );
  1014. }
  1015. private void OnTranslationFailed( TranslationJob job )
  1016. {
  1017. _consecutiveErrors++;
  1018. job.State = TranslationJobState.Failed;
  1019. _ongoingJobs.Remove( job.Key.GetDictionaryLookupKey() );
  1020. if( !Settings.IsShutdown )
  1021. {
  1022. if( _consecutiveErrors > Settings.MaxErrors )
  1023. {
  1024. if( _endpoint.ShouldGetSecondChanceAfterFailure() )
  1025. {
  1026. Logger.Current.Warn( $"More than {Settings.MaxErrors} consecutive errors occurred. Entering fallback mode." );
  1027. _consecutiveErrors = 0;
  1028. }
  1029. else
  1030. {
  1031. Settings.IsShutdown = true;
  1032. Logger.Current.Error( $"More than {Settings.MaxErrors} consecutive errors occurred. Shutting down plugin." );
  1033. _unstartedJobs.Clear();
  1034. _completedJobs.Clear();
  1035. _ongoingJobs.Clear();
  1036. }
  1037. }
  1038. }
  1039. }
  1040. private void OnTranslationFailed( TranslationBatch batch )
  1041. {
  1042. _consecutiveErrors++;
  1043. foreach( var tracker in batch.Trackers )
  1044. {
  1045. tracker.Job.State = TranslationJobState.Failed;
  1046. _ongoingJobs.Remove( tracker.Job.Key.GetDictionaryLookupKey() );
  1047. }
  1048. if( !Settings.IsShutdown )
  1049. {
  1050. if( _consecutiveErrors > Settings.MaxErrors )
  1051. {
  1052. if( _endpoint.ShouldGetSecondChanceAfterFailure() )
  1053. {
  1054. Logger.Current.Warn( $"More than {Settings.MaxErrors} consecutive errors occurred. Entering fallback mode." );
  1055. _consecutiveErrors = 0;
  1056. }
  1057. else
  1058. {
  1059. Settings.IsShutdown = true;
  1060. Logger.Current.Error( $"More than {Settings.MaxErrors} consecutive errors occurred. Shutting down plugin." );
  1061. _unstartedJobs.Clear();
  1062. _completedJobs.Clear();
  1063. _ongoingJobs.Clear();
  1064. }
  1065. }
  1066. }
  1067. }
  1068. private void FinishTranslations()
  1069. {
  1070. if( _completedJobs.Count > 0 )
  1071. {
  1072. for( int i = _completedJobs.Count - 1 ; i >= 0 ; i-- )
  1073. {
  1074. var job = _completedJobs[ i ];
  1075. _completedJobs.RemoveAt( i );
  1076. foreach( var component in job.Components )
  1077. {
  1078. // update the original text, but only if it has not been chaanged already for some reason (could be other translator plugin or game itself)
  1079. try
  1080. {
  1081. var text = component.GetText().TrimIfConfigured();
  1082. if( text == job.Key.OriginalText )
  1083. {
  1084. var info = component.GetTranslationInfo( false );
  1085. SetTranslatedText( component, job.TranslatedText, info );
  1086. }
  1087. }
  1088. catch( NullReferenceException )
  1089. {
  1090. // might fail if compoent is no longer associated to game
  1091. }
  1092. }
  1093. // handle each context
  1094. foreach( var context in job.Contexts )
  1095. {
  1096. // are all jobs within this context completed? If so, we can set the text
  1097. if( context.Jobs.All( x => x.State == TranslationJobState.Succeeded ) )
  1098. {
  1099. try
  1100. {
  1101. var text = context.Component.GetText().TrimIfConfigured();
  1102. var result = context.Result;
  1103. Dictionary<string, string> translations = new Dictionary<string, string>();
  1104. var translatedText = TranslateOrQueueWebJobImmediateByParserResult( null, result, false );
  1105. if( !string.IsNullOrEmpty( translatedText ) )
  1106. {
  1107. if( !_translations.ContainsKey( context.Result.OriginalText ) )
  1108. {
  1109. AddTranslation( context.Result.OriginalText, translatedText );
  1110. QueueNewTranslationForDisk( context.Result.OriginalText, translatedText );
  1111. }
  1112. if( text == result.OriginalText )
  1113. {
  1114. if( translatedText != null )
  1115. {
  1116. var info = context.Component.GetTranslationInfo( false );
  1117. SetTranslatedText( context.Component, translatedText, info );
  1118. }
  1119. }
  1120. }
  1121. }
  1122. catch( NullReferenceException )
  1123. {
  1124. }
  1125. }
  1126. }
  1127. // Utage support
  1128. if( Constants.Types.AdvEngine != null
  1129. && job.OriginalSources.Any( x => Constants.Types.AdvCommand.IsAssignableFrom( x.GetType() ) ) )
  1130. {
  1131. _nextAdvUpdate = Time.time + 0.5f;
  1132. }
  1133. }
  1134. }
  1135. }
  1136. private void UpdateUtageText()
  1137. {
  1138. if( _advEngine == null )
  1139. {
  1140. _advEngine = GameObject.FindObjectOfType( Constants.Types.AdvEngine );
  1141. }
  1142. if( _advEngine != null )
  1143. {
  1144. AccessTools.Method( Constants.Types.AdvEngine, "ChangeLanguage" )?.Invoke( _advEngine, new object[ 0 ] );
  1145. }
  1146. }
  1147. private void ReloadTranslations()
  1148. {
  1149. LoadTranslations();
  1150. foreach( var kvp in ObjectExtensions.GetAllRegisteredObjects() )
  1151. {
  1152. var info = kvp.Value as TranslationInfo;
  1153. if( info != null && !string.IsNullOrEmpty( info.OriginalText ) )
  1154. {
  1155. var key = new TranslationKey( info.OriginalText, false );
  1156. if( TryGetTranslation( key, out string translatedText ) && !string.IsNullOrEmpty( translatedText ) )
  1157. {
  1158. SetTranslatedText( kvp.Key, translatedText, info ); // no need to untemplatize the translated text
  1159. }
  1160. }
  1161. }
  1162. }
  1163. private string CalculateDumpFileName()
  1164. {
  1165. int idx = 0;
  1166. string fileName = null;
  1167. do
  1168. {
  1169. idx++;
  1170. fileName = $"UntranslatedDump{idx}.txt";
  1171. }
  1172. while( File.Exists( fileName ) );
  1173. return fileName;
  1174. }
  1175. private void DumpUntranslated()
  1176. {
  1177. if( _newUntranslated.Count > 0 )
  1178. {
  1179. using( var stream = File.Open( CalculateDumpFileName(), FileMode.Append, FileAccess.Write ) )
  1180. using( var writer = new StreamWriter( stream, Encoding.UTF8 ) )
  1181. {
  1182. foreach( var untranslated in _newUntranslated )
  1183. {
  1184. writer.WriteLine( TextHelper.Encode( untranslated ) + '=' );
  1185. }
  1186. writer.Flush();
  1187. }
  1188. _newUntranslated.Clear();
  1189. }
  1190. }
  1191. private void ToggleTranslation()
  1192. {
  1193. _isInTranslatedMode = !_isInTranslatedMode;
  1194. var objects = ObjectExtensions.GetAllRegisteredObjects();
  1195. Logger.Current.Info( $"Toggling translations of {objects.Count} objects." );
  1196. if( _isInTranslatedMode )
  1197. {
  1198. // make sure we use the translated version of all texts
  1199. foreach( var kvp in objects )
  1200. {
  1201. var ui = kvp.Key;
  1202. try
  1203. {
  1204. if( ( ui as Component )?.gameObject?.activeSelf ?? false )
  1205. {
  1206. var info = (TranslationInfo)kvp.Value;
  1207. if( info != null && info.IsTranslated )
  1208. {
  1209. SetText( ui, info.TranslatedText, true, info );
  1210. }
  1211. }
  1212. }
  1213. catch( Exception )
  1214. {
  1215. // not super pretty, no...
  1216. ObjectExtensions.Remove( ui );
  1217. }
  1218. }
  1219. }
  1220. else
  1221. {
  1222. // make sure we use the original version of all texts
  1223. foreach( var kvp in objects )
  1224. {
  1225. var ui = kvp.Key;
  1226. try
  1227. {
  1228. if( ( ui as Component )?.gameObject?.activeSelf ?? false )
  1229. {
  1230. var info = (TranslationInfo)kvp.Value;
  1231. if( info != null && info.IsTranslated )
  1232. {
  1233. SetText( ui, info.OriginalText, true, info );
  1234. }
  1235. }
  1236. }
  1237. catch( Exception )
  1238. {
  1239. // not super pretty, no...
  1240. ObjectExtensions.Remove( ui );
  1241. }
  1242. }
  1243. }
  1244. }
  1245. private void CopyToClipboard()
  1246. {
  1247. if( Settings.CopyToClipboard
  1248. && _textsToCopyToClipboardOrdered.Count > 0
  1249. && Time.realtimeSinceStartup - _clipboardUpdated > Settings.ClipboardDebounceTime )
  1250. {
  1251. try
  1252. {
  1253. var builder = new StringBuilder();
  1254. foreach( var text in _textsToCopyToClipboardOrdered )
  1255. {
  1256. if( text.Length + builder.Length > Settings.MaxClipboardCopyCharacters ) break;
  1257. builder.AppendLine( text );
  1258. }
  1259. TextEditor editor = (TextEditor)GUIUtility.GetStateObject( typeof( TextEditor ), GUIUtility.keyboardControl );
  1260. editor.text = builder.ToString();
  1261. editor.SelectAll();
  1262. editor.Copy();
  1263. }
  1264. catch( Exception e )
  1265. {
  1266. Logger.Current.Error( e, "An error while copying text to clipboard." );
  1267. }
  1268. finally
  1269. {
  1270. _textsToCopyToClipboard.Clear();
  1271. _textsToCopyToClipboardOrdered.Clear();
  1272. }
  1273. }
  1274. }
  1275. private void PrintObjects()
  1276. {
  1277. using( var stream = File.Open( Path.Combine( Environment.CurrentDirectory, "hierarchy.txt" ), FileMode.Create ) )
  1278. using( var writer = new StreamWriter( stream ) )
  1279. {
  1280. foreach( var root in GetAllRoots() )
  1281. {
  1282. TraverseChildren( writer, root, "" );
  1283. }
  1284. writer.Flush();
  1285. }
  1286. }
  1287. private IEnumerable<GameObject> GetAllRoots()
  1288. {
  1289. var objects = GameObject.FindObjectsOfType<GameObject>();
  1290. foreach( var obj in objects )
  1291. {
  1292. if( obj.transform.parent == null )
  1293. {
  1294. yield return obj;
  1295. }
  1296. }
  1297. }
  1298. private void TraverseChildren( StreamWriter writer, GameObject obj, string identation )
  1299. {
  1300. var layer = LayerMask.LayerToName( obj.gameObject.layer );
  1301. var components = string.Join( ", ", obj.GetComponents<Component>().Select( x => x.GetType().Name ).ToArray() );
  1302. var line = string.Format( "{0,-50} {1,100}",
  1303. identation + obj.gameObject.name + " [" + layer + "]",
  1304. components );
  1305. writer.WriteLine( line );
  1306. for( int i = 0 ; i < obj.transform.childCount ; i++ )
  1307. {
  1308. var child = obj.transform.GetChild( i );
  1309. TraverseChildren( writer, child.gameObject, identation + " " );
  1310. }
  1311. }
  1312. }
  1313. }