AutoTranslationPlugin.cs 48 KB

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