AutoTranslationPlugin.cs 100 KB

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