AutoTranslationPlugin.cs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  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 bool TryGetTranslation( TranslationKey key, out string value )
  350. {
  351. return _translations.TryGetValue( key.GetDictionaryLookupKey(), out value );
  352. }
  353. public bool TryGetReverseTranslation( string value, out string key )
  354. {
  355. return _reverseTranslations.TryGetValue( value, out key );
  356. }
  357. public string Hook_TextChanged_WithResult( object ui, string text )
  358. {
  359. if( _hooksEnabled )
  360. {
  361. return TranslateOrQueueWebJob( ui, text, true );
  362. }
  363. return null;
  364. }
  365. public void Hook_TextChanged( object ui )
  366. {
  367. if( _hooksEnabled )
  368. {
  369. TranslateOrQueueWebJob( ui, null, false );
  370. }
  371. }
  372. public void Hook_TextInitialized( object ui )
  373. {
  374. if( _hooksEnabled )
  375. {
  376. TranslateOrQueueWebJob( ui, null, true );
  377. }
  378. }
  379. private void SetTranslatedText( object ui, string translatedText, TranslationInfo info )
  380. {
  381. info?.SetTranslatedText( translatedText );
  382. if( _isInTranslatedMode )
  383. {
  384. SetText( ui, translatedText, true, info );
  385. }
  386. }
  387. /// <summary>
  388. /// Sets the text of a UI text, while ensuring this will not fire a text changed event.
  389. /// </summary>
  390. private void SetText( object ui, string text, bool isTranslated, TranslationInfo info )
  391. {
  392. if( !info?.IsCurrentlySettingText ?? true )
  393. {
  394. try
  395. {
  396. // TODO: Disable ANY Hook
  397. _hooksEnabled = false;
  398. if( info != null )
  399. {
  400. info.IsCurrentlySettingText = true;
  401. }
  402. ui.SetText( text );
  403. if( Settings.EnableUIResizing )
  404. {
  405. if( isTranslated )
  406. {
  407. info?.ResizeUI( ui );
  408. }
  409. else
  410. {
  411. info?.UnresizeUI( ui );
  412. }
  413. }
  414. }
  415. catch( NullReferenceException )
  416. {
  417. // This is likely happened due to a scene change.
  418. }
  419. catch( Exception e )
  420. {
  421. Logger.Current.Error( e, "An error occurred while setting text on a component." );
  422. }
  423. finally
  424. {
  425. _hooksEnabled = true;
  426. if( info != null )
  427. {
  428. info.IsCurrentlySettingText = false;
  429. }
  430. }
  431. }
  432. }
  433. /// <summary>
  434. /// Determines if a text should be translated.
  435. /// </summary>
  436. private bool IsTranslatable( string str )
  437. {
  438. return _symbolCheck( str ) && str.Length <= Settings.MaxCharactersPerTranslation && !_reverseTranslations.ContainsKey( str );
  439. }
  440. public bool ShouldTranslate( object ui )
  441. {
  442. var cui = ui as Component;
  443. if( cui != null )
  444. {
  445. var go = cui.gameObject;
  446. var isDummy = go.IsDummy();
  447. if( isDummy )
  448. {
  449. return false;
  450. }
  451. var inputField = cui.gameObject.GetFirstComponentInSelfOrAncestor( Constants.Types.InputField )
  452. ?? cui.gameObject.GetFirstComponentInSelfOrAncestor( Constants.Types.TMP_InputField );
  453. return inputField == null;
  454. }
  455. return true;
  456. }
  457. private string TranslateOrQueueWebJob( object ui, string text, bool isAwakening )
  458. {
  459. var info = ui.GetTranslationInfo( isAwakening );
  460. if( !info?.IsAwake ?? false )
  461. {
  462. return null;
  463. }
  464. if( _ongoingOperations.Contains( ui ) )
  465. {
  466. return null;
  467. }
  468. var supportsStabilization = ui.SupportsStabilization();
  469. if( Settings.Delay == 0 || !supportsStabilization )
  470. {
  471. return TranslateOrQueueWebJobImmediate( ui, text, info, supportsStabilization );
  472. }
  473. else
  474. {
  475. StartCoroutine(
  476. DelayForSeconds( Settings.Delay, () =>
  477. {
  478. TranslateOrQueueWebJobImmediate( ui, text, info, supportsStabilization );
  479. } ) );
  480. }
  481. return null;
  482. }
  483. public static bool IsCurrentlySetting( TranslationInfo info )
  484. {
  485. if( info == null ) return false;
  486. return info.IsCurrentlySettingText;
  487. }
  488. /// <summary>
  489. /// Translates the string of a UI text or queues it up to be translated
  490. /// by the HTTP translation service.
  491. /// </summary>
  492. private string TranslateOrQueueWebJobImmediate( object ui, string text, TranslationInfo info, bool supportsStabilization, TranslationContext context = null )
  493. {
  494. // Get the trimmed text
  495. text = ( text ?? ui.GetText() ).TrimIfConfigured();
  496. // Ensure that we actually want to translate this text and its owning UI element.
  497. if( !string.IsNullOrEmpty( text ) && IsTranslatable( text ) && ShouldTranslate( ui ) && !IsCurrentlySetting( info ) )
  498. {
  499. info?.Reset( text );
  500. var textKey = new TranslationKey( text, context == null && !supportsStabilization, context != null );
  501. // if we already have translation loaded in our _translatios dictionary, simply load it and set text
  502. string translation;
  503. if( TryGetTranslation( textKey, out translation ) )
  504. {
  505. QueueNewUntranslatedForClipboard( textKey );
  506. if( !string.IsNullOrEmpty( translation ) )
  507. {
  508. SetTranslatedText( ui, textKey.Untemplate( translation ), info );
  509. return translation;
  510. }
  511. }
  512. else
  513. {
  514. if( context == null && ui.SupportsRichText() )
  515. {
  516. var parser = UnityTextParsers.GetTextParserByGameEngine();
  517. if( parser != null )
  518. {
  519. var result = parser.Parse( text );
  520. if( result.HasRichSyntax )
  521. {
  522. translation = TranslateOrQueueWebJobImmediateByParserResult( ui, result, true );
  523. if( translation != null )
  524. {
  525. SetTranslatedText( ui, translation, info ); // get rid of textKey here!!
  526. }
  527. return translation;
  528. }
  529. }
  530. }
  531. if( supportsStabilization && context == null ) // never stabilize a text that is contextualized or that does not support stabilization
  532. {
  533. // if we dont know what text to translate it to, we need to figure it out.
  534. // this might take a while, so add the UI text component to the ongoing operations
  535. // list, so we dont start multiple operations for it, as its text might be constantly
  536. // changing.
  537. _ongoingOperations.Add( ui );
  538. // start a coroutine, that will execute once the string of the UI text has stopped
  539. // changing. For all texts except 'story' texts, this will add a delay for exactly
  540. // 0.5s to the translation. This is barely noticable.
  541. //
  542. // on the other hand, for 'story' texts, this will take the time that it takes
  543. // for the text to stop 'scrolling' in.
  544. try
  545. {
  546. StartCoroutine(
  547. WaitForTextStablization(
  548. ui: ui,
  549. delay: 1.0f, // 1 second to prevent '1 second tickers' from getting translated
  550. maxTries: 60, // 50 tries, about 1 minute
  551. currentTries: 0,
  552. onMaxTriesExceeded: () =>
  553. {
  554. _ongoingOperations.Remove( ui );
  555. },
  556. onTextStabilized: stabilizedText =>
  557. {
  558. _ongoingOperations.Remove( ui );
  559. if( !string.IsNullOrEmpty( stabilizedText ) && IsTranslatable( stabilizedText ) )
  560. {
  561. var stabilizedTextKey = new TranslationKey( stabilizedText, false );
  562. QueueNewUntranslatedForClipboard( stabilizedTextKey );
  563. info?.Reset( stabilizedText );
  564. // once the text has stabilized, attempt to look it up
  565. if( TryGetTranslation( stabilizedTextKey, out translation ) )
  566. {
  567. if( !string.IsNullOrEmpty( translation ) )
  568. {
  569. // stabilized, no need to untemplate
  570. SetTranslatedText( ui, translation, info );
  571. }
  572. }
  573. else
  574. {
  575. if( context == null && ui.SupportsRichText() )
  576. {
  577. var parser = UnityTextParsers.GetTextParserByGameEngine();
  578. if( parser != null )
  579. {
  580. var result = parser.Parse( stabilizedText );
  581. if( result.HasRichSyntax )
  582. {
  583. var translatedText = TranslateOrQueueWebJobImmediateByParserResult( ui, result, true );
  584. if( translatedText != null )
  585. {
  586. // stabilized, no need to untemplate
  587. SetTranslatedText( ui, translatedText, info );
  588. }
  589. return;
  590. }
  591. }
  592. }
  593. // Lets try not to spam a service that might not be there...
  594. if( _endpoint != null )
  595. {
  596. if( _consecutiveErrors < Settings.MaxErrors && !Settings.IsShutdown )
  597. {
  598. var job = GetOrCreateTranslationJobFor( ui, stabilizedTextKey, context );
  599. job.Components.Add( ui );
  600. }
  601. }
  602. else
  603. {
  604. QueueNewUntranslatedForDisk( stabilizedTextKey );
  605. }
  606. }
  607. }
  608. } ) );
  609. }
  610. catch( Exception )
  611. {
  612. _ongoingOperations.Remove( ui );
  613. }
  614. }
  615. else
  616. {
  617. // Lets try not to spam a service that might not be there...
  618. if( _endpoint != null )
  619. {
  620. if( _consecutiveErrors < Settings.MaxErrors && !Settings.IsShutdown )
  621. {
  622. var job = GetOrCreateTranslationJobFor( ui, textKey, context );
  623. }
  624. }
  625. else
  626. {
  627. QueueNewUntranslatedForDisk( textKey );
  628. }
  629. }
  630. }
  631. }
  632. return null;
  633. }
  634. private string TranslateOrQueueWebJobImmediateByParserResult( object ui, ParserResult result, bool allowStartJob )
  635. {
  636. Dictionary<string, string> translations = new Dictionary<string, string>();
  637. // attempt to lookup ALL strings immediately; return result if possible; queue operations
  638. foreach( var kvp in result.Arguments )
  639. {
  640. var key = kvp.Key;
  641. var value = kvp.Value.TrimIfConfigured();
  642. if( !string.IsNullOrEmpty( value ) && IsTranslatable( value ) )
  643. {
  644. var valueKey = new TranslationKey( value, false, true );
  645. string partTranslation;
  646. if( TryGetTranslation( valueKey, out partTranslation ) )
  647. {
  648. translations.Add( key, partTranslation );
  649. }
  650. else if( allowStartJob )
  651. {
  652. // incomplete, must start job
  653. var context = new TranslationContext( ui, result );
  654. TranslateOrQueueWebJobImmediate( null, value, null, false, context );
  655. }
  656. }
  657. else
  658. {
  659. // the value will do
  660. translations.Add( key, value );
  661. }
  662. }
  663. if( result.Arguments.Count == translations.Count )
  664. {
  665. return result.Untemplate( translations );
  666. }
  667. else
  668. {
  669. return null; // could not perform complete translation
  670. }
  671. }
  672. /// <summary>
  673. /// Utility method that allows me to wait to call an action, until
  674. /// the text has stopped changing. This is important for 'story'
  675. /// mode text, which 'scrolls' into place slowly.
  676. /// </summary>
  677. public IEnumerator WaitForTextStablization( object ui, float delay, int maxTries, int currentTries, Action<string> onTextStabilized, Action onMaxTriesExceeded )
  678. {
  679. if( currentTries < maxTries ) // shortcircuit
  680. {
  681. var beforeText = ui.GetText();
  682. yield return new WaitForSeconds( delay );
  683. var afterText = ui.GetText();
  684. if( beforeText == afterText )
  685. {
  686. onTextStabilized( afterText.TrimIfConfigured() );
  687. }
  688. else
  689. {
  690. StartCoroutine( WaitForTextStablization( ui, delay, maxTries, currentTries + 1, onTextStabilized, onMaxTriesExceeded ) );
  691. }
  692. }
  693. else
  694. {
  695. onMaxTriesExceeded();
  696. }
  697. }
  698. public IEnumerator DelayForSeconds( float delay, Action onContinue )
  699. {
  700. yield return new WaitForSeconds( delay );
  701. onContinue();
  702. }
  703. public void Update()
  704. {
  705. try
  706. {
  707. if( _endpoint != null )
  708. {
  709. _endpoint.OnUpdate();
  710. }
  711. CopyToClipboard();
  712. if( !Settings.IsShutdown )
  713. {
  714. IncrementBatchOperations();
  715. ResetThresholdTimerIfRequired();
  716. KickoffTranslations();
  717. FinishTranslations();
  718. if( _nextAdvUpdate.HasValue && Time.time > _nextAdvUpdate )
  719. {
  720. _nextAdvUpdate = null;
  721. UpdateUtageText();
  722. }
  723. }
  724. if( Input.anyKey )
  725. {
  726. if( Settings.EnablePrintHierarchy && ( Input.GetKey( KeyCode.LeftAlt ) || Input.GetKey( KeyCode.RightAlt ) ) && Input.GetKeyDown( KeyCode.Y ) )
  727. {
  728. PrintObjects();
  729. }
  730. else if( ( Input.GetKey( KeyCode.LeftAlt ) || Input.GetKey( KeyCode.RightAlt ) ) && Input.GetKeyDown( KeyCode.T ) )
  731. {
  732. ToggleTranslation();
  733. }
  734. else if( ( Input.GetKey( KeyCode.LeftAlt ) || Input.GetKey( KeyCode.RightAlt ) ) && Input.GetKeyDown( KeyCode.D ) )
  735. {
  736. DumpUntranslated();
  737. }
  738. else if( ( Input.GetKey( KeyCode.LeftAlt ) || Input.GetKey( KeyCode.RightAlt ) ) && Input.GetKeyDown( KeyCode.R ) )
  739. {
  740. ReloadTranslations();
  741. }
  742. }
  743. }
  744. catch( Exception e )
  745. {
  746. Logger.Current.Error( e, "An error occurred in Update callback. " );
  747. }
  748. }
  749. // create this as a field instead of local var, to prevent new creation on EVERY game loop
  750. private readonly List<string> _kickedOff = new List<string>();
  751. private void KickoffTranslations()
  752. {
  753. if( _endpoint == null ) return;
  754. if( Settings.EnableBatching && _endpoint.SupportsLineSplitting && !_batchLogicHasFailed && _unstartedJobs.Count > 1 && _availableBatchOperations > 0 )
  755. {
  756. while( _unstartedJobs.Count > 0 && _availableBatchOperations > 0 )
  757. {
  758. if( _endpoint.IsBusy ) break;
  759. var kvps = _unstartedJobs.Take( Settings.BatchSize ).ToList();
  760. var batch = new TranslationBatch();
  761. foreach( var kvp in kvps )
  762. {
  763. var key = kvp.Key;
  764. var job = kvp.Value;
  765. _kickedOff.Add( key );
  766. if( !job.AnyComponentsStillHasOriginalUntranslatedTextOrContextual() ) continue;
  767. batch.Add( job );
  768. _ongoingJobs[ key ] = job;
  769. }
  770. if( !batch.IsEmpty )
  771. {
  772. _availableBatchOperations--;
  773. StartCoroutine( _endpoint.Translate( batch.GetFullTranslationKey(), Settings.FromLanguage, Settings.Language, translatedText => OnBatchTranslationCompleted( batch, translatedText ),
  774. () => OnTranslationFailed( batch ) ) );
  775. }
  776. }
  777. }
  778. else
  779. {
  780. foreach( var kvp in _unstartedJobs )
  781. {
  782. if( _endpoint.IsBusy ) break;
  783. var key = kvp.Key;
  784. var job = kvp.Value;
  785. _kickedOff.Add( key );
  786. // lets see if the text should still be translated before kicking anything off
  787. if( !job.AnyComponentsStillHasOriginalUntranslatedTextOrContextual() ) continue;
  788. _ongoingJobs[ key ] = job;
  789. StartCoroutine( _endpoint.Translate( job.Key.GetDictionaryLookupKey(), Settings.FromLanguage, Settings.Language, translatedText => OnSingleTranslationCompleted( job, translatedText ),
  790. () => OnTranslationFailed( job ) ) );
  791. }
  792. }
  793. for( int i = 0 ; i < _kickedOff.Count ; i++ )
  794. {
  795. _unstartedJobs.Remove( _kickedOff[ i ] );
  796. }
  797. _kickedOff.Clear();
  798. }
  799. public void OnBatchTranslationCompleted( TranslationBatch batch, string translatedTextBatch )
  800. {
  801. Settings.TranslationCount++;
  802. if( !Settings.IsShutdown )
  803. {
  804. if( Settings.TranslationCount > Settings.MaxTranslationsBeforeShutdown )
  805. {
  806. Settings.IsShutdown = true;
  807. Logger.Current.Error( $"Maximum translations ({Settings.MaxTranslationsBeforeShutdown}) per session reached. Shutting plugin down." );
  808. }
  809. }
  810. _consecutiveErrors = 0;
  811. var succeeded = batch.MatchWithTranslations( translatedTextBatch );
  812. if( succeeded )
  813. {
  814. foreach( var tracker in batch.Trackers )
  815. {
  816. var job = tracker.Job;
  817. var translatedText = tracker.RawTranslatedText;
  818. if( !string.IsNullOrEmpty( translatedText ) )
  819. {
  820. if( Settings.ForceSplitTextAfterCharacters > 0 )
  821. {
  822. translatedText = translatedText.SplitToLines( Settings.ForceSplitTextAfterCharacters, '\n', ' ', ' ' );
  823. }
  824. job.TranslatedText = job.Key.RepairTemplate( translatedText );
  825. QueueNewTranslationForDisk( job.Key, translatedText );
  826. _completedJobs.Add( job );
  827. }
  828. AddTranslation( job.Key, job.TranslatedText );
  829. job.State = TranslationJobState.Succeeded;
  830. _ongoingJobs.Remove( job.Key.GetDictionaryLookupKey() );
  831. }
  832. }
  833. else
  834. {
  835. // might as well re-add all translation jobs, and never do this again!
  836. _batchLogicHasFailed = true;
  837. foreach( var tracker in batch.Trackers )
  838. {
  839. var key = tracker.Job.Key.GetDictionaryLookupKey();
  840. if( !_unstartedJobs.ContainsKey( key ) )
  841. {
  842. _unstartedJobs[ key ] = tracker.Job;
  843. }
  844. _ongoingJobs.Remove( key );
  845. }
  846. Logger.Current.Error( "A batch operation failed. Disabling batching and restarting failed jobs." );
  847. }
  848. }
  849. private void OnSingleTranslationCompleted( TranslationJob job, string translatedText )
  850. {
  851. Settings.TranslationCount++;
  852. if( !Settings.IsShutdown )
  853. {
  854. if( Settings.TranslationCount > Settings.MaxTranslationsBeforeShutdown )
  855. {
  856. Settings.IsShutdown = true;
  857. Logger.Current.Error( $"Maximum translations ({Settings.MaxTranslationsBeforeShutdown}) per session reached. Shutting plugin down." );
  858. }
  859. }
  860. _consecutiveErrors = 0;
  861. if( !string.IsNullOrEmpty( translatedText ) )
  862. {
  863. if( Settings.ForceSplitTextAfterCharacters > 0 )
  864. {
  865. translatedText = translatedText.SplitToLines( Settings.ForceSplitTextAfterCharacters, '\n', ' ', ' ' );
  866. }
  867. job.TranslatedText = job.Key.RepairTemplate( translatedText );
  868. QueueNewTranslationForDisk( job.Key, translatedText );
  869. _completedJobs.Add( job );
  870. }
  871. AddTranslation( job.Key, job.TranslatedText );
  872. job.State = TranslationJobState.Succeeded;
  873. _ongoingJobs.Remove( job.Key.GetDictionaryLookupKey() );
  874. }
  875. private void OnTranslationFailed( TranslationJob job )
  876. {
  877. _consecutiveErrors++;
  878. job.State = TranslationJobState.Failed;
  879. _ongoingJobs.Remove( job.Key.GetDictionaryLookupKey() );
  880. if( !Settings.IsShutdown )
  881. {
  882. if( _consecutiveErrors > Settings.MaxErrors )
  883. {
  884. if( _endpoint.ShouldGetSecondChanceAfterFailure() )
  885. {
  886. Logger.Current.Warn( $"More than {Settings.MaxErrors} consecutive errors occurred. Entering fallback mode." );
  887. _consecutiveErrors = 0;
  888. }
  889. else
  890. {
  891. Settings.IsShutdown = true;
  892. Logger.Current.Error( $"More than {Settings.MaxErrors} consecutive errors occurred. Shutting down plugin." );
  893. _unstartedJobs.Clear();
  894. _completedJobs.Clear();
  895. _ongoingJobs.Clear();
  896. }
  897. }
  898. }
  899. }
  900. private void OnTranslationFailed( TranslationBatch batch )
  901. {
  902. _consecutiveErrors++;
  903. foreach( var tracker in batch.Trackers )
  904. {
  905. tracker.Job.State = TranslationJobState.Failed;
  906. _ongoingJobs.Remove( tracker.Job.Key.GetDictionaryLookupKey() );
  907. }
  908. if( !Settings.IsShutdown )
  909. {
  910. if( _consecutiveErrors > Settings.MaxErrors )
  911. {
  912. if( _endpoint.ShouldGetSecondChanceAfterFailure() )
  913. {
  914. Logger.Current.Warn( $"More than {Settings.MaxErrors} consecutive errors occurred. Entering fallback mode." );
  915. _consecutiveErrors = 0;
  916. }
  917. else
  918. {
  919. Settings.IsShutdown = true;
  920. Logger.Current.Error( $"More than {Settings.MaxErrors} consecutive errors occurred. Shutting down plugin." );
  921. _unstartedJobs.Clear();
  922. _completedJobs.Clear();
  923. _ongoingJobs.Clear();
  924. }
  925. }
  926. }
  927. }
  928. private void FinishTranslations()
  929. {
  930. if( _completedJobs.Count > 0 )
  931. {
  932. for( int i = _completedJobs.Count - 1 ; i >= 0 ; i-- )
  933. {
  934. var job = _completedJobs[ i ];
  935. _completedJobs.RemoveAt( i );
  936. foreach( var component in job.Components )
  937. {
  938. // update the original text, but only if it has not been chaanged already for some reason (could be other translator plugin or game itself)
  939. try
  940. {
  941. var text = component.GetText().TrimIfConfigured();
  942. if( text == job.Key.OriginalText )
  943. {
  944. var info = component.GetTranslationInfo( false );
  945. SetTranslatedText( component, job.TranslatedText, info );
  946. }
  947. }
  948. catch( NullReferenceException )
  949. {
  950. // might fail if compoent is no longer associated to game
  951. }
  952. }
  953. // handle each context
  954. foreach( var context in job.Contexts )
  955. {
  956. // are all jobs within this context completed? If so, we can set the text
  957. if( context.Jobs.All( x => x.State == TranslationJobState.Succeeded ) )
  958. {
  959. try
  960. {
  961. var text = context.Component.GetText().TrimIfConfigured();
  962. var result = context.Result;
  963. if( text == result.OriginalText )
  964. {
  965. Dictionary<string, string> translations = new Dictionary<string, string>();
  966. var translatedText = TranslateOrQueueWebJobImmediateByParserResult( null, result, false );
  967. if( translatedText != null )
  968. {
  969. var info = context.Component.GetTranslationInfo( false );
  970. SetTranslatedText( context.Component, translatedText, info );
  971. }
  972. }
  973. }
  974. catch( NullReferenceException )
  975. {
  976. }
  977. }
  978. }
  979. // Utage support
  980. if( Constants.Types.AdvEngine != null
  981. && job.OriginalSources.Any( x => Constants.Types.AdvCommand.IsAssignableFrom( x.GetType() ) ) )
  982. {
  983. _nextAdvUpdate = Time.time + 0.5f;
  984. }
  985. }
  986. }
  987. }
  988. private void UpdateUtageText()
  989. {
  990. if( _advEngine == null )
  991. {
  992. _advEngine = GameObject.FindObjectOfType( Constants.Types.AdvEngine );
  993. }
  994. if( _advEngine != null )
  995. {
  996. AccessTools.Method( Constants.Types.AdvEngine, "ChangeLanguage" )?.Invoke( _advEngine, new object[ 0 ] );
  997. }
  998. }
  999. private void ReloadTranslations()
  1000. {
  1001. LoadTranslations();
  1002. foreach( var kvp in ObjectExtensions.GetAllRegisteredObjects() )
  1003. {
  1004. var info = kvp.Value as TranslationInfo;
  1005. if( info != null && !string.IsNullOrEmpty( info.OriginalText ) )
  1006. {
  1007. var key = new TranslationKey( info.OriginalText, false );
  1008. if( TryGetTranslation( key, out string translatedText ) && !string.IsNullOrEmpty( translatedText ) )
  1009. {
  1010. SetTranslatedText( kvp.Key, translatedText, info ); // no need to untemplatize the translated text
  1011. }
  1012. }
  1013. }
  1014. }
  1015. private string CalculateDumpFileName()
  1016. {
  1017. int idx = 0;
  1018. string fileName = null;
  1019. do
  1020. {
  1021. idx++;
  1022. fileName = $"UntranslatedDump{idx}.txt";
  1023. }
  1024. while( File.Exists( fileName ) );
  1025. return fileName;
  1026. }
  1027. private void DumpUntranslated()
  1028. {
  1029. if( _newUntranslated.Count > 0 )
  1030. {
  1031. using( var stream = File.Open( CalculateDumpFileName(), FileMode.Append, FileAccess.Write ) )
  1032. using( var writer = new StreamWriter( stream, Encoding.UTF8 ) )
  1033. {
  1034. foreach( var untranslated in _newUntranslated )
  1035. {
  1036. writer.WriteLine( TextHelper.Encode( untranslated ) + '=' );
  1037. }
  1038. writer.Flush();
  1039. }
  1040. _newUntranslated.Clear();
  1041. }
  1042. }
  1043. private void ToggleTranslation()
  1044. {
  1045. _isInTranslatedMode = !_isInTranslatedMode;
  1046. var objects = ObjectExtensions.GetAllRegisteredObjects();
  1047. Logger.Current.Info( $"Toggling translations of {objects.Count} objects." );
  1048. if( _isInTranslatedMode )
  1049. {
  1050. // make sure we use the translated version of all texts
  1051. foreach( var kvp in objects )
  1052. {
  1053. var ui = kvp.Key;
  1054. try
  1055. {
  1056. if( ( ui as Component )?.gameObject?.activeSelf ?? false )
  1057. {
  1058. var info = (TranslationInfo)kvp.Value;
  1059. if( info != null && info.IsTranslated )
  1060. {
  1061. SetText( ui, info.TranslatedText, true, info );
  1062. }
  1063. }
  1064. }
  1065. catch( Exception )
  1066. {
  1067. // not super pretty, no...
  1068. ObjectExtensions.Remove( ui );
  1069. }
  1070. }
  1071. }
  1072. else
  1073. {
  1074. // make sure we use the original version of all texts
  1075. foreach( var kvp in objects )
  1076. {
  1077. var ui = kvp.Key;
  1078. try
  1079. {
  1080. if( ( ui as Component )?.gameObject?.activeSelf ?? false )
  1081. {
  1082. var info = (TranslationInfo)kvp.Value;
  1083. if( info != null && info.IsTranslated )
  1084. {
  1085. SetText( ui, info.OriginalText, true, info );
  1086. }
  1087. }
  1088. }
  1089. catch( Exception )
  1090. {
  1091. // not super pretty, no...
  1092. ObjectExtensions.Remove( ui );
  1093. }
  1094. }
  1095. }
  1096. }
  1097. private void CopyToClipboard()
  1098. {
  1099. if( Settings.CopyToClipboard
  1100. && _textsToCopyToClipboardOrdered.Count > 0
  1101. && Time.realtimeSinceStartup - _clipboardUpdated > Settings.ClipboardDebounceTime )
  1102. {
  1103. try
  1104. {
  1105. var builder = new StringBuilder();
  1106. foreach( var text in _textsToCopyToClipboardOrdered )
  1107. {
  1108. if( text.Length + builder.Length > Settings.MaxClipboardCopyCharacters ) break;
  1109. builder.AppendLine( text );
  1110. }
  1111. TextEditor editor = (TextEditor)GUIUtility.GetStateObject( typeof( TextEditor ), GUIUtility.keyboardControl );
  1112. editor.text = builder.ToString();
  1113. editor.SelectAll();
  1114. editor.Copy();
  1115. }
  1116. catch( Exception e )
  1117. {
  1118. Logger.Current.Error( e, "An error while copying text to clipboard." );
  1119. }
  1120. finally
  1121. {
  1122. _textsToCopyToClipboard.Clear();
  1123. _textsToCopyToClipboardOrdered.Clear();
  1124. }
  1125. }
  1126. }
  1127. private void PrintObjects()
  1128. {
  1129. using( var stream = File.Open( Path.Combine( Environment.CurrentDirectory, "hierarchy.txt" ), FileMode.Create ) )
  1130. using( var writer = new StreamWriter( stream ) )
  1131. {
  1132. foreach( var root in GetAllRoots() )
  1133. {
  1134. TraverseChildren( writer, root, "" );
  1135. }
  1136. writer.Flush();
  1137. }
  1138. }
  1139. private IEnumerable<GameObject> GetAllRoots()
  1140. {
  1141. var objects = GameObject.FindObjectsOfType<GameObject>();
  1142. foreach( var obj in objects )
  1143. {
  1144. if( obj.transform.parent == null )
  1145. {
  1146. yield return obj;
  1147. }
  1148. }
  1149. }
  1150. private void TraverseChildren( StreamWriter writer, GameObject obj, string identation )
  1151. {
  1152. var layer = LayerMask.LayerToName( obj.gameObject.layer );
  1153. var components = string.Join( ", ", obj.GetComponents<Component>().Select( x => x.GetType().Name ).ToArray() );
  1154. var line = string.Format( "{0,-50} {1,100}",
  1155. identation + obj.gameObject.name + " [" + layer + "]",
  1156. components );
  1157. writer.WriteLine( line );
  1158. for( int i = 0 ; i < obj.transform.childCount ; i++ )
  1159. {
  1160. var child = obj.transform.GetChild( i );
  1161. TraverseChildren( writer, child.gameObject, identation + " " );
  1162. }
  1163. }
  1164. }
  1165. }