AutoTranslationPlugin.cs 46 KB

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