AutoTranslationPlugin.cs 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434
  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. private static readonly char[][] TranslationSplitters = new char[][] { new char[] { '\t' }, new char[] { '=' } };
  36. /// <summary>
  37. /// Allow the instance to be accessed statically, as only one will exist.
  38. /// </summary>
  39. public static AutoTranslationPlugin Current;
  40. /// <summary>
  41. /// These are the currently running translation jobs (being translated by an http request).
  42. /// </summary>
  43. private List<TranslationJob> _completedJobs = new List<TranslationJob>();
  44. private Dictionary<string, TranslationJob> _unstartedJobs = new Dictionary<string, TranslationJob>();
  45. private Dictionary<string, TranslationJob> _ongoingJobs = new Dictionary<string, TranslationJob>();
  46. /// <summary>
  47. /// All the translations are stored in this dictionary.
  48. /// </summary>
  49. private Dictionary<string, string> _staticTranslations = new Dictionary<string, string>();
  50. private Dictionary<string, string> _translations = new Dictionary<string, string>();
  51. private Dictionary<string, string> _reverseTranslations = new Dictionary<string, string>();
  52. /// <summary>
  53. /// These are the new translations that has not yet been persisted to the file system.
  54. /// </summary>
  55. private object _writeToFileSync = new object();
  56. private Dictionary<string, string> _newTranslations = new Dictionary<string, string>();
  57. private HashSet<string> _newUntranslated = new HashSet<string>();
  58. /// <summary>
  59. /// Keeps track of things to copy to clipboard.
  60. /// </summary>
  61. private List<string> _textsToCopyToClipboardOrdered = new List<string>();
  62. private HashSet<string> _textsToCopyToClipboard = new HashSet<string>();
  63. private float _clipboardUpdated = 0.0f;
  64. /// <summary>
  65. /// The number of http translation errors that has occurred up until now.
  66. /// </summary>
  67. private int _consecutiveErrors = 0;
  68. /// <summary>
  69. /// This is a hash set that contains all Text components that is currently being worked on by
  70. /// the translation plugin.
  71. /// </summary>
  72. private HashSet<object> _ongoingOperations = new HashSet<object>();
  73. /// <summary>
  74. /// This function will check if there are symbols of a given language contained in a string.
  75. /// </summary>
  76. private Func<string, bool> _symbolCheck;
  77. /// <summary>
  78. /// Texts currently being scheduled for translation by 'immediate' components.
  79. /// </summary>
  80. private HashSet<string> _immediatelyTranslating = new HashSet<string>();
  81. private Dictionary<string, byte[]> _translatedImages = new Dictionary<string, byte[]>( StringComparer.InvariantCultureIgnoreCase );
  82. private HashSet<string> _untranslatedImages = new HashSet<string>();
  83. private Component _advEngine;
  84. private float? _nextAdvUpdate;
  85. private IKnownEndpoint _endpoint;
  86. private int[] _currentTranslationsQueuedPerSecondRollingWindow = new int[ Settings.TranslationQueueWatchWindow ];
  87. private float? _timeExceededThreshold;
  88. private float _translationsQueuedPerSecond;
  89. private bool _isInTranslatedMode = true;
  90. private bool _textHooksEnabled = true;
  91. private bool _imageHooksEnabled = true;
  92. private bool _batchLogicHasFailed = false;
  93. private int _availableBatchOperations = Settings.MaxAvailableBatchOperations;
  94. private float _batchOperationSecondCounter = 0;
  95. private string[] _previouslyQueuedText = new string[ Settings.PreviousTextStaggerCount ];
  96. private int _staggerTextCursor = 0;
  97. private int _concurrentStaggers = 0;
  98. private int _frameForLastQueuedTranslation = -1;
  99. private int _consecutiveFramesTranslated = 0;
  100. private int _secondForQueuedTranslation = -1;
  101. private int _consecutiveSecondsTranslated = 0;
  102. private bool _hasOverrideFont = false;
  103. private bool _overrideFont = false;
  104. private bool _initialized = false;
  105. private bool _temporarilyDisabled = false;
  106. public void Initialize()
  107. {
  108. Current = this;
  109. if( Logger.Current == null )
  110. {
  111. Logger.Current = new ConsoleLogger();
  112. }
  113. try
  114. {
  115. Settings.Configure();
  116. }
  117. catch( Exception e )
  118. {
  119. Logger.Current.Error( e, "An error occurred during configuration. Shutting plugin down." );
  120. _endpoint = null;
  121. Settings.IsShutdown = true;
  122. return;
  123. }
  124. if( Settings.EnableConsole ) DebugConsole.Enable();
  125. HooksSetup.InstallTextHooks();
  126. HooksSetup.InstallImageHooks();
  127. try
  128. {
  129. _endpoint = KnownEndpoints.FindEndpoint( Settings.ServiceEndpoint );
  130. }
  131. catch( Exception e )
  132. {
  133. Logger.Current.Error( e, "An unexpected error occurred during initialization of endpoint." );
  134. }
  135. if( !TextHelper.IsFromLanguageSupported( Settings.FromLanguage ) )
  136. {
  137. Logger.Current.Error( $"The plugin has been configured to use the 'FromLanguage={Settings.FromLanguage}'. This language is not supported. Shutting plugin down." );
  138. _endpoint = null;
  139. Settings.IsShutdown = true;
  140. }
  141. _symbolCheck = TextHelper.GetSymbolCheck( Settings.FromLanguage );
  142. if( !string.IsNullOrEmpty( Settings.OverrideFont ) )
  143. {
  144. var available = Font.GetOSInstalledFontNames();
  145. if( !available.Contains( Settings.OverrideFont ) )
  146. {
  147. Logger.Current.Error( $"The specified override font is not available. Available fonts: " + string.Join( ", ", available ) );
  148. Settings.OverrideFont = null;
  149. }
  150. else
  151. {
  152. _hasOverrideFont = true;
  153. }
  154. _overrideFont = _hasOverrideFont;
  155. }
  156. if( Features.SupportsScenes && Settings.EnableTextureScanOnSceneLoad && ( Settings.EnableTextureDumping || Settings.EnableTextureTranslation ) )
  157. {
  158. try
  159. {
  160. EnableSceneLoadScan();
  161. }
  162. catch( Exception e )
  163. {
  164. Logger.Current.Error( e, "An error occurred while settings up texture scene-load scans." );
  165. }
  166. }
  167. LoadTranslations();
  168. LoadStaticTranslations();
  169. // start a thread that will periodically removed unused references
  170. var t1 = new Thread( MaintenanceLoop );
  171. t1.IsBackground = true;
  172. t1.Start();
  173. // start a thread that will periodically save new translations
  174. var t2 = new Thread( SaveTranslationsLoop );
  175. t2.IsBackground = true;
  176. t2.Start();
  177. }
  178. private IEnumerable<string> GetTranslationFiles()
  179. {
  180. return Directory.GetFiles( Path.Combine( Config.Current.DataPath, Settings.TranslationDirectory ), $"*.txt", SearchOption.AllDirectories )
  181. .Select( x => x.Replace( "/", "\\" ) );
  182. }
  183. private IEnumerable<string> GetTextureFiles()
  184. {
  185. return Directory.GetFiles( Path.Combine( Config.Current.DataPath, Settings.TextureDirectory ), $"*.png", SearchOption.AllDirectories )
  186. .Select( x => x.Replace( "/", "\\" ) );
  187. }
  188. private void MaintenanceLoop( object state )
  189. {
  190. while( true )
  191. {
  192. try
  193. {
  194. ObjectExtensions.Cull();
  195. }
  196. catch( Exception e )
  197. {
  198. Logger.Current.Error( e, "An unexpected error occurred while removing GC'ed resources." );
  199. }
  200. Thread.Sleep( 1000 * 60 );
  201. }
  202. }
  203. private void SaveTranslationsLoop( object state )
  204. {
  205. try
  206. {
  207. while( true )
  208. {
  209. if( _newTranslations.Count > 0 )
  210. {
  211. lock( _writeToFileSync )
  212. {
  213. if( _newTranslations.Count > 0 )
  214. {
  215. using( var stream = File.Open( Settings.AutoTranslationsFilePath, FileMode.Append, FileAccess.Write ) )
  216. using( var writer = new StreamWriter( stream, Encoding.UTF8 ) )
  217. {
  218. foreach( var kvp in _newTranslations )
  219. {
  220. writer.WriteLine( TextHelper.Encode( kvp.Key ) + '=' + TextHelper.Encode( kvp.Value ) );
  221. }
  222. writer.Flush();
  223. }
  224. _newTranslations.Clear();
  225. }
  226. }
  227. }
  228. else
  229. {
  230. Thread.Sleep( 5000 );
  231. }
  232. }
  233. }
  234. catch( Exception e )
  235. {
  236. Logger.Current.Error( e, "An error occurred while saving translations to disk." );
  237. }
  238. }
  239. public void EnableSceneLoadScan()
  240. {
  241. EnableSceneLoadScanInternal();
  242. }
  243. public void EnableSceneLoadScanInternal()
  244. {
  245. // specified in own method, because of chance that this has changed through Unity lifetime
  246. SceneManager.sceneLoaded += ( arg1, arg2 ) => SceneManager_SceneLoaded();
  247. }
  248. private void SceneManager_SceneLoaded()
  249. {
  250. Logger.Current.Info( "SceneLoading..." );
  251. var startTime = Time.realtimeSinceStartup;
  252. ManualHookForTextures();
  253. var endTime = Time.realtimeSinceStartup;
  254. Logger.Current.Info( $"SceneLoaded (took {Math.Round( endTime - startTime, 2 )} seconds)" );
  255. }
  256. /// <summary>
  257. /// Loads the translations found in Translation.{lang}.txt
  258. /// </summary>
  259. private void LoadTranslations()
  260. {
  261. try
  262. {
  263. lock( _writeToFileSync )
  264. {
  265. Directory.CreateDirectory( Path.Combine( Config.Current.DataPath, Settings.TranslationDirectory ) );
  266. Directory.CreateDirectory( Path.GetDirectoryName( Path.Combine( Config.Current.DataPath, Settings.OutputFile ) ) );
  267. var mainTranslationFile = Settings.AutoTranslationsFilePath.Replace( "/", "\\" );
  268. LoadTranslationsInFile( mainTranslationFile );
  269. foreach( var fullFileName in GetTranslationFiles().Reverse().Except( new[] { mainTranslationFile } ) )
  270. {
  271. LoadTranslationsInFile( fullFileName );
  272. }
  273. }
  274. if( Settings.EnableTextureTranslation || Settings.EnableTextureDumping )
  275. {
  276. _translatedImages.Clear();
  277. _untranslatedImages.Clear();
  278. Directory.CreateDirectory( Path.Combine( Config.Current.DataPath, Settings.TextureDirectory ) );
  279. foreach( var fullFileName in GetTextureFiles() )
  280. {
  281. RegisterImageFromFile( fullFileName );
  282. }
  283. }
  284. }
  285. catch( Exception e )
  286. {
  287. Logger.Current.Error( e, "An error occurred while loading translations." );
  288. }
  289. }
  290. private void RegisterImageFromFile( string fullFileName )
  291. {
  292. var fileName = Path.GetFileNameWithoutExtension( fullFileName );
  293. var startHash = fileName.LastIndexOf( "[" );
  294. var endHash = fileName.LastIndexOf( "]" );
  295. if( endHash > -1 && startHash > -1 && endHash > startHash )
  296. {
  297. var takeFrom = startHash + 1;
  298. // load based on whether or not the key is image hashed
  299. var parts = fileName.Substring( takeFrom, endHash - takeFrom ).Split( '-' );
  300. string key;
  301. string originalHash;
  302. if( parts.Length == 1 )
  303. {
  304. key = parts[ 0 ];
  305. originalHash = parts[ 0 ];
  306. }
  307. else if( parts.Length == 2 )
  308. {
  309. key = parts[ 0 ];
  310. originalHash = parts[ 1 ];
  311. }
  312. else
  313. {
  314. Logger.Current.Warn( $"Image not loaded (unknown hash): {fullFileName}." );
  315. return;
  316. }
  317. var data = File.ReadAllBytes( fullFileName );
  318. var currentHash = HashHelper.Compute( data );
  319. var isModified = StringComparer.InvariantCultureIgnoreCase.Compare( originalHash, currentHash ) != 0;
  320. // only load images that someone has modified!
  321. if( Settings.LoadUnmodifiedTextures || isModified )
  322. {
  323. RegisterTranslatedImage( key, data );
  324. Logger.Current.Debug( $"Image loaded: {fullFileName}." );
  325. }
  326. else
  327. {
  328. RegisterUntranslatedImage( key );
  329. Logger.Current.Warn( $"Image not loaded (unmodified): {fullFileName}." );
  330. }
  331. //if( Settings.DeleteUnmodifiedTextures && !isModified )
  332. //{
  333. // try
  334. // {
  335. // File.Delete( fullFileName );
  336. // Logger.Current.Warn( $"Image deleted (unmodified): {fullFileName}." );
  337. // }
  338. // catch( Exception e )
  339. // {
  340. // Logger.Current.Warn( e, $"An error occurred while trying to delete unmodified image: {fullFileName}." );
  341. // }
  342. //}
  343. }
  344. else
  345. {
  346. Logger.Current.Warn( $"Image not loaded (no hash): {fullFileName}." );
  347. }
  348. }
  349. private void RegisterImageFromData( string textureName, string key, byte[] data )
  350. {
  351. var name = textureName.SanitizeForFileSystem();
  352. var root = Path.Combine( Config.Current.DataPath, Settings.TextureDirectory );
  353. var originalHash = HashHelper.Compute( data );
  354. // allow hash and key to be the same; only store one of them then!
  355. string fileName;
  356. if( key == originalHash )
  357. {
  358. fileName = name + " [" + key + "].png";
  359. }
  360. else
  361. {
  362. fileName = name + " [" + key + "-" + originalHash + "].png";
  363. }
  364. var fullName = Path.Combine( root, fileName );
  365. File.WriteAllBytes( fullName, data );
  366. Logger.Current.Info( "Dumped texture file: " + fileName );
  367. if( Settings.LoadUnmodifiedTextures )
  368. {
  369. RegisterTranslatedImage( key, data );
  370. }
  371. else
  372. {
  373. RegisterUntranslatedImage( key );
  374. }
  375. }
  376. private void RegisterTranslatedImage( string key, byte[] data )
  377. {
  378. _translatedImages[ key ] = data;
  379. }
  380. private void RegisterUntranslatedImage( string key )
  381. {
  382. _untranslatedImages.Add( key );
  383. }
  384. private void LoadTranslationsInFile( string fullFileName )
  385. {
  386. if( File.Exists( fullFileName ) )
  387. {
  388. Logger.Current.Debug( $"Loading texts: {fullFileName}." );
  389. string[] translations = File.ReadAllLines( fullFileName, Encoding.UTF8 );
  390. foreach( string translation in translations )
  391. {
  392. for( int i = 0 ; i < TranslationSplitters.Length ; i++ )
  393. {
  394. var splitter = TranslationSplitters[ i ];
  395. string[] kvp = translation.Split( splitter, StringSplitOptions.None );
  396. if( kvp.Length == 2 )
  397. {
  398. string key = TextHelper.Decode( kvp[ 0 ].TrimIfConfigured() );
  399. string value = TextHelper.Decode( kvp[ 1 ].TrimIfConfigured() );
  400. if( !string.IsNullOrEmpty( key ) && !string.IsNullOrEmpty( value ) && IsTranslatable( key ) )
  401. {
  402. AddTranslation( key, value );
  403. break;
  404. }
  405. }
  406. }
  407. }
  408. }
  409. }
  410. private void LoadStaticTranslations()
  411. {
  412. if( Settings.UseStaticTranslations && Settings.FromLanguage == Settings.DefaultFromLanguage && Settings.Language == Settings.DefaultLanguage )
  413. {
  414. var tab = new char[] { '\t' };
  415. var equals = new char[] { '=' };
  416. var splitters = new char[][] { tab, equals };
  417. // load static translations from previous titles
  418. string[] translations = Properties.Resources.StaticTranslations.Split( new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries );
  419. foreach( string translation in translations )
  420. {
  421. for( int i = 0 ; i < splitters.Length ; i++ )
  422. {
  423. var splitter = splitters[ i ];
  424. string[] kvp = translation.Split( splitter, StringSplitOptions.None );
  425. if( kvp.Length >= 2 )
  426. {
  427. string key = TextHelper.Decode( kvp[ 0 ].TrimIfConfigured() );
  428. string value = TextHelper.Decode( kvp[ 1 ].TrimIfConfigured() );
  429. if( !string.IsNullOrEmpty( key ) && !string.IsNullOrEmpty( value ) )
  430. {
  431. _staticTranslations[ key ] = value;
  432. break;
  433. }
  434. }
  435. }
  436. }
  437. }
  438. }
  439. private TranslationJob GetOrCreateTranslationJobFor( object ui, TranslationKey key, TranslationContext context )
  440. {
  441. var lookupKey = key.GetDictionaryLookupKey();
  442. if( _unstartedJobs.TryGetValue( lookupKey, out TranslationJob unstartedJob ) )
  443. {
  444. unstartedJob.Associate( context );
  445. return unstartedJob;
  446. }
  447. if( _ongoingJobs.TryGetValue( lookupKey, out TranslationJob ongoingJob ) )
  448. {
  449. ongoingJob.Associate( context );
  450. return ongoingJob;
  451. }
  452. foreach( var completedJob in _completedJobs )
  453. {
  454. if( completedJob.Key.GetDictionaryLookupKey() == lookupKey )
  455. {
  456. completedJob.Associate( context );
  457. return completedJob;
  458. }
  459. }
  460. Logger.Current.Debug( "Queued translation for: " + lookupKey );
  461. ongoingJob = new TranslationJob( key );
  462. if( ui != null )
  463. {
  464. ongoingJob.OriginalSources.Add( ui );
  465. }
  466. ongoingJob.Associate( context );
  467. _unstartedJobs.Add( lookupKey, ongoingJob );
  468. CheckStaggerText( lookupKey );
  469. CheckConsecutiveFrames();
  470. CheckConsecutiveSeconds();
  471. CheckThresholds();
  472. return ongoingJob;
  473. }
  474. private void CheckConsecutiveSeconds()
  475. {
  476. var currentSecond = (int)Time.time;
  477. var lastSecond = currentSecond - 1;
  478. if( lastSecond == _secondForQueuedTranslation )
  479. {
  480. // we also queued something last frame, lets increment our counter
  481. _consecutiveSecondsTranslated++;
  482. if( _consecutiveSecondsTranslated > Settings.MaximumConsecutiveSecondsTranslated )
  483. {
  484. // Shutdown, this wont be tolerated!!!
  485. _unstartedJobs.Clear();
  486. _completedJobs.Clear();
  487. _ongoingJobs.Clear();
  488. Settings.IsShutdown = true;
  489. Logger.Current.Error( $"SPAM DETECTED: Translations were queued every second for more than {Settings.MaximumConsecutiveSecondsTranslated} consecutive seconds. Shutting down plugin." );
  490. }
  491. }
  492. else if( currentSecond == _secondForQueuedTranslation )
  493. {
  494. // do nothing, there may be multiple translations per frame, that wont increase this counter
  495. }
  496. else
  497. {
  498. // but if multiple Update frames has passed, we will reset the counter
  499. _consecutiveSecondsTranslated = 0;
  500. }
  501. _secondForQueuedTranslation = currentSecond;
  502. }
  503. private void CheckConsecutiveFrames()
  504. {
  505. var currentFrame = Time.frameCount;
  506. var lastFrame = currentFrame - 1;
  507. if( lastFrame == _frameForLastQueuedTranslation )
  508. {
  509. // we also queued something last frame, lets increment our counter
  510. _consecutiveFramesTranslated++;
  511. if( _consecutiveFramesTranslated > Settings.MaximumConsecutiveFramesTranslated )
  512. {
  513. // Shutdown, this wont be tolerated!!!
  514. _unstartedJobs.Clear();
  515. _completedJobs.Clear();
  516. _ongoingJobs.Clear();
  517. Settings.IsShutdown = true;
  518. Logger.Current.Error( $"SPAM DETECTED: Translations were queued every frame for more than {Settings.MaximumConsecutiveFramesTranslated} consecutive frames. Shutting down plugin." );
  519. }
  520. }
  521. else if( currentFrame == _frameForLastQueuedTranslation )
  522. {
  523. // do nothing, there may be multiple translations per frame, that wont increase this counter
  524. }
  525. else if( _consecutiveFramesTranslated > 0 )
  526. {
  527. // but if multiple Update frames has passed, we will reset the counter
  528. _consecutiveFramesTranslated--;
  529. }
  530. _frameForLastQueuedTranslation = currentFrame;
  531. }
  532. public void PeriodicResetFrameCheck()
  533. {
  534. var currentSecond = (int)Time.time;
  535. if( currentSecond % 100 == 0 )
  536. {
  537. _consecutiveFramesTranslated = 0;
  538. }
  539. }
  540. private void CheckStaggerText( string untranslatedText )
  541. {
  542. bool wasProblematic = false;
  543. for( int i = 0 ; i < _previouslyQueuedText.Length ; i++ )
  544. {
  545. var previouslyQueuedText = _previouslyQueuedText[ i ];
  546. if( previouslyQueuedText != null )
  547. {
  548. if( untranslatedText.RemindsOf( previouslyQueuedText ) )
  549. {
  550. wasProblematic = true;
  551. break;
  552. }
  553. }
  554. }
  555. if( wasProblematic )
  556. {
  557. _concurrentStaggers++;
  558. if( _concurrentStaggers > Settings.MaximumStaggers )
  559. {
  560. _unstartedJobs.Clear();
  561. _completedJobs.Clear();
  562. _ongoingJobs.Clear();
  563. Settings.IsShutdown = true;
  564. Logger.Current.Error( $"SPAM DETECTED: Text that is 'scrolling in' is being translated. Disable that feature. Shutting down plugin." );
  565. }
  566. }
  567. else
  568. {
  569. _concurrentStaggers = 0;
  570. }
  571. _previouslyQueuedText[ _staggerTextCursor % _previouslyQueuedText.Length ] = untranslatedText;
  572. _staggerTextCursor++;
  573. }
  574. private void CheckThresholds()
  575. {
  576. if( _unstartedJobs.Count > Settings.MaxUnstartedJobs )
  577. {
  578. _unstartedJobs.Clear();
  579. _completedJobs.Clear();
  580. _ongoingJobs.Clear();
  581. Settings.IsShutdown = true;
  582. Logger.Current.Error( $"SPAM DETECTED: More than {Settings.MaxUnstartedJobs} queued for translations due to unknown reasons. Shutting down plugin." );
  583. }
  584. var previousIdx = ( (int)( Time.time - Time.deltaTime ) ) % Settings.TranslationQueueWatchWindow;
  585. var newIdx = ( (int)Time.time ) % Settings.TranslationQueueWatchWindow;
  586. if( previousIdx != newIdx )
  587. {
  588. _currentTranslationsQueuedPerSecondRollingWindow[ newIdx ] = 0;
  589. }
  590. _currentTranslationsQueuedPerSecondRollingWindow[ newIdx ]++;
  591. var translationsInWindow = _currentTranslationsQueuedPerSecondRollingWindow.Sum();
  592. _translationsQueuedPerSecond = (float)translationsInWindow / Settings.TranslationQueueWatchWindow;
  593. if( _translationsQueuedPerSecond > Settings.MaxTranslationsQueuedPerSecond )
  594. {
  595. if( !_timeExceededThreshold.HasValue )
  596. {
  597. _timeExceededThreshold = Time.time;
  598. }
  599. if( Time.time - _timeExceededThreshold.Value > Settings.MaxSecondsAboveTranslationThreshold )
  600. {
  601. _unstartedJobs.Clear();
  602. _completedJobs.Clear();
  603. _ongoingJobs.Clear();
  604. Settings.IsShutdown = true;
  605. Logger.Current.Error( $"SPAM DETECTED: More than {Settings.MaxTranslationsQueuedPerSecond} translations per seconds queued for a {Settings.MaxSecondsAboveTranslationThreshold} second period. Shutting down plugin." );
  606. }
  607. }
  608. else
  609. {
  610. _timeExceededThreshold = null;
  611. }
  612. }
  613. private void IncrementBatchOperations()
  614. {
  615. _batchOperationSecondCounter += Time.deltaTime;
  616. if( _batchOperationSecondCounter > Settings.IncreaseBatchOperationsEvery )
  617. {
  618. if( _availableBatchOperations < Settings.MaxAvailableBatchOperations )
  619. {
  620. _availableBatchOperations++;
  621. }
  622. _batchOperationSecondCounter = 0;
  623. }
  624. }
  625. private void ResetThresholdTimerIfRequired()
  626. {
  627. var previousIdx = ( (int)( Time.time - Time.deltaTime ) ) % Settings.TranslationQueueWatchWindow;
  628. var newIdx = ( (int)Time.time ) % Settings.TranslationQueueWatchWindow;
  629. if( previousIdx != newIdx )
  630. {
  631. _currentTranslationsQueuedPerSecondRollingWindow[ newIdx ] = 0;
  632. }
  633. var translationsInWindow = _currentTranslationsQueuedPerSecondRollingWindow.Sum();
  634. _translationsQueuedPerSecond = (float)translationsInWindow / Settings.TranslationQueueWatchWindow;
  635. if( _translationsQueuedPerSecond <= Settings.MaxTranslationsQueuedPerSecond )
  636. {
  637. _timeExceededThreshold = null;
  638. }
  639. }
  640. private bool IsImageRegistered( string key )
  641. {
  642. return _translatedImages.ContainsKey( key ) || _untranslatedImages.Contains( key );
  643. }
  644. private bool TryGetTranslatedImage( string key, out byte[] data )
  645. {
  646. return _translatedImages.TryGetValue( key, out data );
  647. }
  648. private void AddTranslation( string key, string value )
  649. {
  650. _translations[ key ] = value;
  651. _reverseTranslations[ value ] = key;
  652. }
  653. private void AddTranslation( TranslationKey key, string value )
  654. {
  655. var lookup = key.GetDictionaryLookupKey();
  656. _translations[ lookup ] = value;
  657. _reverseTranslations[ value ] = lookup;
  658. }
  659. private void QueueNewUntranslatedForClipboard( TranslationKey key )
  660. {
  661. if( Settings.CopyToClipboard && Features.SupportsClipboard )
  662. {
  663. if( !_textsToCopyToClipboard.Contains( key.RelevantText ) )
  664. {
  665. _textsToCopyToClipboard.Add( key.RelevantText );
  666. _textsToCopyToClipboardOrdered.Add( key.RelevantText );
  667. _clipboardUpdated = Time.realtimeSinceStartup;
  668. }
  669. }
  670. }
  671. private void QueueNewUntranslatedForDisk( TranslationKey key )
  672. {
  673. _newUntranslated.Add( key.GetDictionaryLookupKey() );
  674. }
  675. private void QueueNewTranslationForDisk( TranslationKey key, string value )
  676. {
  677. lock( _writeToFileSync )
  678. {
  679. _newTranslations[ key.GetDictionaryLookupKey() ] = value;
  680. }
  681. }
  682. private void QueueNewTranslationForDisk( string key, string value )
  683. {
  684. lock( _writeToFileSync )
  685. {
  686. _newTranslations[ key ] = value;
  687. }
  688. }
  689. private bool TryGetTranslation( TranslationKey key, out string value )
  690. {
  691. return TryGetTranslation( key.GetDictionaryLookupKey(), out value );
  692. }
  693. private bool TryGetTranslation( string key, out string value )
  694. {
  695. var result = _translations.TryGetValue( key, out value );
  696. if( result )
  697. {
  698. return result;
  699. }
  700. else if( _staticTranslations.Count > 0 )
  701. {
  702. if( _staticTranslations.TryGetValue( key, out value ) )
  703. {
  704. QueueNewTranslationForDisk( key, value );
  705. AddTranslation( key, value );
  706. return true;
  707. }
  708. }
  709. return result;
  710. }
  711. public bool TryGetReverseTranslation( string value, out string key )
  712. {
  713. return _reverseTranslations.TryGetValue( value, out key );
  714. }
  715. public string Hook_TextChanged_WithResult( object ui, string text )
  716. {
  717. if( !ui.IsKnownTextType() ) return null;
  718. if( _textHooksEnabled && !_temporarilyDisabled )
  719. {
  720. return TranslateOrQueueWebJob( ui, text, false );
  721. }
  722. return null;
  723. }
  724. public string ExternalHook_TextChanged_WithResult( object ui, string text )
  725. {
  726. if( !ui.IsKnownTextType() ) return null;
  727. if( _textHooksEnabled && !_temporarilyDisabled )
  728. {
  729. return TranslateOrQueueWebJob( ui, text, true );
  730. }
  731. return null;
  732. }
  733. public void Hook_TextChanged( object ui )
  734. {
  735. if( _textHooksEnabled && !_temporarilyDisabled )
  736. {
  737. TranslateOrQueueWebJob( ui, null, false );
  738. }
  739. }
  740. public void Hook_ImageChangedOnComponent( object source, Texture2D texture = null, bool isPrefixHooked = false )
  741. {
  742. if( !_imageHooksEnabled ) return;
  743. if( !source.IsKnownImageType() ) return;
  744. HandleImage( source, texture, isPrefixHooked );
  745. }
  746. public void Hook_ImageChanged( Texture2D texture, bool isPrefixHooked = false )
  747. {
  748. if( !_imageHooksEnabled ) return;
  749. if( texture == null ) return;
  750. HandleImage( null, texture, isPrefixHooked );
  751. }
  752. private void SetTranslatedText( object ui, string translatedText, TextTranslationInfo info )
  753. {
  754. info?.SetTranslatedText( translatedText );
  755. if( _isInTranslatedMode )
  756. {
  757. SetText( ui, translatedText, true, info );
  758. }
  759. }
  760. public void Hook_HandleComponent( object ui )
  761. {
  762. if( _hasOverrideFont )
  763. {
  764. var info = ui.GetTextTranslationInfo();
  765. if( _overrideFont )
  766. {
  767. info?.ChangeFont( ui );
  768. }
  769. else
  770. {
  771. info?.UnchangeFont( ui );
  772. }
  773. }
  774. if( Settings.ForceUIResizing )
  775. {
  776. var info = ui.GetTextTranslationInfo();
  777. if( info?.IsCurrentlySettingText == false )
  778. {
  779. // force UI resizing is highly problematic for NGUI because text should somehow
  780. // be set after changing "resize" properties... brilliant stuff
  781. if( ui.GetType() != ClrTypes.UILabel )
  782. {
  783. info?.ResizeUI( ui );
  784. }
  785. }
  786. }
  787. }
  788. /// <summary>
  789. /// Sets the text of a UI text, while ensuring this will not fire a text changed event.
  790. /// </summary>
  791. private void SetText( object ui, string text, bool isTranslated, TextTranslationInfo info )
  792. {
  793. if( !info?.IsCurrentlySettingText ?? true )
  794. {
  795. try
  796. {
  797. _textHooksEnabled = false;
  798. if( info != null )
  799. {
  800. info.IsCurrentlySettingText = true;
  801. }
  802. if( Settings.EnableUIResizing || Settings.ForceUIResizing )
  803. {
  804. if( isTranslated || Settings.ForceUIResizing )
  805. {
  806. info?.ResizeUI( ui );
  807. }
  808. else
  809. {
  810. info?.UnresizeUI( ui );
  811. }
  812. }
  813. // NGUI only behaves if you set the text after the resize behaviour
  814. ui.SetText( text );
  815. info?.ResetScrollIn( ui );
  816. }
  817. catch( TargetInvocationException )
  818. {
  819. // might happen with NGUI
  820. }
  821. catch( NullReferenceException )
  822. {
  823. // This is likely happened due to a scene change.
  824. }
  825. catch( Exception e )
  826. {
  827. Logger.Current.Error( e, "An error occurred while setting text on a component." );
  828. }
  829. finally
  830. {
  831. _textHooksEnabled = true;
  832. if( info != null )
  833. {
  834. info.IsCurrentlySettingText = false;
  835. }
  836. }
  837. }
  838. }
  839. /// <summary>
  840. /// Determines if a text should be translated.
  841. /// </summary>
  842. private bool IsTranslatable( string str )
  843. {
  844. return _symbolCheck( str )
  845. && str.Length <= Settings.MaxCharactersPerTranslation
  846. && !_reverseTranslations.ContainsKey( str )
  847. && !Settings.IgnoreTextStartingWith.Any( x => str.StartsWithStrict( x ) );
  848. }
  849. private bool IsShortText( string str )
  850. {
  851. return str.Length <= ( Settings.MaxCharactersPerTranslation / 2 );
  852. }
  853. public bool ShouldTranslateImageComponent( object ui )
  854. {
  855. var component = ui as Component;
  856. if( component != null )
  857. {
  858. // dummy check
  859. var go = component.gameObject;
  860. var ignore = go.HasIgnoredName();
  861. if( ignore )
  862. {
  863. return false;
  864. }
  865. var behaviour = component as Behaviour;
  866. if( behaviour?.isActiveAndEnabled == false )
  867. {
  868. return false;
  869. }
  870. }
  871. return true;
  872. }
  873. public bool ShouldTranslateTextComponent( object ui, bool ignoreComponentState )
  874. {
  875. var component = ui as Component;
  876. if( component != null )
  877. {
  878. // dummy check
  879. var go = component.gameObject;
  880. var ignore = go.HasIgnoredName();
  881. if( ignore )
  882. {
  883. return false;
  884. }
  885. if( !ignoreComponentState )
  886. {
  887. var behaviour = component as Behaviour;
  888. if( behaviour?.isActiveAndEnabled == false )
  889. {
  890. return false;
  891. }
  892. }
  893. var inputField = component.gameObject.GetFirstComponentInSelfOrAncestor( ClrTypes.InputField )
  894. ?? component.gameObject.GetFirstComponentInSelfOrAncestor( ClrTypes.TMP_InputField );
  895. return inputField == null;
  896. }
  897. return true;
  898. }
  899. private string TranslateOrQueueWebJob( object ui, string text, bool ignoreComponentState )
  900. {
  901. var info = ui.GetTextTranslationInfo();
  902. if( _ongoingOperations.Contains( ui ) )
  903. {
  904. return TranslateImmediate( ui, text, info, ignoreComponentState );
  905. }
  906. var supportsStabilization = ui.SupportsStabilization();
  907. if( Settings.Delay == 0 || !supportsStabilization )
  908. {
  909. return TranslateOrQueueWebJobImmediate( ui, text, info, supportsStabilization, ignoreComponentState );
  910. }
  911. else
  912. {
  913. StartCoroutine(
  914. DelayForSeconds( Settings.Delay, () =>
  915. {
  916. TranslateOrQueueWebJobImmediate( ui, text, info, supportsStabilization, ignoreComponentState );
  917. } ) );
  918. }
  919. return null;
  920. }
  921. public static bool IsCurrentlySetting( TextTranslationInfo info )
  922. {
  923. if( info == null ) return false;
  924. return info.IsCurrentlySettingText;
  925. }
  926. private void HandleImage( object source, Texture2D texture, bool isPrefixHooked )
  927. {
  928. if( Settings.EnableTextureDumping )
  929. {
  930. try
  931. {
  932. DumpTexture( source, texture );
  933. }
  934. catch( Exception e )
  935. {
  936. Logger.Current.Error( e, "An error occurred while dumping texture." );
  937. }
  938. }
  939. if( Settings.EnableTextureTranslation )
  940. {
  941. try
  942. {
  943. TranslateTexture( source, texture, isPrefixHooked, false );
  944. }
  945. catch( Exception e )
  946. {
  947. Logger.Current.Error( e, "An error occurred while translating texture." );
  948. }
  949. }
  950. }
  951. private void TranslateTexture( object ui, bool forceReload )
  952. {
  953. if( ui is Texture2D texture2d )
  954. {
  955. TranslateTexture( null, texture2d, false, forceReload );
  956. }
  957. else
  958. {
  959. TranslateTexture( ui, null, false, forceReload );
  960. }
  961. }
  962. private void TranslateTexture( object source, Texture2D texture, bool isPrefixHooked, bool forceReload )
  963. {
  964. try
  965. {
  966. _imageHooksEnabled = false;
  967. texture = texture ?? source.GetTexture();
  968. if( texture == null ) return;
  969. var tti = texture.GetTextureTranslationInfo();
  970. var iti = source.GetImageTranslationInfo();
  971. var key = tti.GetKey( texture );
  972. if( string.IsNullOrEmpty( key ) ) return;
  973. if( TryGetTranslatedImage( key, out var newData ) )
  974. {
  975. if( _isInTranslatedMode )
  976. {
  977. // handle texture
  978. if( !tti.IsTranslated || forceReload )
  979. {
  980. try
  981. {
  982. texture.LoadImageEx( newData, tti.IsNonReadable( texture ) );
  983. }
  984. finally
  985. {
  986. tti.IsTranslated = true;
  987. }
  988. }
  989. // handle containing component
  990. if( iti != null )
  991. {
  992. if( !iti.IsTranslated || forceReload )
  993. {
  994. try
  995. {
  996. if( !isPrefixHooked )
  997. {
  998. source.SetAllDirtyEx();
  999. }
  1000. }
  1001. finally
  1002. {
  1003. iti.IsTranslated = true;
  1004. }
  1005. }
  1006. }
  1007. }
  1008. }
  1009. else
  1010. {
  1011. // if we cannot find the texture, and the texture is considered translated... hmmm someone has removed a file
  1012. // handle texture
  1013. var originalData = tti.GetOriginalData( texture );
  1014. if( originalData != null )
  1015. {
  1016. if( tti.IsTranslated )
  1017. {
  1018. try
  1019. {
  1020. texture.LoadImageEx( originalData, tti.IsNonReadable( texture ) );
  1021. }
  1022. finally
  1023. {
  1024. tti.IsTranslated = true;
  1025. }
  1026. }
  1027. // handle containing component
  1028. if( iti != null )
  1029. {
  1030. if( iti.IsTranslated )
  1031. {
  1032. try
  1033. {
  1034. if( !isPrefixHooked )
  1035. {
  1036. source.SetAllDirtyEx();
  1037. }
  1038. }
  1039. finally
  1040. {
  1041. iti.IsTranslated = true;
  1042. }
  1043. }
  1044. }
  1045. }
  1046. }
  1047. if( !_isInTranslatedMode )
  1048. {
  1049. var originalData = tti.GetOriginalData( texture );
  1050. if( originalData != null )
  1051. {
  1052. // handle texture
  1053. if( tti.IsTranslated )
  1054. {
  1055. try
  1056. {
  1057. texture.LoadImageEx( originalData, tti.IsNonReadable( texture ) );
  1058. }
  1059. finally
  1060. {
  1061. tti.IsTranslated = false;
  1062. }
  1063. }
  1064. // handle containing component
  1065. if( iti != null )
  1066. {
  1067. if( iti.IsTranslated )
  1068. {
  1069. try
  1070. {
  1071. if( !isPrefixHooked )
  1072. {
  1073. source.SetAllDirtyEx();
  1074. }
  1075. }
  1076. finally
  1077. {
  1078. iti.IsTranslated = false;
  1079. }
  1080. }
  1081. }
  1082. }
  1083. }
  1084. }
  1085. finally
  1086. {
  1087. _imageHooksEnabled = true;
  1088. }
  1089. }
  1090. private void DumpTexture( object source, Texture2D texture )
  1091. {
  1092. try
  1093. {
  1094. _imageHooksEnabled = false;
  1095. texture = texture ?? source.GetTexture();
  1096. if( texture == null ) return;
  1097. var info = texture.GetTextureTranslationInfo();
  1098. if( info.HasDumpedAlternativeTexture ) return;
  1099. try
  1100. {
  1101. if( ShouldTranslate( texture ) )
  1102. {
  1103. var key = info.GetKey( texture );
  1104. if( string.IsNullOrEmpty( key ) ) return;
  1105. if( !IsImageRegistered( key ) )
  1106. {
  1107. var name = texture.GetTextureName();
  1108. //var format = "[" + texture.format.ToString() + "] ";
  1109. var originalData = info.GetOrCreateOriginalData( texture );
  1110. RegisterImageFromData( name, key, originalData );
  1111. }
  1112. }
  1113. }
  1114. finally
  1115. {
  1116. info.HasDumpedAlternativeTexture = true;
  1117. }
  1118. }
  1119. finally
  1120. {
  1121. _imageHooksEnabled = true;
  1122. }
  1123. }
  1124. private bool ShouldTranslate( Texture2D texture )
  1125. {
  1126. // convert to int so engine versions that does not have specific enums still work
  1127. var format = (int)texture.format;
  1128. // 1 = Alpha8
  1129. // 9 = R16
  1130. // 63 = R8
  1131. return format != 1
  1132. && format != 9
  1133. && format != 63;
  1134. }
  1135. private string TranslateImmediate( object ui, string text, TextTranslationInfo info, bool ignoreComponentState )
  1136. {
  1137. // Get the trimmed text
  1138. text = ( text ?? ui.GetText() ).TrimIfConfigured();
  1139. if( !string.IsNullOrEmpty( text ) && IsTranslatable( text ) && ShouldTranslateTextComponent( ui, ignoreComponentState ) && !IsCurrentlySetting( info ) )
  1140. {
  1141. info?.Reset( text );
  1142. var textKey = new TranslationKey( ui, text, ui.IsSpammingComponent(), false );
  1143. // if we already have translation loaded in our _translatios dictionary, simply load it and set text
  1144. string translation;
  1145. if( TryGetTranslation( textKey, out translation ) )
  1146. {
  1147. if( !string.IsNullOrEmpty( translation ) )
  1148. {
  1149. SetTranslatedText( ui, textKey.Untemplate( translation ), info );
  1150. return translation;
  1151. }
  1152. }
  1153. }
  1154. return null;
  1155. }
  1156. /// <summary>
  1157. /// Translates the string of a UI text or queues it up to be translated
  1158. /// by the HTTP translation service.
  1159. /// </summary>
  1160. private string TranslateOrQueueWebJobImmediate( object ui, string text, TextTranslationInfo info, bool supportsStabilization, bool ignoreComponentState, TranslationContext context = null )
  1161. {
  1162. text = text ?? ui.GetText();
  1163. // make sure text exists
  1164. var originalText = text;
  1165. if( context == null )
  1166. {
  1167. // Get the trimmed text
  1168. text = text.TrimIfConfigured();
  1169. }
  1170. // Ensure that we actually want to translate this text and its owning UI element.
  1171. if( !string.IsNullOrEmpty( text ) && IsTranslatable( text ) && ShouldTranslateTextComponent( ui, ignoreComponentState ) && !IsCurrentlySetting( info ) )
  1172. {
  1173. //Logger.Current.Debug( "START: " + ui.GetType().Name + ": " + text );
  1174. info?.Reset( originalText );
  1175. var isSpammer = ui.IsSpammingComponent();
  1176. var textKey = new TranslationKey( ui, text, isSpammer, context != null );
  1177. // if we already have translation loaded in our _translatios dictionary, simply load it and set text
  1178. string translation;
  1179. if( TryGetTranslation( textKey, out translation ) )
  1180. {
  1181. QueueNewUntranslatedForClipboard( textKey );
  1182. if( !string.IsNullOrEmpty( translation ) )
  1183. {
  1184. if( context == null ) // never set text if operation is contextualized (only a part translation)
  1185. {
  1186. SetTranslatedText( ui, textKey.Untemplate( translation ), info );
  1187. }
  1188. return translation;
  1189. }
  1190. }
  1191. else
  1192. {
  1193. if( context == null && ui.SupportsRichText() )
  1194. {
  1195. var parser = UnityTextParsers.GetTextParserByGameEngine();
  1196. if( parser != null )
  1197. {
  1198. var result = parser.Parse( text );
  1199. if( result.HasRichSyntax )
  1200. {
  1201. var isWhitelisted = ui.IsWhitelistedForImmediateRichTextTranslation();
  1202. translation = TranslateOrQueueWebJobImmediateByParserResult( ui, result, isWhitelisted );
  1203. if( translation != null )
  1204. {
  1205. SetTranslatedText( ui, translation, info );
  1206. return translation;
  1207. }
  1208. else if( isWhitelisted )
  1209. {
  1210. return null;
  1211. }
  1212. }
  1213. }
  1214. }
  1215. if( supportsStabilization && context == null ) // never stabilize a text that is contextualized or that does not support stabilization
  1216. {
  1217. // if we dont know what text to translate it to, we need to figure it out.
  1218. // this might take a while, so add the UI text component to the ongoing operations
  1219. // list, so we dont start multiple operations for it, as its text might be constantly
  1220. // changing.
  1221. _ongoingOperations.Add( ui );
  1222. // start a coroutine, that will execute once the string of the UI text has stopped
  1223. // changing. For all texts except 'story' texts, this will add a delay for exactly
  1224. // 0.5s to the translation. This is barely noticable.
  1225. //
  1226. // on the other hand, for 'story' texts, this will take the time that it takes
  1227. // for the text to stop 'scrolling' in.
  1228. try
  1229. {
  1230. StartCoroutine(
  1231. WaitForTextStablization(
  1232. ui: ui,
  1233. delay: 1.0f, // 1 second to prevent '1 second tickers' from getting translated
  1234. maxTries: 60, // 50 tries, about 1 minute
  1235. currentTries: 0,
  1236. onMaxTriesExceeded: () =>
  1237. {
  1238. _ongoingOperations.Remove( ui );
  1239. },
  1240. onTextStabilized: stabilizedText =>
  1241. {
  1242. _ongoingOperations.Remove( ui );
  1243. originalText = stabilizedText;
  1244. stabilizedText = stabilizedText.TrimIfConfigured();
  1245. if( !string.IsNullOrEmpty( stabilizedText ) && IsTranslatable( stabilizedText ) )
  1246. {
  1247. var stabilizedTextKey = new TranslationKey( ui, stabilizedText, false );
  1248. QueueNewUntranslatedForClipboard( stabilizedTextKey );
  1249. info?.Reset( originalText );
  1250. // once the text has stabilized, attempt to look it up
  1251. if( TryGetTranslation( stabilizedTextKey, out translation ) )
  1252. {
  1253. if( !string.IsNullOrEmpty( translation ) )
  1254. {
  1255. // stabilized, no need to untemplate
  1256. SetTranslatedText( ui, translation, info );
  1257. }
  1258. }
  1259. else
  1260. {
  1261. if( context == null && ui.SupportsRichText() )
  1262. {
  1263. var parser = UnityTextParsers.GetTextParserByGameEngine();
  1264. if( parser != null )
  1265. {
  1266. var result = parser.Parse( stabilizedText );
  1267. if( result.HasRichSyntax )
  1268. {
  1269. var translatedText = TranslateOrQueueWebJobImmediateByParserResult( ui, result, true );
  1270. if( translatedText != null )
  1271. {
  1272. // stabilized, no need to untemplate
  1273. SetTranslatedText( ui, translatedText, info );
  1274. }
  1275. return;
  1276. }
  1277. }
  1278. }
  1279. // Lets try not to spam a service that might not be there...
  1280. if( _endpoint != null )
  1281. {
  1282. if( !Settings.IsShutdown )
  1283. {
  1284. var job = GetOrCreateTranslationJobFor( ui, stabilizedTextKey, context );
  1285. job.Components.Add( ui );
  1286. }
  1287. }
  1288. else
  1289. {
  1290. QueueNewUntranslatedForDisk( stabilizedTextKey );
  1291. }
  1292. }
  1293. }
  1294. } ) );
  1295. }
  1296. catch( Exception )
  1297. {
  1298. _ongoingOperations.Remove( ui );
  1299. }
  1300. }
  1301. else if( !isSpammer || ( isSpammer && IsShortText( text ) ) )
  1302. {
  1303. if( context != null )
  1304. {
  1305. // if there is a context, this is a part-translation, which means it is not a candidate for scrolling-in text
  1306. if( _endpoint != null )
  1307. {
  1308. if( !Settings.IsShutdown )
  1309. {
  1310. // once the text has stabilized, attempt to look it up
  1311. var job = GetOrCreateTranslationJobFor( ui, textKey, context );
  1312. }
  1313. }
  1314. else
  1315. {
  1316. QueueNewUntranslatedForDisk( textKey );
  1317. }
  1318. }
  1319. else
  1320. {
  1321. StartCoroutine(
  1322. WaitForTextStablization(
  1323. textKey: textKey,
  1324. delay: 1.0f,
  1325. onTextStabilized: () =>
  1326. {
  1327. // Lets try not to spam a service that might not be there...
  1328. if( _endpoint != null )
  1329. {
  1330. // once the text has stabilized, attempt to look it up
  1331. if( !Settings.IsShutdown )
  1332. {
  1333. if( !TryGetTranslation( textKey, out translation ) )
  1334. {
  1335. var job = GetOrCreateTranslationJobFor( ui, textKey, context );
  1336. }
  1337. }
  1338. }
  1339. else
  1340. {
  1341. QueueNewUntranslatedForDisk( textKey );
  1342. }
  1343. } ) );
  1344. }
  1345. }
  1346. }
  1347. }
  1348. return null;
  1349. }
  1350. private string TranslateOrQueueWebJobImmediateByParserResult( object ui, ParserResult result, bool allowStartJob )
  1351. {
  1352. Dictionary<string, string> translations = new Dictionary<string, string>();
  1353. // attempt to lookup ALL strings immediately; return result if possible; queue operations
  1354. foreach( var kvp in result.Arguments )
  1355. {
  1356. var key = kvp.Key;
  1357. var value = kvp.Value.TrimIfConfigured();
  1358. if( !string.IsNullOrEmpty( value ) && IsTranslatable( value ) )
  1359. {
  1360. string partTranslation;
  1361. if( TryGetTranslation( value, out partTranslation ) )
  1362. {
  1363. translations.Add( key, partTranslation );
  1364. }
  1365. else if( allowStartJob )
  1366. {
  1367. // incomplete, must start job
  1368. var context = new TranslationContext( ui, result );
  1369. TranslateOrQueueWebJobImmediate( ui, value, null, false, true, context );
  1370. }
  1371. }
  1372. else
  1373. {
  1374. // the value will do
  1375. translations.Add( key, value );
  1376. }
  1377. }
  1378. if( result.Arguments.Count == translations.Count )
  1379. {
  1380. return result.Untemplate( translations );
  1381. }
  1382. else
  1383. {
  1384. return null; // could not perform complete translation
  1385. }
  1386. }
  1387. /// <summary>
  1388. /// Utility method that allows me to wait to call an action, until
  1389. /// the text has stopped changing. This is important for 'story'
  1390. /// mode text, which 'scrolls' into place slowly.
  1391. /// </summary>
  1392. public IEnumerator WaitForTextStablization( object ui, float delay, int maxTries, int currentTries, Action<string> onTextStabilized, Action onMaxTriesExceeded )
  1393. {
  1394. yield return 0; // wait a single frame to allow any external plugins to complete their hooking logic
  1395. bool succeeded = false;
  1396. while( currentTries < maxTries ) // shortcircuit
  1397. {
  1398. var beforeText = ui.GetText();
  1399. yield return new WaitForSeconds( delay );
  1400. var afterText = ui.GetText();
  1401. //Logger.Current.Debug( "WAITING: " + ui.GetType().Name + ": " + afterText );
  1402. if( beforeText == afterText )
  1403. {
  1404. onTextStabilized( afterText );
  1405. succeeded = true;
  1406. break;
  1407. }
  1408. currentTries++;
  1409. }
  1410. if( !succeeded )
  1411. {
  1412. onMaxTriesExceeded();
  1413. }
  1414. }
  1415. /// <summary>
  1416. /// Utility method that allows me to wait to call an action, until
  1417. /// the text has stopped changing. This is important for 'story'
  1418. /// mode text, which 'scrolls' into place slowly. This version is
  1419. /// for global text, where the component cannot tell us if the text
  1420. /// has changed itself.
  1421. /// </summary>
  1422. public IEnumerator WaitForTextStablization( TranslationKey textKey, float delay, Action onTextStabilized, Action onFailed = null )
  1423. {
  1424. var text = textKey.GetDictionaryLookupKey();
  1425. if( !_immediatelyTranslating.Contains( text ) )
  1426. {
  1427. _immediatelyTranslating.Add( text );
  1428. try
  1429. {
  1430. yield return new WaitForSeconds( delay );
  1431. bool succeeded = true;
  1432. foreach( var otherImmediatelyTranslating in _immediatelyTranslating )
  1433. {
  1434. if( text != otherImmediatelyTranslating )
  1435. {
  1436. if( text.RemindsOf( otherImmediatelyTranslating ) )
  1437. {
  1438. succeeded = false;
  1439. break;
  1440. }
  1441. }
  1442. }
  1443. if( succeeded )
  1444. {
  1445. onTextStabilized();
  1446. }
  1447. else
  1448. {
  1449. onFailed?.Invoke();
  1450. }
  1451. }
  1452. finally
  1453. {
  1454. _immediatelyTranslating.Remove( text );
  1455. }
  1456. }
  1457. }
  1458. public IEnumerator DelayForSeconds( float delay, Action onContinue )
  1459. {
  1460. yield return new WaitForSeconds( delay );
  1461. onContinue();
  1462. }
  1463. public void Awake()
  1464. {
  1465. if( !_initialized )
  1466. {
  1467. _initialized = true;
  1468. try
  1469. {
  1470. Initialize();
  1471. ManualHook();
  1472. }
  1473. catch( Exception e )
  1474. {
  1475. Logger.Current.Error( e, "An unexpected error occurred during plugin initialization." );
  1476. }
  1477. }
  1478. }
  1479. public void Start()
  1480. {
  1481. try
  1482. {
  1483. HooksSetup.InstallOverrideTextHooks();
  1484. }
  1485. catch( Exception e )
  1486. {
  1487. Logger.Current.Error( e, "An unexpected error occurred during plugin start." );
  1488. }
  1489. }
  1490. public void Update()
  1491. {
  1492. try
  1493. {
  1494. if( _endpoint != null )
  1495. {
  1496. _endpoint.OnUpdate();
  1497. }
  1498. if( Features.SupportsClipboard )
  1499. {
  1500. CopyToClipboard();
  1501. }
  1502. if( !Settings.IsShutdown )
  1503. {
  1504. PeriodicResetFrameCheck();
  1505. IncrementBatchOperations();
  1506. ResetThresholdTimerIfRequired();
  1507. KickoffTranslations();
  1508. FinishTranslations();
  1509. if( ClrTypes.AdvEngine != null && _nextAdvUpdate.HasValue && Time.time > _nextAdvUpdate )
  1510. {
  1511. _nextAdvUpdate = null;
  1512. UpdateUtageText();
  1513. }
  1514. }
  1515. if( Input.anyKey )
  1516. {
  1517. if( Settings.EnablePrintHierarchy && ( Input.GetKey( KeyCode.LeftAlt ) || Input.GetKey( KeyCode.RightAlt ) ) && Input.GetKeyDown( KeyCode.Y ) )
  1518. {
  1519. PrintObjects();
  1520. }
  1521. else if( ( Input.GetKey( KeyCode.LeftAlt ) || Input.GetKey( KeyCode.RightAlt ) ) && Input.GetKeyDown( KeyCode.T ) )
  1522. {
  1523. ToggleTranslation();
  1524. }
  1525. else if( ( Input.GetKey( KeyCode.LeftAlt ) || Input.GetKey( KeyCode.RightAlt ) ) && Input.GetKeyDown( KeyCode.F ) )
  1526. {
  1527. ToggleFont();
  1528. }
  1529. else if( ( Input.GetKey( KeyCode.LeftAlt ) || Input.GetKey( KeyCode.RightAlt ) ) && Input.GetKeyDown( KeyCode.D ) )
  1530. {
  1531. DumpUntranslated();
  1532. }
  1533. else if( ( Input.GetKey( KeyCode.LeftAlt ) || Input.GetKey( KeyCode.RightAlt ) ) && Input.GetKeyDown( KeyCode.R ) )
  1534. {
  1535. ReloadTranslations();
  1536. }
  1537. else if( ( Input.GetKey( KeyCode.LeftAlt ) || Input.GetKey( KeyCode.RightAlt ) ) && Input.GetKeyDown( KeyCode.U ) )
  1538. {
  1539. ManualHook();
  1540. }
  1541. }
  1542. }
  1543. catch( Exception e )
  1544. {
  1545. Logger.Current.Error( e, "An error occurred in Update callback. " );
  1546. }
  1547. }
  1548. // create this as a field instead of local var, to prevent new creation on EVERY game loop
  1549. private readonly List<string> _kickedOff = new List<string>();
  1550. private void KickoffTranslations()
  1551. {
  1552. if( _endpoint == null ) return;
  1553. if( Settings.EnableBatching && _endpoint.SupportsLineSplitting && !_batchLogicHasFailed && _unstartedJobs.Count > 1 && _availableBatchOperations > 0 )
  1554. {
  1555. while( _unstartedJobs.Count > 0 && _availableBatchOperations > 0 )
  1556. {
  1557. if( _endpoint.IsBusy ) break;
  1558. var kvps = _unstartedJobs.Take( Settings.BatchSize ).ToList();
  1559. var batch = new TranslationBatch();
  1560. foreach( var kvp in kvps )
  1561. {
  1562. var key = kvp.Key;
  1563. var job = kvp.Value;
  1564. _kickedOff.Add( key );
  1565. if( !job.AnyComponentsStillHasOriginalUntranslatedTextOrContextual() ) continue;
  1566. batch.Add( job );
  1567. _ongoingJobs[ key ] = job;
  1568. }
  1569. if( !batch.IsEmpty )
  1570. {
  1571. _availableBatchOperations--;
  1572. StartCoroutine( _endpoint.Translate( batch.GetFullTranslationKey(), Settings.FromLanguage, Settings.Language, translatedText => OnBatchTranslationCompleted( batch, translatedText ),
  1573. () => OnTranslationFailed( batch ) ) );
  1574. }
  1575. }
  1576. }
  1577. else
  1578. {
  1579. foreach( var kvp in _unstartedJobs )
  1580. {
  1581. if( _endpoint.IsBusy ) break;
  1582. var key = kvp.Key;
  1583. var job = kvp.Value;
  1584. _kickedOff.Add( key );
  1585. // lets see if the text should still be translated before kicking anything off
  1586. if( !job.AnyComponentsStillHasOriginalUntranslatedTextOrContextual() ) continue;
  1587. _ongoingJobs[ key ] = job;
  1588. StartCoroutine( _endpoint.Translate( job.Key.GetDictionaryLookupKey(), Settings.FromLanguage, Settings.Language, translatedText => OnSingleTranslationCompleted( job, translatedText ),
  1589. () => OnTranslationFailed( job ) ) );
  1590. }
  1591. }
  1592. for( int i = 0 ; i < _kickedOff.Count ; i++ )
  1593. {
  1594. _unstartedJobs.Remove( _kickedOff[ i ] );
  1595. }
  1596. _kickedOff.Clear();
  1597. }
  1598. public void OnBatchTranslationCompleted( TranslationBatch batch, string translatedTextBatch )
  1599. {
  1600. _consecutiveErrors = 0;
  1601. var succeeded = batch.MatchWithTranslations( translatedTextBatch );
  1602. if( succeeded )
  1603. {
  1604. foreach( var tracker in batch.Trackers )
  1605. {
  1606. Settings.TranslationCount++;
  1607. var job = tracker.Job;
  1608. var translatedText = tracker.RawTranslatedText;
  1609. if( !string.IsNullOrEmpty( translatedText ) )
  1610. {
  1611. if( Settings.ForceSplitTextAfterCharacters > 0 )
  1612. {
  1613. translatedText = translatedText.SplitToLines( Settings.ForceSplitTextAfterCharacters, '\n', ' ', ' ' );
  1614. }
  1615. job.TranslatedText = job.Key.RepairTemplate( translatedText );
  1616. QueueNewTranslationForDisk( job.Key, translatedText );
  1617. _completedJobs.Add( job );
  1618. }
  1619. AddTranslation( job.Key, job.TranslatedText );
  1620. job.State = TranslationJobState.Succeeded;
  1621. _ongoingJobs.Remove( job.Key.GetDictionaryLookupKey() );
  1622. }
  1623. }
  1624. else
  1625. {
  1626. // might as well re-add all translation jobs, and never do this again!
  1627. _batchLogicHasFailed = true;
  1628. foreach( var tracker in batch.Trackers )
  1629. {
  1630. Settings.TranslationCount++;
  1631. var key = tracker.Job.Key.GetDictionaryLookupKey();
  1632. if( !_unstartedJobs.ContainsKey( key ) )
  1633. {
  1634. _unstartedJobs[ key ] = tracker.Job;
  1635. }
  1636. _ongoingJobs.Remove( key );
  1637. }
  1638. Logger.Current.Error( "A batch operation failed. Disabling batching and restarting failed jobs." );
  1639. }
  1640. if( !Settings.IsShutdown )
  1641. {
  1642. if( Settings.TranslationCount > Settings.MaxTranslationsBeforeShutdown )
  1643. {
  1644. Settings.IsShutdown = true;
  1645. Logger.Current.Error( $"Maximum translations ({Settings.MaxTranslationsBeforeShutdown}) per session reached. Shutting plugin down." );
  1646. _unstartedJobs.Clear();
  1647. _completedJobs.Clear();
  1648. _ongoingJobs.Clear();
  1649. }
  1650. }
  1651. }
  1652. private void OnSingleTranslationCompleted( TranslationJob job, string translatedText )
  1653. {
  1654. Settings.TranslationCount++;
  1655. _consecutiveErrors = 0;
  1656. if( !string.IsNullOrEmpty( translatedText ) )
  1657. {
  1658. if( Settings.ForceSplitTextAfterCharacters > 0 )
  1659. {
  1660. translatedText = translatedText.SplitToLines( Settings.ForceSplitTextAfterCharacters, '\n', ' ', ' ' );
  1661. }
  1662. job.TranslatedText = job.Key.RepairTemplate( translatedText );
  1663. QueueNewTranslationForDisk( job.Key, translatedText );
  1664. _completedJobs.Add( job );
  1665. }
  1666. AddTranslation( job.Key, job.TranslatedText );
  1667. job.State = TranslationJobState.Succeeded;
  1668. _ongoingJobs.Remove( job.Key.GetDictionaryLookupKey() );
  1669. if( !Settings.IsShutdown )
  1670. {
  1671. if( Settings.TranslationCount > Settings.MaxTranslationsBeforeShutdown )
  1672. {
  1673. Settings.IsShutdown = true;
  1674. Logger.Current.Error( $"Maximum translations ({Settings.MaxTranslationsBeforeShutdown}) per session reached. Shutting plugin down." );
  1675. _unstartedJobs.Clear();
  1676. _completedJobs.Clear();
  1677. _ongoingJobs.Clear();
  1678. }
  1679. }
  1680. }
  1681. private void OnTranslationFailed( TranslationJob job )
  1682. {
  1683. Settings.TranslationCount++; // counts as a translation
  1684. _consecutiveErrors++;
  1685. job.State = TranslationJobState.Failed;
  1686. _ongoingJobs.Remove( job.Key.GetDictionaryLookupKey() );
  1687. if( !Settings.IsShutdown )
  1688. {
  1689. if( _consecutiveErrors >= Settings.MaxErrors )
  1690. {
  1691. Settings.IsShutdown = true;
  1692. Logger.Current.Error( $"{Settings.MaxErrors} or more consecutive errors occurred. Shutting down plugin." );
  1693. _unstartedJobs.Clear();
  1694. _completedJobs.Clear();
  1695. _ongoingJobs.Clear();
  1696. }
  1697. }
  1698. }
  1699. private void OnTranslationFailed( TranslationBatch batch )
  1700. {
  1701. Settings.TranslationCount++; // counts as a translation
  1702. _consecutiveErrors++;
  1703. foreach( var tracker in batch.Trackers )
  1704. {
  1705. tracker.Job.State = TranslationJobState.Failed;
  1706. _ongoingJobs.Remove( tracker.Job.Key.GetDictionaryLookupKey() );
  1707. }
  1708. if( !Settings.IsShutdown )
  1709. {
  1710. if( _consecutiveErrors >= Settings.MaxErrors )
  1711. {
  1712. Settings.IsShutdown = true;
  1713. Logger.Current.Error( $"{Settings.MaxErrors} or more consecutive errors occurred. Shutting down plugin." );
  1714. _unstartedJobs.Clear();
  1715. _completedJobs.Clear();
  1716. _ongoingJobs.Clear();
  1717. }
  1718. }
  1719. }
  1720. private void FinishTranslations()
  1721. {
  1722. if( _completedJobs.Count > 0 )
  1723. {
  1724. for( int i = _completedJobs.Count - 1 ; i >= 0 ; i-- )
  1725. {
  1726. var job = _completedJobs[ i ];
  1727. _completedJobs.RemoveAt( i );
  1728. foreach( var component in job.Components )
  1729. {
  1730. // update the original text, but only if it has not been chaanged already for some reason (could be other translator plugin or game itself)
  1731. try
  1732. {
  1733. var text = component.GetText().TrimIfConfigured();
  1734. if( text == job.Key.OriginalText )
  1735. {
  1736. var info = component.GetTextTranslationInfo();
  1737. SetTranslatedText( component, job.TranslatedText, info );
  1738. }
  1739. }
  1740. catch( NullReferenceException )
  1741. {
  1742. // might fail if compoent is no longer associated to game
  1743. }
  1744. }
  1745. // handle each context
  1746. foreach( var context in job.Contexts )
  1747. {
  1748. // are all jobs within this context completed? If so, we can set the text
  1749. if( context.Jobs.All( x => x.State == TranslationJobState.Succeeded ) )
  1750. {
  1751. try
  1752. {
  1753. var text = context.Component.GetText().TrimIfConfigured();
  1754. var result = context.Result;
  1755. Dictionary<string, string> translations = new Dictionary<string, string>();
  1756. var translatedText = TranslateOrQueueWebJobImmediateByParserResult( context.Component, result, false );
  1757. if( !string.IsNullOrEmpty( translatedText ) )
  1758. {
  1759. if( !_translations.ContainsKey( context.Result.OriginalText ) )
  1760. {
  1761. AddTranslation( context.Result.OriginalText, translatedText );
  1762. QueueNewTranslationForDisk( context.Result.OriginalText, translatedText );
  1763. }
  1764. if( text == result.OriginalText )
  1765. {
  1766. if( translatedText != null )
  1767. {
  1768. var info = context.Component.GetTextTranslationInfo();
  1769. SetTranslatedText( context.Component, translatedText, info );
  1770. }
  1771. }
  1772. }
  1773. }
  1774. catch( NullReferenceException )
  1775. {
  1776. }
  1777. }
  1778. }
  1779. // Utage support
  1780. if( ClrTypes.AdvEngine != null
  1781. && job.OriginalSources.Any( x => ClrTypes.AdvCommand.IsAssignableFrom( x.GetType() ) ) )
  1782. {
  1783. _nextAdvUpdate = Time.time + 0.5f;
  1784. }
  1785. }
  1786. }
  1787. }
  1788. private void UpdateUtageText()
  1789. {
  1790. // After an object is destroyed, an equality check with null will return true. The variable does not go to null, you can still call GetInstanceID() on it, but the "==" operator is overloaded and behaves as expected.
  1791. if( _advEngine == null || _advEngine?.gameObject == null )
  1792. {
  1793. _advEngine = (Component)GameObject.FindObjectOfType( Constants.ClrTypes.AdvEngine );
  1794. }
  1795. if( _advEngine != null )
  1796. {
  1797. AccessTools.Method( Constants.ClrTypes.AdvEngine, "ChangeLanguage" )?.Invoke( _advEngine, new object[ 0 ] );
  1798. }
  1799. }
  1800. private void ReloadTranslations()
  1801. {
  1802. LoadTranslations();
  1803. foreach( var kvp in ObjectExtensions.GetAllRegisteredObjects() )
  1804. {
  1805. var ui = kvp.Key;
  1806. try
  1807. {
  1808. if( ui is Component component )
  1809. {
  1810. if( component.gameObject?.activeSelf ?? false )
  1811. {
  1812. var tti = kvp.Value as TextTranslationInfo;
  1813. if( tti != null && !string.IsNullOrEmpty( tti.OriginalText ) )
  1814. {
  1815. var key = new TranslationKey( kvp.Key, tti.OriginalText, false );
  1816. if( TryGetTranslation( key, out string translatedText ) && !string.IsNullOrEmpty( translatedText ) )
  1817. {
  1818. SetTranslatedText( kvp.Key, translatedText, tti ); // no need to untemplatize the translated text
  1819. }
  1820. }
  1821. }
  1822. }
  1823. if( Settings.EnableTextureTranslation )
  1824. {
  1825. TranslateTexture( ui, true );
  1826. }
  1827. }
  1828. catch( Exception )
  1829. {
  1830. // not super pretty, no...
  1831. ObjectExtensions.Remove( ui );
  1832. }
  1833. }
  1834. }
  1835. private string CalculateDumpFileName()
  1836. {
  1837. int idx = 0;
  1838. string fileName = null;
  1839. do
  1840. {
  1841. idx++;
  1842. fileName = $"UntranslatedDump{idx}.txt";
  1843. }
  1844. while( File.Exists( fileName ) );
  1845. return fileName;
  1846. }
  1847. private void DumpUntranslated()
  1848. {
  1849. if( _newUntranslated.Count > 0 )
  1850. {
  1851. using( var stream = File.Open( CalculateDumpFileName(), FileMode.Append, FileAccess.Write ) )
  1852. using( var writer = new StreamWriter( stream, Encoding.UTF8 ) )
  1853. {
  1854. foreach( var untranslated in _newUntranslated )
  1855. {
  1856. writer.WriteLine( TextHelper.Encode( untranslated ) + '=' );
  1857. }
  1858. writer.Flush();
  1859. }
  1860. _newUntranslated.Clear();
  1861. }
  1862. }
  1863. private void ToggleFont()
  1864. {
  1865. if( _hasOverrideFont )
  1866. {
  1867. _overrideFont = !_overrideFont;
  1868. var objects = ObjectExtensions.GetAllRegisteredObjects();
  1869. Logger.Current.Info( $"Toggling fonts of {objects.Count} objects." );
  1870. if( _overrideFont )
  1871. {
  1872. // make sure we use the translated version of all texts
  1873. foreach( var kvp in objects )
  1874. {
  1875. var tti = kvp.Value as TextTranslationInfo;
  1876. if( tti != null )
  1877. {
  1878. var ui = kvp.Key;
  1879. try
  1880. {
  1881. if( ( ui as Component )?.gameObject?.activeSelf ?? false )
  1882. {
  1883. tti?.ChangeFont( ui );
  1884. }
  1885. }
  1886. catch( Exception )
  1887. {
  1888. // not super pretty, no...
  1889. ObjectExtensions.Remove( ui );
  1890. }
  1891. }
  1892. }
  1893. }
  1894. else
  1895. {
  1896. // make sure we use the original version of all texts
  1897. foreach( var kvp in objects )
  1898. {
  1899. var tti = kvp.Value as TextTranslationInfo;
  1900. var ui = kvp.Key;
  1901. try
  1902. {
  1903. if( ( ui as Component )?.gameObject?.activeSelf ?? false )
  1904. {
  1905. tti?.UnchangeFont( ui );
  1906. }
  1907. }
  1908. catch( Exception )
  1909. {
  1910. // not super pretty, no...
  1911. ObjectExtensions.Remove( ui );
  1912. }
  1913. }
  1914. }
  1915. }
  1916. }
  1917. private void ToggleTranslation()
  1918. {
  1919. _isInTranslatedMode = !_isInTranslatedMode;
  1920. var objects = ObjectExtensions.GetAllRegisteredObjects();
  1921. Logger.Current.Info( $"Toggling translations of {objects.Count} objects." );
  1922. // FIXME: Translate TEXTURES first??? Problem if texture is not related to a component!
  1923. if( _isInTranslatedMode )
  1924. {
  1925. // make sure we use the translated version of all texts
  1926. foreach( var kvp in objects )
  1927. {
  1928. var ui = kvp.Key;
  1929. try
  1930. {
  1931. if( ui is Component component )
  1932. {
  1933. if( component.gameObject?.activeSelf ?? false )
  1934. {
  1935. var tti = kvp.Value as TextTranslationInfo;
  1936. if( tti != null && tti.IsTranslated )
  1937. {
  1938. SetText( ui, tti.TranslatedText, true, tti );
  1939. }
  1940. }
  1941. }
  1942. if( Settings.EnableTextureTranslation && Settings.EnableTextureToggling )
  1943. {
  1944. TranslateTexture( ui, false );
  1945. }
  1946. }
  1947. catch( Exception )
  1948. {
  1949. // not super pretty, no...
  1950. ObjectExtensions.Remove( ui );
  1951. }
  1952. }
  1953. }
  1954. else
  1955. {
  1956. // make sure we use the original version of all texts
  1957. foreach( var kvp in objects )
  1958. {
  1959. var ui = kvp.Key;
  1960. try
  1961. {
  1962. if( ui is Component component )
  1963. {
  1964. if( component.gameObject?.activeSelf ?? false )
  1965. {
  1966. var tti = kvp.Value as TextTranslationInfo;
  1967. if( tti != null && tti.IsTranslated )
  1968. {
  1969. SetText( ui, tti.OriginalText, true, tti );
  1970. }
  1971. }
  1972. }
  1973. if( Settings.EnableTextureTranslation && Settings.EnableTextureToggling )
  1974. {
  1975. TranslateTexture( ui, false );
  1976. }
  1977. }
  1978. catch( Exception )
  1979. {
  1980. // not super pretty, no...
  1981. ObjectExtensions.Remove( ui );
  1982. }
  1983. }
  1984. }
  1985. }
  1986. private void CopyToClipboard()
  1987. {
  1988. if( Settings.CopyToClipboard
  1989. && _textsToCopyToClipboardOrdered.Count > 0
  1990. && Time.realtimeSinceStartup - _clipboardUpdated > Settings.ClipboardDebounceTime )
  1991. {
  1992. try
  1993. {
  1994. var builder = new StringBuilder();
  1995. foreach( var text in _textsToCopyToClipboardOrdered )
  1996. {
  1997. if( text.Length + builder.Length > Settings.MaxClipboardCopyCharacters ) break;
  1998. builder.AppendLine( text );
  1999. }
  2000. TextEditor editor = (TextEditor)GUIUtility.GetStateObject( typeof( TextEditor ), GUIUtility.keyboardControl );
  2001. editor.text = builder.ToString();
  2002. editor.SelectAll();
  2003. editor.Copy();
  2004. }
  2005. catch( Exception e )
  2006. {
  2007. Logger.Current.Error( e, "An error while copying text to clipboard." );
  2008. }
  2009. finally
  2010. {
  2011. _textsToCopyToClipboard.Clear();
  2012. _textsToCopyToClipboardOrdered.Clear();
  2013. }
  2014. }
  2015. }
  2016. private void PrintObjects()
  2017. {
  2018. using( var stream = File.Open( Path.Combine( Environment.CurrentDirectory, "hierarchy.txt" ), FileMode.Create ) )
  2019. using( var writer = new StreamWriter( stream ) )
  2020. {
  2021. foreach( var root in GetAllRoots() )
  2022. {
  2023. TraverseChildren( writer, root, "" );
  2024. }
  2025. writer.Flush();
  2026. }
  2027. }
  2028. private void ManualHook()
  2029. {
  2030. ManualHookForComponents();
  2031. ManualHookForTextures();
  2032. }
  2033. private void ManualHookForComponents()
  2034. {
  2035. foreach( var root in GetAllRoots() )
  2036. {
  2037. TraverseChildrenManualHook( root );
  2038. }
  2039. }
  2040. private void ManualHookForTextures()
  2041. {
  2042. if( Settings.EnableTextureScanOnSceneLoad && ( Settings.EnableTextureTranslation || Settings.EnableTextureDumping ) )
  2043. {
  2044. // scan all textures and update
  2045. var textures = Resources.FindObjectsOfTypeAll<Texture2D>();
  2046. foreach( var texture in textures )
  2047. {
  2048. Hook_ImageChanged( texture );
  2049. }
  2050. //// scan all components and set dirty
  2051. //var components = GameObject.FindObjectsOfType<Component>();
  2052. //foreach( var component in components )
  2053. //{
  2054. // component.SetAllDirtyEx();
  2055. //}
  2056. }
  2057. }
  2058. private IEnumerable<GameObject> GetAllRoots()
  2059. {
  2060. var objects = GameObject.FindObjectsOfType<GameObject>();
  2061. foreach( var obj in objects )
  2062. {
  2063. if( obj.transform != null && obj.transform.parent == null )
  2064. {
  2065. yield return obj;
  2066. }
  2067. }
  2068. }
  2069. private void TraverseChildren( StreamWriter writer, GameObject obj, string identation )
  2070. {
  2071. if( obj != null )
  2072. {
  2073. var layer = LayerMask.LayerToName( obj.layer );
  2074. var components = string.Join( ", ", obj.GetComponents<Component>().Select( x => x?.GetType()?.Name ).Where( x => x != null ).ToArray() );
  2075. var line = string.Format( "{0,-50} {1,100}",
  2076. identation + obj.name + " [" + layer + "]",
  2077. components );
  2078. writer.WriteLine( line );
  2079. if( obj.transform != null )
  2080. {
  2081. for( int i = 0 ; i < obj.transform.childCount ; i++ )
  2082. {
  2083. var child = obj.transform.GetChild( i );
  2084. TraverseChildren( writer, child.gameObject, identation + " " );
  2085. }
  2086. }
  2087. }
  2088. }
  2089. private void TraverseChildrenManualHook( GameObject obj )
  2090. {
  2091. if( obj != null )
  2092. {
  2093. var components = obj.GetComponents<Component>();
  2094. foreach( var component in components )
  2095. {
  2096. if( component.IsKnownTextType() )
  2097. {
  2098. Hook_TextChanged( component );
  2099. }
  2100. if( Settings.EnableTextureTranslation || Settings.EnableTextureDumping )
  2101. {
  2102. if( component.IsKnownImageType() )
  2103. {
  2104. Hook_ImageChangedOnComponent( component );
  2105. }
  2106. }
  2107. }
  2108. if( obj.transform != null )
  2109. {
  2110. for( int i = 0 ; i < obj.transform.childCount ; i++ )
  2111. {
  2112. var child = obj.transform.GetChild( i );
  2113. TraverseChildrenManualHook( child.gameObject );
  2114. }
  2115. }
  2116. }
  2117. }
  2118. public void DisableAutoTranslator()
  2119. {
  2120. _temporarilyDisabled = true;
  2121. }
  2122. public void EnableAutoTranslator()
  2123. {
  2124. _temporarilyDisabled = false;
  2125. }
  2126. }
  2127. }