AutoTranslationPlugin.cs 48 KB

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