AutoTranslationPlugin.cs 51 KB

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