Repository: chi-rei-den/Localizer Branch: master Commit: eddcaa798702 Files: 132 Total size: 322.4 KB Directory structure: gitextract_1rgzmmn8/ ├── .editorconfig ├── .gitattributes ├── .github/ │ └── workflows/ │ └── build.yml ├── .gitignore ├── .gitmodules ├── LICENSE ├── Localizer/ │ ├── Attributes/ │ │ ├── ModTranslationOwnerFieldAttribute.cs │ │ ├── ModTranslationPropAttribute.cs │ │ └── OperationTimingAttribute.cs │ ├── Configuration.cs │ ├── DataModel/ │ │ ├── Default/ │ │ │ ├── AttributeFile.cs │ │ │ ├── BaseEntry.cs │ │ │ ├── BasicBuffFile.cs │ │ │ ├── BasicItemFile.cs │ │ │ ├── BasicNPCFile.cs │ │ │ ├── BasicPrefixFile.cs │ │ │ ├── BasicProjectileFile.cs │ │ │ ├── CustomModTranslationFile.cs │ │ │ ├── ExportConfig.cs │ │ │ ├── File.cs │ │ │ ├── GitHubUpdateInfo.cs │ │ │ ├── LdstrFile.cs │ │ │ ├── LoadedModWrapper.cs │ │ │ ├── ModWrapper.cs │ │ │ ├── Package.cs │ │ │ ├── PackageGroup.cs │ │ │ └── PackageGroupState.cs │ │ ├── IEntry.cs │ │ ├── IExportConfig.cs │ │ ├── IFile.cs │ │ ├── IMod.cs │ │ ├── IPackage.cs │ │ ├── IPackageGroup.cs │ │ └── IUpdateInfo.cs │ ├── Disposable.cs │ ├── Enums/ │ │ ├── AutoImportType.cs │ │ ├── LogLevel.cs │ │ ├── OperationTiming.cs │ │ └── PackageType.cs │ ├── Helpers/ │ │ ├── Extensions.cs │ │ ├── Reflection.cs │ │ ├── UI.cs │ │ └── Utils.cs │ ├── Hooks.cs │ ├── Lang/ │ │ └── Lang.cs │ ├── Localizer.cs │ ├── Localizer.csproj │ ├── Localizer.csproj.DotSettings │ ├── LocalizerKernel.cs │ ├── LocalizerPlugin.cs │ ├── ModBrowser/ │ │ └── Patches.cs │ ├── Modules/ │ │ ├── DefaultNetworkModule.cs │ │ └── DefaultPackageModule.cs │ ├── Network/ │ │ ├── DownloadManager.cs │ │ ├── GitHubModUpdate.cs │ │ ├── IDownloadManagerService.cs │ │ ├── IPackageBrowserService.cs │ │ ├── IUpdateService.cs │ │ └── PackageBrowser.cs │ ├── Package/ │ │ ├── Export/ │ │ │ ├── BasicFileExport.cs │ │ │ ├── CustomModTranslationFileExport.cs │ │ │ ├── IFileExportService.cs │ │ │ ├── IPackageExportService.cs │ │ │ ├── LdstrFileExport.cs │ │ │ └── PackageExport.cs │ │ ├── IPackageManageService.cs │ │ ├── Import/ │ │ │ ├── AutoImportService.cs │ │ │ ├── BasicImporter.cs │ │ │ ├── CecilLdstrImporter.cs │ │ │ ├── CustomModTranslationImporter.cs │ │ │ ├── FileImporter.cs │ │ │ ├── HarmonyLdstrImporter.cs │ │ │ ├── IPackageImportService.cs │ │ │ ├── LdstrImporterBase.cs │ │ │ ├── MonoModLdstrImporter.cs │ │ │ ├── PackageImportService.cs │ │ │ └── RefreshLanguageService.cs │ │ ├── Load/ │ │ │ ├── IFileLoadService.cs │ │ │ ├── IPackageLoadService.cs │ │ │ ├── JsonFileLoad.cs │ │ │ ├── PackedPackageLoad.cs │ │ │ └── SourcePackageLoad.cs │ │ ├── Pack/ │ │ │ ├── IPackagePackService.cs │ │ │ └── ZipPackagePackService.cs │ │ ├── PackageManageService.cs │ │ ├── Save/ │ │ │ ├── IFileSaveService.cs │ │ │ ├── IPackageSaveService.cs │ │ │ ├── JsonFileSaveService.cs │ │ │ └── PackageSaveService.cs │ │ └── Update/ │ │ ├── BasicFileUpdater.cs │ │ ├── CustomModTranslationUpdater.cs │ │ ├── FileUpdater.cs │ │ ├── IPackageUpdateService.cs │ │ ├── IUpdateLogger.cs │ │ ├── LdstrFileUpdater.cs │ │ ├── PackageUpdateService.cs │ │ └── PlainUpdateLogger.cs │ ├── Properties/ │ │ └── AssemblyInfo.cs │ ├── UIs/ │ │ ├── Components/ │ │ │ ├── BasicListBox.cs │ │ │ ├── BasicWindow.cs │ │ │ ├── LabelListBoxItem.cs │ │ │ └── TitleBar.cs │ │ ├── MainWindow.cs │ │ ├── Stylesheet.cs │ │ ├── UIDesktop.cs │ │ ├── UIHost.cs │ │ ├── UIModsPatch.cs │ │ ├── UIRenderer.cs │ │ └── Views/ │ │ ├── ManagerView.cs │ │ ├── ReloadPluginView.cs │ │ └── TestView.cs │ ├── build.txt │ └── description.txt ├── Localizer.sln ├── Localizer.sln.DotSettings ├── LocalizerTest/ │ ├── DataModel/ │ │ └── GitHubUpdateInfoTest.cs │ ├── Helper/ │ │ ├── ExtensionsTest.cs │ │ └── UtilsTest.cs │ ├── LocalizerTest.cs │ ├── LocalizerTest.csproj │ ├── Network/ │ │ └── GitHubModUpdateService.cs │ ├── Ninject.cs │ ├── NonTest/ │ │ └── UpdateLogger.cs │ └── Package/ │ ├── Import/ │ │ ├── BasicFileImportTest.cs │ │ ├── CustomModTranslationFileImportTest.cs │ │ └── LdstrFileImportBaseTest.cs │ └── Update/ │ ├── BasicFileUpdateTest.cs │ ├── CustomModTranslationFileUpdateTest.cs │ └── LdstrFileUpdateTest.cs ├── ModPatch/ │ ├── ModPatch.csproj │ └── Program.cs └── README.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ # To learn more about .editorconfig see https://aka.ms/editorconfigdocs ############################### # Core EditorConfig Options # ############################### # All files [*] indent_style=space # Code files [*.{cs,csx,vb,vbx}] indent_size=4 insert_final_newline=true charset=utf-8 ############################### # .NET Coding Conventions # ############################### [*.{cs,vb}] # Organize usings dotnet_sort_system_directives_first=true # this. preferences dotnet_style_qualification_for_field=false:silent dotnet_style_qualification_for_property=false:silent dotnet_style_qualification_for_method=false:silent dotnet_style_qualification_for_event=false:silent # Language keywords vs BCL types preferences dotnet_style_predefined_type_for_locals_parameters_members=true:silent dotnet_style_predefined_type_for_member_access=true:silent # Parentheses preferences dotnet_style_parentheses_in_arithmetic_binary_operators=always_for_clarity:silent dotnet_style_parentheses_in_relational_binary_operators=always_for_clarity:silent dotnet_style_parentheses_in_other_binary_operators=always_for_clarity:silent dotnet_style_parentheses_in_other_operators=never_if_unnecessary:silent # Modifier preferences dotnet_style_require_accessibility_modifiers=for_non_interface_members:silent dotnet_style_readonly_field=true:suggestion # Expression-level preferences dotnet_style_object_initializer=true:suggestion dotnet_style_collection_initializer=true:suggestion dotnet_style_explicit_tuple_names=true:suggestion dotnet_style_null_propagation=true:suggestion dotnet_style_coalesce_expression=true:suggestion dotnet_style_prefer_is_null_check_over_reference_equality_method=true:silent dotnet_prefer_inferred_tuple_names=true:suggestion dotnet_prefer_inferred_anonymous_type_member_names=true:suggestion dotnet_style_prefer_auto_properties=true:silent dotnet_style_prefer_conditional_expression_over_assignment=true:silent dotnet_style_prefer_conditional_expression_over_return=true:silent ############################### # Naming Conventions # ############################### # Style Definitions dotnet_naming_style.pascal_case_style.capitalization=pascal_case # Use PascalCase for constant fields dotnet_naming_rule.constant_fields_should_be_pascal_case.severity=suggestion dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols=constant_fields dotnet_naming_rule.constant_fields_should_be_pascal_case.style=pascal_case_style dotnet_naming_symbols.constant_fields.applicable_kinds=field dotnet_naming_symbols.constant_fields.applicable_accessibilities=* dotnet_naming_symbols.constant_fields.required_modifiers=const ############################### # C# Coding Conventions # ############################### [*.cs] # var preferences csharp_style_var_for_built_in_types=true:silent csharp_style_var_when_type_is_apparent=true:silent csharp_style_var_elsewhere=true:silent # Expression-bodied members csharp_style_expression_bodied_methods=false:silent csharp_style_expression_bodied_constructors=false:silent csharp_style_expression_bodied_operators=false:silent csharp_style_expression_bodied_properties=true:silent csharp_style_expression_bodied_indexers=true:silent csharp_style_expression_bodied_accessors=true:silent # Pattern matching preferences csharp_style_pattern_matching_over_is_with_cast_check=true:suggestion csharp_style_pattern_matching_over_as_with_null_check=true:suggestion # Null-checking preferences csharp_style_throw_expression=true:suggestion csharp_style_conditional_delegate_call=true:suggestion # Modifier preferences csharp_preferred_modifier_order=public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion # Expression-level preferences csharp_prefer_braces=true:silent csharp_style_deconstructed_variable_declaration=true:suggestion csharp_prefer_simple_default_expression=true:suggestion csharp_style_pattern_local_over_anonymous_function=true:suggestion csharp_style_inlined_variable_declaration=true:suggestion csharp_using_directive_placement=outside_namespace:silent ############################### # C# Formatting Rules # ############################### # New line preferences csharp_new_line_before_open_brace=all csharp_new_line_before_else=true csharp_new_line_before_catch=true csharp_new_line_before_finally=true csharp_new_line_before_members_in_object_initializers=true csharp_new_line_before_members_in_anonymous_types=true csharp_new_line_between_query_expression_clauses=true # Indentation preferences csharp_indent_case_contents=true csharp_indent_switch_labels=true csharp_indent_labels=flush_left csharp_indent_braces=false # Space preferences csharp_space_after_cast=false csharp_space_after_keywords_in_control_flow_statements=true csharp_space_between_method_call_parameter_list_parentheses=false csharp_space_between_method_declaration_parameter_list_parentheses=false csharp_space_between_parentheses=false csharp_space_before_colon_in_inheritance_clause=true csharp_space_after_colon_in_inheritance_clause=true csharp_space_around_binary_operators=before_and_after csharp_space_between_method_declaration_empty_parameter_list_parentheses=false csharp_space_between_method_call_name_and_opening_parenthesis=false csharp_space_between_method_call_empty_parameter_list_parentheses=false # Wrapping preferences csharp_preserve_single_line_statements=true csharp_preserve_single_line_blocks=true ############################### # ReSharper Rules # ############################### # ReSharper properties resharper_align_linq_query=true resharper_align_multiline_argument=true resharper_align_multiline_calls_chain=true resharper_align_multiline_extends_list=true resharper_align_multline_type_parameter_constrains=true resharper_align_multline_type_parameter_list=true resharper_align_tuple_components=true resharper_blank_lines_before_single_line_comment=1 resharper_csharp_align_multiline_parameter=true resharper_csharp_align_multiple_declaration=true resharper_csharp_empty_block_style=together resharper_csharp_insert_final_newline=true resharper_csharp_use_indent_from_vs=false resharper_keep_existing_declaration_block_arrangement=false resharper_keep_existing_switch_expression_arrangement=false resharper_max_enum_members_on_line=1 resharper_max_initializer_elements_on_line=1 resharper_place_simple_anonymousmethod_on_single_line=false resharper_place_simple_embedded_statement_on_same_line=False resharper_place_simple_initializer_on_single_line=true resharper_wrap_linq_expressions=chop_always ================================================ FILE: .gitattributes ================================================ ############################################################################### # Set default behavior to automatically normalize line endings. ############################################################################### * text=auto ############################################################################### # Set default behavior for command prompt diff. # # This is need for earlier builds of msysgit that does not have it on by # default for csharp files. # Note: This is only used by command line ############################################################################### #*.cs diff=csharp ############################################################################### # Set the merge driver for project and solution files # # Merging from the command prompt will add diff markers to the files if there # are conflicts (Merging from VS is not affected by the settings below, in VS # the diff markers are never inserted). Diff markers may cause the following # file extensions to fail to load in VS. An alternative would be to treat # these files as binary and thus will always conflict and require user # intervention with every merge. To do so, just uncomment the entries below ############################################################################### #*.sln merge=binary #*.csproj merge=binary #*.vbproj merge=binary #*.vcxproj merge=binary #*.vcproj merge=binary #*.dbproj merge=binary #*.fsproj merge=binary #*.lsproj merge=binary #*.wixproj merge=binary #*.modelproj merge=binary #*.sqlproj merge=binary #*.wwaproj merge=binary ############################################################################### # behavior for image files # # image files are treated as binary by default. ############################################################################### #*.jpg binary #*.png binary #*.gif binary ############################################################################### # diff behavior for common document formats # # Convert binary document formats to text before diffing them. This feature # is only available from the command line. Turn it on by uncommenting the # entries below. ############################################################################### #*.doc diff=astextplain #*.DOC diff=astextplain #*.docx diff=astextplain #*.DOCX diff=astextplain #*.dot diff=astextplain #*.DOT diff=astextplain #*.pdf diff=astextplain #*.PDF diff=astextplain #*.rtf diff=astextplain #*.RTF diff=astextplain ================================================ FILE: .github/workflows/build.yml ================================================ name: Mod Build on: [push] jobs: build: runs-on: windows-latest steps: - uses: actions/checkout@v1 with: submodules: recursive - name: Installer NuGet client uses: nuget/setup-nuget@v1 - name: Setup tModLoader uses: chi-rei-den/ModLoaderTools@v1.1 with: command: setup - name: Restore NuGet Packages run: nuget restore Localizer.sln - name: Build Mod run: | & "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\MSBuild.exe" Localizer.sln /p:Configuration=Release /p:Platform=x86 - name: Patch Mod run: '& "$ENV:GITHUB_WORKSPACE\ModPatch\bin\Release\net472\ModPatch.exe"' - name: Publish Mod if: github.ref == 'refs/heads/master' uses: chi-rei-den/ModLoaderTools@v1 with: command: publish path: Localizer env: steamid64: ${{ secrets.steamid64 }} passphrase: ${{ secrets.mod_browser_passphrase }} - name: Clean artifact run: | mkdir .\Artifact\Artifact\ Copy-Item -Path "$ENV:UserProfile\Documents\My Games\Terraria\ModLoader\Mods\*" -Destination .\Artifact\Artifact del .\Artifact\Artifact\enabled.json - uses: actions/upload-artifact@master with: name: Build Artifact path: Artifact - name: Run Tests run: | copy .\LocalizerTest\bin\Release\net472\tModLoader.exe .\LocalizerTest\bin\Release\net472\Terraria.exe & "$ENV:UserProfile\.nuget\packages\xunit.runner.console\2.4.1\tools\net472\xunit.console.x86.exe" ".\LocalizerTest\bin\Release\net472\LocalizerTest.dll" ================================================ FILE: .gitignore ================================================ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. Localizer/WPF/ # User-specific files *.suo *.user *.userosscache *.sln.docstates # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ # Visual Studio 2015 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUNIT *.VisualState.xml TestResult.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c # DNX project.lock.json project.fragment.lock.json artifacts/ *_i.c *_p.c *_i.h *.ilk *.meta *.obj *.pch *.pdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opendb *.opensdf *.sdf *.cachefile *.VC.db *.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx *.sap # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # JustCode is a .NET coding add-in .JustCode # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # NCrunch _NCrunch_* .*crunch*.local.xml nCrunchTemp_* # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # TODO: Comment the next line if you want to checkin your web deploy settings # but database connection strings (with potential passwords) will be unencrypted #*.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to # checkin your Azure Web App publish settings, but sensitive information contained # in these scripts will be unencrypted PublishScripts/ # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore **/packages/* # except build/, which is used as an MSBuild target. !**/packages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/packages/repositories.config # NuGet v3's project.json files produces more ignoreable files *.nuget.props *.nuget.targets # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Windows Store app package directories and files AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !*.[Cc]ache/ # Others ClientBin/ ~$* *~ *.dbmdl *.dbproj.schemaview *.jfm *.pfx *.publishsettings node_modules/ orleans.codegen.cs # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm # SQL Server files *.mdf *.ldf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings # Microsoft Fakes FakesAssemblies/ # GhostDoc plugin setting file *.GhostDoc.xml # Node.js Tools for Visual Studio .ntvs_analysis.dat # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/ModelManifest.xml **/*.Server/GeneratedArtifacts **/*.Server/ModelManifest.xml _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ # FAKE - F# Make .fake/ # JetBrains Rider .idea/ *.sln.iml # CodeRush .cr/ # Python Tools for Visual Studio (PTVS) __pycache__/ *.pyc /Localizer/Plugins /Localizer/lib ================================================ FILE: .gitmodules ================================================ [submodule "Squid"] path = Squid url = https://github.com/chi-rei-den/Squid ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: Localizer/Attributes/ModTranslationOwnerFieldAttribute.cs ================================================ using System; namespace Localizer.Attributes { /// /// Indicates the field contains objects those have ModTranslations need to be localized. /// public class ModTranslationOwnerFieldAttribute : Attribute { public ModTranslationOwnerFieldAttribute(string fieldName) { FieldName = fieldName; } public string FieldName { get; } } } ================================================ FILE: Localizer/Attributes/ModTranslationPropAttribute.cs ================================================ using System; namespace Localizer.Attributes { /// /// Indicates the name of ModTranslation property. /// public class ModTranslationPropAttribute : Attribute { public ModTranslationPropAttribute(string propName) { PropName = propName; } public string PropName { get; } } } ================================================ FILE: Localizer/Attributes/OperationTimingAttribute.cs ================================================ using System; namespace Localizer.Attributes { public class OperationTimingAttribute : Attribute { public OperationTiming Timing { get; } public OperationTimingAttribute(OperationTiming timing = OperationTiming.Any) { Timing = timing; } } } ================================================ FILE: Localizer/Configuration.cs ================================================ namespace Localizer { public class Configuration { public bool AutoImport { get; set; } = true; public bool ImportLdstr { get; set; } = true; public string LdstrImporter { get; set; } = "Cecil"; public bool ImporBasictAfterSetupContent { get; set; } = true; public AutoImportType AutoImportType { get; set; } = AutoImportType.All; public bool ShowUI { get; set; } = true; public LogLevel LogLevel { get; set; } = LogLevel.Info; public bool RebuildTooltips { get; set; } = true; public bool RebuildTooltipsOnce { get; set; } = true; public string[] ModListMirror { get; set; } = new[] { "mirror.sgkoi.dev", "mirror7.sgkoi.dev", "mirror8.sgkoi.dev", "mirror5.sgkoi.dev", }; public string[] ModDownloadMirror { get; set; } = new[] { "mirror.sgkoi.dev", "mirror7.sgkoi.dev", "mirror8.sgkoi.dev", "mirror5.sgkoi.dev", }; public string[] ModDescMirror { get; set; } = new[] { "mirror.sgkoi.dev", "mirror7.sgkoi.dev", "mirror8.sgkoi.dev", "mirror5.sgkoi.dev", }; } } ================================================ FILE: Localizer/DataModel/Default/AttributeFile.cs ================================================ using System.Collections.Generic; using System.Linq; namespace Localizer.DataModel.Default { public class AttributeFile : IFile { public Dictionary Translations { get; set; } = new Dictionary(); public List GetKeys() { return Translations.Keys.ToList(); } public IEntry GetValue(string key) { return Translations[key]; } } } ================================================ FILE: Localizer/DataModel/Default/BaseEntry.cs ================================================ namespace Localizer.DataModel.Default { public class BaseEntry : IEntry { public string Origin { get; set; } public string Translation { get; set; } public IEntry Clone() { return new BaseEntry { Origin = Origin, Translation = Translation }; } } } ================================================ FILE: Localizer/DataModel/Default/BasicBuffFile.cs ================================================ using System.Collections.Generic; using System.Linq; using Localizer.Attributes; namespace Localizer.DataModel.Default { public class BuffEntry : IEntry { [ModTranslationProp("DisplayName")] public BaseEntry Name { get; set; } [ModTranslationProp("Description")] public BaseEntry Description { get; set; } public IEntry Clone() { return new BuffEntry { Name = Name.Clone() as BaseEntry, Description = Description.Clone() as BaseEntry }; } } public class BasicBuffFile : IFile { [ModTranslationOwnerField("buffs")] public Dictionary Buffs { get; set; } = new Dictionary(); public List GetKeys() { return Buffs.Keys.ToList(); } public IEntry GetValue(string key) { return Buffs[key]; } } } ================================================ FILE: Localizer/DataModel/Default/BasicItemFile.cs ================================================ using System.Collections.Generic; using System.Linq; using Localizer.Attributes; namespace Localizer.DataModel.Default { public class ItemEntry : IEntry { [ModTranslationProp("DisplayName")] public BaseEntry Name { get; set; } [ModTranslationProp("Tooltip")] public BaseEntry Tooltip { get; set; } public IEntry Clone() { return new ItemEntry { Name = Name.Clone() as BaseEntry, Tooltip = Tooltip.Clone() as BaseEntry }; } } public class BasicItemFile : IFile { [ModTranslationOwnerField("items")] public Dictionary Items { get; set; } = new Dictionary(); public List GetKeys() { return Items.Keys.ToList(); } public IEntry GetValue(string key) { return Items[key]; } } } ================================================ FILE: Localizer/DataModel/Default/BasicNPCFile.cs ================================================ using System.Collections.Generic; using System.Linq; using Localizer.Attributes; namespace Localizer.DataModel.Default { public class NPCEntry : IEntry { [ModTranslationProp("DisplayName")] public BaseEntry Name { get; set; } public IEntry Clone() { return new NPCEntry { Name = Name.Clone() as BaseEntry }; } } public class BasicNPCFile : IFile { [ModTranslationOwnerField("npcs")] public Dictionary NPCs { get; set; } = new Dictionary(); public List GetKeys() { return NPCs.Keys.ToList(); } public IEntry GetValue(string key) { return NPCs[key]; } } } ================================================ FILE: Localizer/DataModel/Default/BasicPrefixFile.cs ================================================ using System.Collections.Generic; using System.Linq; using Localizer.Attributes; namespace Localizer.DataModel.Default { public class PrefixEntry : IEntry { [ModTranslationProp("DisplayName")] public BaseEntry Name { get; set; } public IEntry Clone() { return new PrefixEntry { Name = Name.Clone() as BaseEntry }; } } public class BasicPrefixFile : IFile { [ModTranslationOwnerField("prefixes")] public Dictionary Prefixes { get; set; } = new Dictionary(); public List GetKeys() { return Prefixes.Keys.ToList(); } public IEntry GetValue(string key) { return Prefixes[key]; } } } ================================================ FILE: Localizer/DataModel/Default/BasicProjectileFile.cs ================================================ using System.Collections.Generic; using System.Linq; using Localizer.Attributes; namespace Localizer.DataModel.Default { public class ProjectileEntry : IEntry { [ModTranslationProp("DisplayName")] public BaseEntry Name { get; set; } public IEntry Clone() { return new ProjectileEntry { Name = Name.Clone() as BaseEntry }; } } public class BasicProjectileFile : IFile { [ModTranslationOwnerField("projectiles")] public Dictionary Projectiles { get; set; } = new Dictionary(); public List GetKeys() { return Projectiles.Keys.ToList(); } public IEntry GetValue(string key) { return Projectiles[key]; } } } ================================================ FILE: Localizer/DataModel/Default/CustomModTranslationFile.cs ================================================ using System.Collections.Generic; using System.Linq; namespace Localizer.DataModel.Default { public class CustomModTranslationFile : IFile { public Dictionary Translations { get; set; } = new Dictionary(); public List GetKeys() { return Translations.Keys.ToList(); } public IEntry GetValue(string key) { return Translations[key]; } } } ================================================ FILE: Localizer/DataModel/Default/ExportConfig.cs ================================================ namespace Localizer.DataModel.Default { public class ExportConfig : IExportConfig { public bool MakeBackup { get; set; } public bool ForceOverride { get; set; } public bool WithTranslation { get; set; } } } ================================================ FILE: Localizer/DataModel/Default/File.cs ================================================ using System.Collections.Generic; using Newtonsoft.Json; namespace Localizer.DataModel.Default { public abstract class File : IFile { [JsonIgnore] public IPackage Owner { get; set; } public abstract List GetKeys(); public abstract IEntry GetValue(string key); public abstract void AddEntry(string key, IEntry entry); } } ================================================ FILE: Localizer/DataModel/Default/GitHubUpdateInfo.cs ================================================ using System; namespace Localizer.DataModel.Default { public class GitHubUpdateInfo : IUpdateInfo { public UpdateType Type { get; } public Version Version { get; } private string versionString; public GitHubUpdateInfo(string versionString) { this.versionString = versionString; Type = ParseType(versionString[0]); Version = Version.Parse(versionString.Substring(1, versionString.Length - 1)); } internal UpdateType ParseType(char t) { switch (t) { case 'a': return UpdateType.Minor; case 'b': return UpdateType.Major; case 'c': return UpdateType.Critical; default: return UpdateType.None; } } } } ================================================ FILE: Localizer/DataModel/Default/LdstrFile.cs ================================================ using System.Collections.Generic; using System.Linq; using Localizer.Attributes; namespace Localizer.DataModel.Default { public class LdstrEntry : IEntry { public List Instructions { get; set; } public IEntry Clone() { var entry = new LdstrEntry { Instructions = new List() }; foreach (var ins in Instructions) { entry.Instructions.Add(ins.Clone() as BaseEntry); } return entry; } } [OperationTiming] public class LdstrFile : IFile { public Dictionary LdstrEntries { get; set; } = new Dictionary(); public List GetKeys() { return LdstrEntries.Keys.ToList(); } public IEntry GetValue(string key) { return LdstrEntries[key]; } } } ================================================ FILE: Localizer/DataModel/Default/LoadedModWrapper.cs ================================================ using System; using System.Reflection; using Terraria; using Terraria.ModLoader; using Terraria.ModLoader.Core; namespace Localizer.DataModel.Default { public class LoadedModWrapper : IMod { internal readonly WeakReference wrapped; public LoadedModWrapper(object mod) { wrapped = new WeakReference(mod); name = mod.ValueOf("Name"); Code = name == "ModLoader" ? Assembly.GetAssembly(typeof(Main)) : mod.ValueOf("assembly"); var buildProp = mod.ValueOf("properties"); displayName = buildProp.ValueOf("displayName"); version = buildProp.ValueOf("version"); File = mod.ValueOf("modFile"); } public string Name => name ?? ""; private string name; public Assembly Code { get; } public string DisplayName => displayName ?? ""; private string displayName; public Version Version => version ?? new Version(); private Version version; public TmodFile File { get; } public bool Enabled => (bool)typeof(ModLoader).Invoke("IsEnabled", Name); } } ================================================ FILE: Localizer/DataModel/Default/ModWrapper.cs ================================================ using System; using System.Reflection; using Terraria; using Terraria.ModLoader; using Terraria.ModLoader.Core; namespace Localizer.DataModel.Default { public class ModWrapper : IMod { private readonly WeakReference wrapped; public ModWrapper(Mod mod) { if (mod is null) { throw new ArgumentNullException(nameof(mod)); } wrapped = new WeakReference(mod); } public Mod Mod { get { Mod mod = null; wrapped?.TryGetTarget(out mod); return mod; } } public string Name => Mod?.Name ?? ""; public Assembly Code { get { if (Name == "ModLoader") { return Assembly.GetAssembly(typeof(Main)); } else { return Mod?.Code; } } } public string DisplayName => Mod.DisplayName ?? ""; public Version Version => Mod?.Version; public TmodFile File => Mod?.ValueOf("File"); public bool Enabled => (bool)typeof(ModLoader).Invoke("IsEnabled", Name); } } ================================================ FILE: Localizer/DataModel/Default/Package.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Newtonsoft.Json; namespace Localizer.DataModel.Default { [JsonObject(MemberSerialization.OptIn)] public class Package : IPackage { public Package() { } public Package(string name, IMod mod, CultureInfo language) { Name = name; Mod = mod; ModName = mod.Name; Description = string.Empty; Language = language; Version = new Version(1, 0, 0, 0); FileList = new List(); Files = new List(); } public bool Exported { get; set; } [JsonProperty] public string Name { get; set; } = ""; [JsonProperty] public string Author { get; set; } = ""; [JsonProperty] public string ModName { get; set; } = ""; [JsonProperty] public string Description { get; set; } = ""; [JsonProperty] public string LocalizedModName { get; set; } = ""; [JsonProperty] public Version Version { get; set; } [JsonProperty] public Version ModVersion { get; set; } [JsonProperty] public CultureInfo Language { get; set; } = CultureInfo.GetCultureInfo("en-US"); [JsonProperty] public ICollection FileList { get; set; } = new List(); public ICollection Files { get; set; } = new List(); public int Count => Files.Sum(f => f.GetKeys().Count()); public bool Enabled { get; set; } = true; public IMod Mod { get; set; } public void AddFile(IFile file) { if (file == null) { return; } if (!FileList.Contains(file.GetType().Name)) { FileList.Add(file.GetType().Name); } Files.Add(file); } public void RemoveFile(IFile file) { throw new NotImplementedException(); } } } ================================================ FILE: Localizer/DataModel/Default/PackageGroup.cs ================================================ using System.Collections.Generic; namespace Localizer.DataModel.Default { public class PackageGroup : IPackageGroup { public IMod Mod { get; set; } public ICollection Packages { get; set; } } } ================================================ FILE: Localizer/DataModel/Default/PackageGroupState.cs ================================================ using System.Collections.Specialized; using Newtonsoft.Json; namespace Localizer.DataModel.Default { [JsonObject(MemberSerialization.OptOut)] public class PackageGroupState { public PackageGroupState() { } public PackageGroupState(IPackageGroup pg) { ModName = pg.Mod.Name; Packages = new OrderedDictionary(); foreach (var p in pg.Packages) { Packages.Add(p.Name, p.Enabled); } } public string ModName { get; set; } public OrderedDictionary Packages { get; set; } } } ================================================ FILE: Localizer/DataModel/IEntry.cs ================================================ namespace Localizer.DataModel { public interface IEntry { IEntry Clone(); } } ================================================ FILE: Localizer/DataModel/IExportConfig.cs ================================================ namespace Localizer.DataModel { public interface IExportConfig { /// /// Create backups before exportation. /// bool MakeBackup { get; set; } /// /// Overwrite or not if the file is already exists. /// bool ForceOverride { get; set; } /// /// If the ModTranslation already has a translation of current culture, /// then export it. /// bool WithTranslation { get; set; } } } ================================================ FILE: Localizer/DataModel/IFile.cs ================================================ using System.Collections.Generic; namespace Localizer.DataModel { public interface IFile { List GetKeys(); IEntry GetValue(string key); } } ================================================ FILE: Localizer/DataModel/IMod.cs ================================================ using System; using System.Reflection; using Terraria.ModLoader.Core; namespace Localizer.DataModel { public interface IMod { /// /// Name of the mod. /// string Name { get; } /// /// Code of the mod. /// Assembly Code { get; } /// /// DisplayName of the mod. /// string DisplayName { get; } /// /// Version of the mod. /// Version Version { get; } /// /// File of the mod. /// TmodFile File { get; } bool Enabled { get; } } } ================================================ FILE: Localizer/DataModel/IPackage.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; namespace Localizer.DataModel { public interface IPackage { /// /// Name of the package. /// string Name { get; set; } /// /// Author of the package. /// string Author { get; set; } /// /// The name of the mod this package target for. /// string ModName { get; set; } /// /// The localized name of the mod. /// string LocalizedModName { get; set; } /// /// Description of the package. /// string Description { get; set; } /// /// Version of the package. /// Version Version { get; set; } /// /// Version of the targeted mod. /// Version ModVersion { get; set; } /// /// Culture of the package. /// CultureInfo Language { get; set; } /// /// File types this package including. /// ICollection FileList { get; set; } /// /// Files this package including. /// ICollection Files { get; set; } int Count { get; } /// /// The enable status of the package. /// bool Enabled { get; set; } /// /// The mod this package target for. /// IMod Mod { get; set; } /// /// Add a file into Files and FileList /// /// void AddFile(IFile file); /// /// Remove a file from Files and FileList /// /// void RemoveFile(IFile file); } } ================================================ FILE: Localizer/DataModel/IPackageGroup.cs ================================================ using System.Collections.Generic; namespace Localizer.DataModel { public interface IPackageGroup { /// /// Mod of the group, every package in this group is for this mod. /// IMod Mod { get; set; } ICollection Packages { get; set; } } } ================================================ FILE: Localizer/DataModel/IUpdateInfo.cs ================================================ using System; namespace Localizer.DataModel { public enum UpdateType { None, Minor, Major, Critical, } public interface IUpdateInfo { UpdateType Type { get; } Version Version { get; } } } ================================================ FILE: Localizer/Disposable.cs ================================================ using System; namespace Localizer { public abstract class Disposable : IDisposable { protected bool disposed = false; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~Disposable() { Dispose(false); } protected virtual void Dispose(bool disposeManaged) { if (!disposed) { if (disposeManaged) { DisposeManaged(); } DisposeUnmanaged(); disposed = true; } } protected virtual void DisposeManaged() { } protected virtual void DisposeUnmanaged() { } } } ================================================ FILE: Localizer/Enums/AutoImportType.cs ================================================ using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Localizer { [JsonConverter(typeof(StringEnumConverter))] public enum AutoImportType { All, DownloadedOnly, SourceOnly, } } ================================================ FILE: Localizer/Enums/LogLevel.cs ================================================ using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Localizer { [JsonConverter(typeof(StringEnumConverter))] public enum LogLevel : byte { Fatal = 0, Error = 1, Warn = 2, Info = 3, Debug = 4, } } ================================================ FILE: Localizer/Enums/OperationTiming.cs ================================================ using System; namespace Localizer { [Flags] public enum OperationTiming : byte { BeforeModCtor = 0b00000001, BeforeModLoad = 0b00000010, BeforeContentLoad = 0b00000100, PostContentLoad = 0b00001000, Any = 0b11111111, } } ================================================ FILE: Localizer/Enums/PackageType.cs ================================================ namespace Localizer { public enum PackageType { Packed, Source, } } ================================================ FILE: Localizer/Helpers/Extensions.cs ================================================ using System; using System.Globalization; using System.Linq; using System.Reflection; using Localizer.Attributes; using Localizer.DataModel.Default; using Terraria.ModLoader; namespace Localizer.Helpers { public static class Extensions { #region ModTranslation public static void Import(this ModTranslation modTranslation, BaseEntry entry, CultureInfo culture) { if (entry != null) { if (entry.Origin != modTranslation.GetDefault() && modTranslation.GetDefault() != modTranslation.Key && !string.IsNullOrWhiteSpace(modTranslation.GetDefault()) && !string.IsNullOrWhiteSpace(entry.Origin)) { Utils.LogWarn( $"Mismatch origin text when importing \"{modTranslation.Key}\"{Environment.NewLine}Origin in mod: {modTranslation.GetDefault()}{Environment.NewLine}Origin in package: {entry.Origin}{Environment.NewLine}Translation in package: {entry.Translation}"); return; } if (modTranslation.GetDefault() != null && !string.IsNullOrEmpty(entry.Translation) && entry.Translation != modTranslation.Key) { modTranslation.AddTranslation(Localizer.CultureInfoToGameCulture(culture), entry.Translation); } } } public static string GetTranslation(this ModTranslation modTranslation, CultureInfo culture) { var translation = modTranslation.GetTranslation(Localizer.CultureInfoToGameCulture(culture)); return string.IsNullOrWhiteSpace(translation) ? "" : translation; } public static string DefaultOrEmpty(this ModTranslation modTranslation) { var d = modTranslation.GetDefault(); return string.IsNullOrWhiteSpace(d) || d == modTranslation.Key ? "" : d; } #endregion #region Reflection public static PropertyInfo[] ModTranslationOwnerField(this Type type) { return type.GetProperties().Where(p => p.GetCustomAttribute() != null) .ToArray(); } public static string ModTranslationOwnerFieldName(this PropertyInfo prop) { return prop.GetCustomAttribute()?.FieldName; } public static PropertyInfo[] ModTranslationProp(this Type type) { return type.GetProperties().Where(p => p.GetCustomAttribute() != null) .ToArray(); } #endregion } } ================================================ FILE: Localizer/Helpers/Reflection.cs ================================================ using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Harmony; namespace System.Reflection { public static class NoroHelper { public const BindingFlags AnyVisibility = BindingFlags.Public | BindingFlags.NonPublic; public const BindingFlags Any = AnyVisibility | BindingFlags.Static | BindingFlags.Instance; public static HarmonyMethod HarmonyMethod(Expression expression) { return new HarmonyMethod((expression.Body as MethodCallExpression)?.Method); } public static MethodInfo MethodInfo(Expression expression) { return (expression.Body as MethodCallExpression)?.Method; } public static Type Type(this string name) { //return AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.DefinedTypes).FirstOrDefault(t => t.FullName == name); return AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.DefinedTypes.Any(t => t.FullName == name))?.ManifestModule.GetType(name); } public static FieldInfo Field(this Type type, string name, BindingFlags flags = Any) { return type?.GetField(name, flags) ?? type?.BaseType?.Field(name, flags); } public static PropertyInfo Property(this Type type, string name, BindingFlags flags = Any) { return type?.GetProperty(name, flags) ?? type?.BaseType?.Property(name, flags); } public static MethodInfo Method(this Type t, string name, IEnumerable args) { return t.Method(name, args.ToArray()); } public static MethodInfo Method(this Type t, string name, params Type[] args) { if (name is null) { throw new ArgumentNullException(nameof(name)); } if (args == null || args.Length == 0) { return t.GetMethod(name, Any); } return t.GetMethod(name, Any, null, args, new ParameterModifier[] { }); } public static object ValueOf(this Type type, string name, object value = null) { var field = type?.Field(name); if (field != null) { return field.GetValue(value); } var prop = type?.Property(name); if (prop != null) { return prop.GetValue(value); } throw new MemberAccessException($"{name} not found ({type})"); } public static object ValueOf(this object obj, string name) { return obj?.GetType().ValueOf(name, obj); } public static T ValueOf(this Type type, string name) { return (T)type?.ValueOf(name); } public static T ValueOf(this object obj, string name) { return (T)obj?.ValueOf(name); } public static void SetField(this Type type, string name, object value) { type?.Field(name).SetValue(null, value); } public static void SetField(this object obj, string name, object value) { obj?.GetType().Field(name).SetValue(obj, value); } public static object Invoke(this object o, string name, params object[] args) { if (name is null) { throw new ArgumentNullException(nameof(name)); } var method = (o is Type t ? t : o.GetType()).Method(name, args.Select(a => a.GetType())) ?? throw new MissingMethodException($"{o.GetType().FullName}.{name}"); return method.Invoke(o, args); } } } ================================================ FILE: Localizer/Helpers/UI.cs ================================================ using System; using System.Reflection; using Localizer.DataModel; using Microsoft.Xna.Framework.Graphics; using Terraria.UI; using static Localizer.Lang; namespace Localizer.Helpers { public static class UI { public static string GetPkgLabelText(IPackage p) { return _("PackageDisplay", _(p.Enabled ? "PackageEnabled" : "PackageDisabled"), p.Name, p.Version, p.Author); } public static void ShowInfoMessage(string message, int gotoMenu, UIState state = null, string altButtonText = "", Action altButtonAction = null) { var infoMsgUI = GetModLoaderUI("infoMessage") ?? throw new Exception("Cannot Find infoMessage field"); infoMsgUI.Invoke("Show", message, gotoMenu, state, altButtonText, altButtonAction); } public static object GetModLoaderUI(string uiName) { return "Terraria.ModLoader.UI.Interface".Type()?.ValueOf(uiName); } public static void SafeBegin(this SpriteBatch sb) { try { sb.Begin(); } catch (InvalidOperationException) { } } public static void SafeBegin(this SpriteBatch sb, SamplerState sampler, RasterizerState rasterizer) { try { sb.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied, sampler, null, rasterizer); } catch (InvalidOperationException) { } } public static void SafeEnd(this SpriteBatch sb) { try { sb.End(); } catch (InvalidOperationException) { } } } } ================================================ FILE: Localizer/Helpers/Utils.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Reflection; using System.Reflection.Emit; using System.Text; using System.Text.RegularExpressions; using Harmony; using Harmony.ILCopying; using Localizer.Attributes; using Localizer.DataModel; using Localizer.DataModel.Default; using Localizer.Helpers; using Mono.Cecil; using MonoMod.Utils; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Terraria.ModLoader; using File = System.IO.File; // ReSharper disable once CheckNamespace namespace Localizer { public static partial class Utils { #region Zip /// /// Add a file into a ZipArchive as an entry. /// /// Target archive. /// The path of the file. /// Entry name in the archive. public static void WriteZipArchiveEntry(ZipArchive archive, string filePath, string entryName) { var fileEntry = archive.CreateEntry(entryName); using (var stream = fileEntry.Open()) { var fileBytes = File.ReadAllBytes(filePath); stream.Write(fileBytes, 0, fileBytes.Length); } } #endregion #region Reflection /// /// Return the method matched with the findableName in the given type. /// Return null if fail. /// /// /// /// public static MethodBase GetMethodBase(string findableName) { var method = typeof(T).FindMethod(findableName); return method != null ? MethodBase.GetMethodFromHandle(method.MethodHandle) : null; } private static Dictionary> _cachedMethod = new Dictionary>(); public static MethodBase FindMethodByID(Module m, string findableName) { if (!_cachedMethod.ContainsKey(m)) { _cachedMethod.Add(m, new Dictionary()); foreach (var t in m.GetTypes()) { foreach (var method in t.GetMethods(NoroHelper.Any)) { var key = method.GetID(); if (!_cachedMethod[m].ContainsKey(key)) { _cachedMethod[m].Add(key, method); } } } } return _cachedMethod[m].ContainsKey(findableName) ? _cachedMethod[m][findableName] : null; } private static Regex genericTypeMatch = new Regex(@"\[\[(.*?), .*?\]\]", RegexOptions.Compiled); public static MethodDefinition FindMethodByID(ModuleDefinition m, string findableName) { var cecilName = genericTypeMatch.Replace(findableName, "<$1>"); foreach (var t in m.GetTypes()) { foreach (var method in t.Methods) { var id = method.GetID(); if (id == findableName) { return method; } if (id == cecilName) { return method; } } } return null; } #endregion #region Json /// /// Serialize an object and write to disk. /// /// Object want to serialize. /// Store path of the serialized file. /// public static void SerializeJsonAndCreateFile(object obj, string path, bool indent = true) { using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write)) { using (var sw = new StreamWriter(fs)) { sw.Write(JsonConvert.SerializeObject(obj, indent ? Formatting.Indented : Formatting.None, new VersionConverter())); } } } /// /// Read a file return the deserialized object. /// /// Path of the file. /// The type of result. /// public static T ReadFileAndDeserializeJson(string path) { using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { return ReadFileAndDeserializeJson(fs); } } /// /// Read a stream return the deserialized object. /// /// Stream want to deserialize. /// The type of result. /// public static T ReadFileAndDeserializeJson(Stream stream) { using (var sr = new StreamReader(stream)) { var content = sr.ReadToEnd(); try { return JsonConvert.DeserializeObject(content, new VersionConverter()); } catch { return JsonConvert.DeserializeObject(content); } } } /// /// Read a file return the deserialized object. /// /// The type of result. /// Path of the file. /// public static object ReadFileAndDeserializeJson(Type t, string path) { using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { return ReadFileAndDeserializeJson(t, fs); } } /// /// Read a file return the deserialized object. /// /// The type of result. /// Stream want to deserialize. /// public static object ReadFileAndDeserializeJson(Type t, Stream stream) { using (var sr = new StreamReader(stream)) { return JsonConvert.DeserializeObject(sr.ReadToEnd(), t); } } #endregion #region GameCulture #endregion #region Log public static void LogFatal(object o) { Localizer.Log.Fatal(o); } public static void LogError(object o) { if (Localizer.Config.LogLevel >= LogLevel.Error) { Localizer.Log.Error(o); } } public static void LogWarn(object o) { if (Localizer.Config.LogLevel >= LogLevel.Warn) { Localizer.Log.Warn(o); } } public static void LogInfo(object o) { if (Localizer.Config.LogLevel >= LogLevel.Info) { Localizer.Log.Info(o); } } public static void LogDebug(object o) { if (Localizer.Config.LogLevel >= LogLevel.Debug) { Localizer.Log.Debug(o); } } #endregion #region Network internal static string UserAgent(bool localizer = true) { if (!localizer) { // Request by tModLoader return $"tModLoader/{ModLoader.versionTag} ({Environment.OSVersion}; {(Environment.Is64BitOperatingSystem ? "x64" : "x86")})"; } return $"Localizer/{Localizer.Instance.Version} ({Environment.OSVersion}; {(Environment.Is64BitOperatingSystem ? "x64" : "x86")}) tModLoader/{ModLoader.versionTag} ({(Environment.Is64BitOperatingSystem ? "x64" : "x86")})"; } public static HttpWebResponse GET(string url) { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.ContentType = "application/json;charset=UTF-8"; request.Accept = "application/vnd.github.v3+json"; request.UserAgent = UserAgent(); request.Timeout = 9000; request.Headers["Accept-Language"] = Terraria.Localization.LanguageManager.Instance.ActiveCulture.CultureInfo.ToString(); return (HttpWebResponse)request.GetResponse(); } public static string GetResponseBody(HttpWebResponse response) { if (response == null) { return null; } var encoding = Encoding.UTF8; using (var myResponseStream = response.GetResponseStream()) { using (var myStreamReader = new StreamReader(myResponseStream, encoding)) { return myStreamReader.ReadToEnd(); } } } #endregion #region Others public static string AsRainbow(string text, int frameCounter, int? unit = null) { var rainbowText = ""; var hueUnit = 4f / (unit ?? text.Length); var baseHue = (frameCounter % 300) / 300f; for (var i = 0; i < text.Length; i++) { var colorHue = baseHue + hueUnit * i / text.Length; var color = Terraria.Main.hslToRgb(1.5f - colorHue, 1, 0.7f); rainbowText += $"[c/{color.R:X2}{color.G:X2}{color.B:X2}:{text[i]}]"; } return rainbowText; } /// /// Create mappings from the name of actual ModTranslation container in the mod to the property /// in the translation file. /// /// /// public static Dictionary CreateEntryMappings(Type entryType) { if (entryType == null) { throw new ArgumentNullException(); } var mappings = new Dictionary(); foreach (var prop in entryType.ModTranslationProp()) { var attr = prop.GetCustomAttribute(typeof(ModTranslationPropAttribute)) as ModTranslationPropAttribute; mappings.Add(attr.PropName, prop); } return mappings; } /// /// Get the translation of the property of the entry. /// eg: GetTranslation(*an ItemEntry*, *Name property*) /// which returns ItemEntry.Name.Translation. /// /// /// /// public static string GetTranslationOfEntry(IEntry entry, PropertyInfo prop) { return (prop.GetValue(entry) as BaseEntry)?.Translation; } /// /// Create directory if doesn't exist. /// /// public static void EnsureDir(string path) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } public static ICollection GetLoadedMods() { return ModLoader.Mods?.Select(m => Localizer.GetWrappedMod(m.Name)).ToArray(); } public static Mod GetModByName(string name) { return ModLoader.Mods.FirstOrDefault(m => m.Name == name); } public static string DateTimeToFileName(DateTime dateTime) { return string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", dateTime); } public static string EscapePath(string path) { return path.Trim(Path.GetInvalidPathChars()); } public static List GetInstructions(MethodBase method) { var dummy = new DynamicMethod("Dummy", typeof(void), new Type[] { }); if (method.GetMethodBody() is null) { return null; } return MethodBodyReader.GetInstructions(dummy.GetILGenerator(), method); } public static void SafeWrap(Action action) { SafeWrap(action, out var ex); } public static void SafeWrap(Action action, out Exception ex) { try { ex = null; action(); } catch (Exception e) { ex = e; LogError(e); } } public static T SafeWrap(Func func) { return SafeWrap(func, out var ex); } public static T SafeWrap(Func func, out Exception ex) { try { ex = null; return func(); } catch (Exception e) { ex = e; LogError(e); } return default; } public static void Patch(this HarmonyInstance instance, string @class, string method, bool exactMatch = true, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null) { if (exactMatch) { instance.Patch(@class.Type().Method(method), prefix: prefix, postfix: postfix, transpiler: transpiler); } else { instance.Patch(@class.Type() .GetMethods(NoroHelper.Any) .FirstOrDefault(m => m.Name.Contains(method)), prefix: prefix, postfix: postfix, transpiler: transpiler); } } #endregion } } ================================================ FILE: Localizer/Hooks.cs ================================================ using Microsoft.Xna.Framework; namespace Localizer { public class Hooks { public delegate void BeforeModCtorHandler(object mod); public static event BeforeModCtorHandler BeforeModCtor; internal static void InvokeBeforeModCtor(object mod) { BeforeModCtor?.Invoke(mod); } public delegate void BeforeLoadHandler(); public static event BeforeLoadHandler BeforeLoad; internal static void InvokeBeforeLoad() { BeforeLoad?.Invoke(); } public delegate void BeforeSetupContentHandler(); public static event BeforeSetupContentHandler BeforeSetupContent; internal static void InvokeBeforeSetupContent() { BeforeSetupContent?.Invoke(); } public delegate void PostSetupContentHandler(); public static event PostSetupContentHandler PostSetupContent; internal static void InvokePostSetupContent() { PostSetupContent?.Invoke(); } public delegate void GameUpdateHandler(GameTime gameTime); public static event GameUpdateHandler GameUpdate; internal static void InvokeOnGameUpdate(GameTime gameTime) { GameUpdate?.Invoke(gameTime); } public delegate void PostDrawHandler(GameTime gameTime); public static event PostDrawHandler PostDraw; internal static void InvokeOnPostDraw(GameTime gameTime) { PostDraw?.Invoke(gameTime); } } } ================================================ FILE: Localizer/Lang/Lang.cs ================================================ using System.Collections.Generic; using Terraria.Localization; using Terraria.ModLoader; // ReSharper disable once CheckNamespace namespace Localizer { public static class Lang { private static List _keys = new List() { "NewVersion", "PackageManage", "Reload", "ReloadDesc", "OpenFolder", "OpenFolderDesc", "NoPackageFound", "PackageEnabled", "PackageDisabled", "PackageDisplay", "RefreshOnline", "RefreshOnlineDesc", "PackageOnline", "Export", "ExportDesc", "ExportWithTranslation", "ExportWithTranslationDesc", "PackageUpdate", "PackageLoading", "OpenUI", "TranslatedBy" }; private static Dictionary _en = new Dictionary() { { _keys[0], "Found new version of Localizer: {0} \nPlease go update it." }, { _keys[1], "Package Management" }, { _keys[2], "Reload" }, { _keys[3], "Reload all packages" }, { _keys[4], "Open Localizer Folder" }, { _keys[5], "Find downloaded and exported packages" }, { _keys[6], "No localization package found for this Mod" }, { _keys[7], "Enabled" }, { _keys[8], "Disabled" }, { _keys[9], "({0}) {1} v{2} by {3}" }, { _keys[10], "Refresh" }, { _keys[11], "Refresh online package list" }, { _keys[12], "Online" }, { _keys[13], "Export" }, { _keys[14], "Export without current translation" }, { _keys[15], "Export T" }, { _keys[16], "Export with translation" }, { _keys[17], "New Version" }, { _keys[18], "Packages loading" }, { _keys[19], "{0}, Click to open {1} config" }, { _keys[20], "{0}, translated by {1}" }, }; private static Dictionary _zh = new Dictionary() { { _keys[0], "发现汉化者Mod有新版本: {0} \n请前往更新。" }, { _keys[1], "汉化包管理" }, { _keys[2], "重新加载" }, { _keys[3], "重新读取所有汉化包" }, { _keys[4], "打开文件夹" }, { _keys[5], "查找下载、导出的汉化包及配置文件" }, { _keys[6], "你没有这个Mod的汉化包,\n请下载或自己制作" }, { _keys[7], "已启用" }, { _keys[8], "未启用" }, { _keys[9], "({0}) {1} v{2} 作者:{3}" }, { _keys[10], "刷新" }, { _keys[11], "刷新在线汉化包列表" }, { _keys[12], "未下载" }, { _keys[13], "导出" }, { _keys[14], "导出不包含当前翻译的汉化包" }, { _keys[15], "导出翻译" }, { _keys[16], "导出包含翻译的汉化包" }, { _keys[17], "可更新" }, { _keys[18], "正在加载汉化包,请稍候查看或刷新" }, { _keys[19], "{0},点击打开{1}设置界面" }, { _keys[20], "{0},汉化:{1}" }, }; public static void AddModTranslations(Mod mod) { foreach (var k in _keys) { var translation = mod.CreateTranslation(k); translation.SetDefault(_en[k]); translation.AddTranslation(GameCulture.Chinese, _zh[k]); mod.AddTranslation(translation); } } public static string _(string key, params object[] args) { var value = Language.GetTextValue($"Mods.Localizer.{key}"); if (value == $"Mods.Localizer.{key}") { value = Language.GetTextValue($"Mods.!Localizer.{key}"); } return string.Format(value, args); } } } ================================================ FILE: Localizer/Localizer.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Reflection; using System.Threading.Tasks; using Harmony; using Localizer.Attributes; using Localizer.DataModel; using Localizer.DataModel.Default; using Localizer.Helpers; using Localizer.Network; using Localizer.Package.Import; using Localizer.UIs; using log4net; using Microsoft.Xna.Framework; using MonoMod.RuntimeDetour.HookGen; using Ninject; using Terraria; using Terraria.Localization; using Terraria.ModLoader; using Terraria.ModLoader.Core; using static Localizer.Lang; using File = System.IO.File; namespace Localizer { public sealed class Localizer : Mod { public static string SavePath; public static string SourcePackageDirPath; public static string DownloadPackageDirPath; public static string ConfigPath; public static Localizer Instance { get; private set; } public static ILog Log { get; private set; } public static TmodFile TmodFile { get; private set; } public static Configuration Config { get; set; } public static OperationTiming State { get; internal set; } internal static LocalizerKernel Kernel { get; private set; } internal static HarmonyInstance Harmony { get; set; } internal static MainWindow PackageUI { get; set; } internal static LoadedModWrapper LoadedLocalizer; private static Dictionary _gameCultures; private static bool _initiated = false; public Localizer() { Instance = this; LoadedLocalizer = new LoadedModWrapper("Terraria.ModLoader.Core.AssemblyManager".Type().ValueOf("loadedMods").Invoke("get_Item", "!Localizer")); this.SetField("k__BackingField", LoadedLocalizer.File); this.SetField("k__BackingField", LoadedLocalizer.Code); Log = LogManager.GetLogger(nameof(Localizer)); Harmony = HarmonyInstance.Create(nameof(Localizer)); Harmony.Patch("Terraria.ModLoader.Core.AssemblyManager", "Instantiate", prefix: NoroHelper.HarmonyMethod(() => AfterLocalizerCtorHook(null))); State = OperationTiming.BeforeModCtor; TmodFile = Instance.ValueOf("File"); Init(); _initiated = true; } private static void AfterLocalizerCtorHook(object mod) { Hooks.InvokeBeforeModCtor(mod); } private static void Init() { _gameCultures = typeof(GameCulture).ValueOf>("_legacyCultures"); ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; SavePath = "./Localizer/"; SourcePackageDirPath = SavePath + "/Source/"; DownloadPackageDirPath = SavePath + "/Download/"; ConfigPath = SavePath + "/Config.json"; Utils.EnsureDir(SavePath); Utils.EnsureDir(SourcePackageDirPath); Utils.EnsureDir(DownloadPackageDirPath); LoadConfig(); AddModTranslations(Instance); Kernel = new LocalizerKernel(); Kernel.Init(); ModBrowser.Patches.Patch(); var autoImportService = Kernel.Get(); } public override void Load() { if (!_initiated) { throw new Exception("Localizer not initialized."); } State = OperationTiming.BeforeModLoad; Hooks.InvokeBeforeLoad(); Kernel.Get(); UIModsPatch.Patch(); } public override void PostSetupContent() { State = OperationTiming.BeforeContentLoad; Hooks.InvokeBeforeSetupContent(); CheckUpdate(); AddPostDrawHook(); } public UIHost UIHost { get; private set; } private void AddPostDrawHook() { if (Main.dedServ) { return; } UIHost = new UIHost(); Main.OnPostDraw += OnPostDraw; } private void OnPostDraw(GameTime time) { if (Main.dedServ) { return; } Main.spriteBatch.SafeBegin(); Hooks.InvokeOnPostDraw(time); try { UIHost.Update(time); UIHost.Draw(time); } catch { } if (PackageUI?.Visible ?? false) { Main.DrawCursor(Main.DrawThickCursor(false), false); } Main.spriteBatch.SafeEnd(); } public override void PostAddRecipes() { State = OperationTiming.PostContentLoad; Hooks.InvokePostSetupContent(); } public override void UpdateUI(GameTime gameTime) { Hooks.InvokeOnGameUpdate(gameTime); } public void CheckUpdate() { Task.Run(() => { var curVersion = Version; if (Kernel.Get().CheckUpdate(curVersion, out var updateInfo)) { var msg = _("NewVersion", updateInfo.Version); if (Main.gameMenu) { UI.ShowInfoMessage(msg, 0); } else { Main.NewText(msg, Color.Red); } } }); } public override void Unload() { try { SaveConfig(); // MonoModHooks.RemoveAll use mod.Name to unload the mod assembly LoadedLocalizer.File.SetField("k__BackingField", "!Localizer"); LoadedLocalizer.SetField("name", "!Localizer"); PackageUI?.Close(); UIHost.Dispose(); Main.OnPostDraw -= OnPostDraw; HookEndpointManager.RemoveAllOwnedBy(this); Harmony.UnpatchAll(nameof(Localizer)); Harmony.UnpatchAll(nameof(Patches)); Kernel.Dispose(); PackageUI = null; Harmony = null; Kernel = null; _gameCultures = null; Config = null; Instance = null; } catch (Exception e) { Log.Error(e); } finally { _initiated = false; Log = null; } base.Unload(); } public static void LoadConfig() { Log.Info("Loading config"); if (File.Exists(ConfigPath)) { Config = Utils.ReadFileAndDeserializeJson(ConfigPath); if (Config is null) { Config = new Configuration(); } } else { Log.Info("No config file, creating..."); Config = new Configuration(); } Utils.SerializeJsonAndCreateFile(Config, ConfigPath); Log.Info("Config loaded"); } public static void SaveConfig() { Log.Info("Saving config..."); Utils.SerializeJsonAndCreateFile(Config, ConfigPath); Log.Info("Config saved"); } public static GameCulture AddGameCulture(CultureInfo culture) { return GameCulture.FromName(culture.Name) != null ? null : new GameCulture(culture.Name, _gameCultures.Count); } public static GameCulture CultureInfoToGameCulture(CultureInfo culture) { var gc = GameCulture.FromName(culture.Name); return gc ?? AddGameCulture(culture); } public static void RefreshLanguages() { Kernel.Get().Refresh(); } public static IMod GetWrappedMod(string name) { if (State < OperationTiming.PostContentLoad) { var loadedMods = "Terraria.ModLoader.Core.AssemblyManager".Type().ValueOf("loadedMods"); return (bool)loadedMods.Invoke("ContainsKey", name) ? new LoadedModWrapper(loadedMods.Invoke("get_Item", name)) : null; } var mod = Utils.GetModByName(name); if (mod is null) { return null; } return new ModWrapper(mod); } public static bool CanDoOperationNow(Type t) { var attribute = t.GetCustomAttribute(); return attribute == null || CanDoOperationNow(attribute.Timing); } public static bool CanDoOperationNow(OperationTiming t) { return (t & State) != 0; } } } ================================================ FILE: Localizer/Localizer.csproj ================================================  Localizer net45 x86 7.3 1.2.0.1 3.3.4 {205c6e4a-4f9c-44fe-bb81-48f9914f048f} Squid ================================================ FILE: Localizer/Localizer.csproj.DotSettings ================================================  True ================================================ FILE: Localizer/LocalizerKernel.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Localizer.Modules; using Ninject; using Ninject.Modules; namespace Localizer { public sealed class LocalizerKernel : StandardKernel { public List Plugins { get; private set; } public Dictionary PluginEnableStatus { get; private set; } private static readonly string ExternalPluginDirPath = "./Localizer/Plugins/"; public LocalizerKernel() { AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolveHandler; Plugins = new List(); PluginEnableStatus = new Dictionary(); } public void Init() { Load(new NinjectModule[] { new DefaultPackageModule(), new DefaultNetworkModule(), }); LoadPlugins(); } public override void Dispose(bool disposing) { if (!IsDisposed) { AppDomain.CurrentDomain.AssemblyResolve -= AssemblyResolveHandler; if (disposing) { UnloadAllPlugins(); Plugins = null; } } base.Dispose(disposing); } internal void UnloadAllPlugins() { foreach (var plugin in Plugins) { plugin.Dispose(); } Plugins.Clear(); } internal void LoadPlugins() { Utils.EnsureDir(ExternalPluginDirPath); var dirInfo = new DirectoryInfo(ExternalPluginDirPath); foreach (var file in dirInfo.GetFiles("*.dll")) { var a = Assembly.Load(File.ReadAllBytes(file.FullName)); LoadPlugin(a); } } internal void LoadPlugin(Assembly asm) { try { foreach (var type in asm.GetExportedTypes()) { if (type.IsSubclassOf(typeof(LocalizerPlugin)) && type.IsPublic && !type.IsAbstract) { var instance = (LocalizerPlugin)Activator.CreateInstance(type); Plugins.Add(instance); instance.Initialize(this); Utils.LogInfo($"Plugin [{instance.Name}] loaded."); } } } catch (Exception e) { Utils.LogError($"Error occured when loading Plugin [{asm.GetName()}]. \nError: {e}"); } } internal void UnloadPlugin(string pluginName) { if (string.IsNullOrWhiteSpace(pluginName)) { throw new ArgumentException(nameof(pluginName)); } var plugin = Plugins.SingleOrDefault(p => p.Name == pluginName) ?? throw new Exception($"Cannot find plugin [{pluginName}]"); UnloadPlugin(plugin); } internal void UnloadPlugin(LocalizerPlugin plugin) { if (plugin is null) { Utils.LogWarn("Plugin cannot be unloaded because it's null"); return; } if (Plugins.Contains(plugin)) { Utils.LogWarn($"Plugin [{plugin.Name}] doesn't exist"); return; } plugin.Dispose(); Plugins.Remove(plugin); Utils.LogInfo($"Plugin [{plugin.Name}] successfully unloaded."); } private static Assembly AssemblyResolveHandler(object sender, ResolveEventArgs args) { try { var asmName = new AssemblyName(args.Name); if (asmName.Name == "Localizer") { return Localizer.Instance.Code; } var referencedAsm = Assembly.GetExecutingAssembly().GetReferencedAssemblies() .FirstOrDefault(a => a.Name.StartsWith($"!Localizer_{asmName.Name}_")); if (referencedAsm != null) { return Assembly.Load(referencedAsm); } var fileName = asmName.Name + ".dll"; var asmFile = GetExternalPluginFileBytes(fileName); if (asmFile != null && asmFile.Length != 0) { return Assembly.Load(asmFile); } return null; } catch (Exception) { return null; } } private static byte[] GetExternalPluginFileBytes(string fileName) { var path = Path.Combine(ExternalPluginDirPath, fileName); if (!File.Exists(path)) { return null; } return File.ReadAllBytes(path); } } } ================================================ FILE: Localizer/LocalizerPlugin.cs ================================================ using System; namespace Localizer { public abstract class LocalizerPlugin : Disposable { public abstract string Name { get; } public abstract string Author { get; } public virtual Version Version => new Version(); public abstract string Description { get; } public abstract void Initialize(LocalizerKernel kernel); } } ================================================ FILE: Localizer/ModBrowser/Patches.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using System.Reflection.Emit; using System.Text.RegularExpressions; using Harmony; using Terraria.Localization; using Terraria.ModLoader; namespace Localizer.ModBrowser { public static class Patches { public static HarmonyInstance HarmonyInstance { get; set; } public static void Patch() { Utils.LogInfo($"Patching ModBrowser, tML version: {ModLoader.version}"); HarmonyInstance = HarmonyInstance.Create(nameof(Patches)); if (LanguageManager.Instance.ActiveCulture == GameCulture.Chinese) { try { #region Download Mod List if (!string.IsNullOrEmpty(GetModListURL())) { HarmonyInstance.Patch("Terraria.ModLoader.UI.ModBrowser.UIModBrowser", "", exactMatch: false, transpiler: NoroHelper.HarmonyMethod(() => PopulateModBrowserTranspiler(null))); Utils.LogInfo("PopulateModBrowser Patched"); } #endregion #region Get Mod Download URL if (!string.IsNullOrEmpty(GetModDownloadURL())) { HarmonyInstance.Patch("Terraria.ModLoader.UI.ModBrowser.UIModDownloadItem", "FromJson", transpiler: NoroHelper.HarmonyMethod(() => FromJSONTranspiler(null))); Utils.LogInfo("FromJson Patched"); if (!string.IsNullOrEmpty(GetModDescURL())) { HarmonyInstance.Patch("Terraria.ModLoader.UI.UIModInfo", "", exactMatch: false, transpiler: NoroHelper.HarmonyMethod(() => OnActivateTranspiler(null))); Utils.LogInfo("OnActivate Patched"); } } #endregion #region List My Mods // Terraria.ModLoader.UI.UIManagePublished.OnActivate // "http://javid.ddns.net/tModLoader/listmymods.php" #endregion #region Publish Mod // Terraria.ModLoader.UI.UIModSourceItem.PublishMod // "http://javid.ddns.net/tModLoader/publishmod.php" #endregion #region Unpublish Mod // Terraria.ModLoader.UI.UIModManageItem.UnpublishMod // "http://javid.ddns.net/tModLoader/unpublishmymod.php" #endregion #region Register Link // Terraria.ModLoader.UI.UIEnterPassphraseMenu.VisitRegisterWebpage // Terraria.ModLoader.UI.UIEnterSteamIDMenu.VisitRegisterWebpage // "http://javid.ddns.net/tModLoader/register.php" #endregion #region Direct Mod Listing // Terraria.ModLoader.UI.ModBrowser.UIModBrowser.<>c. // "http://javid.ddns.net/tModLoader/DirectModDownloadListing.php" HarmonyInstance.Patch("Terraria.ModLoader.UI.ModBrowser.UIModBrowser.<>c", "", exactMatch: false, transpiler: NoroHelper.HarmonyMethod(() => DirectModListingTranspiler(null))); Utils.LogInfo("DirectModListing Patched"); #endregion #region Query Mod Download URL // Terraria.ModLoader.Interface.ServerModBrowserMenu // "http://javid.ddns.net/tModLoader/tools/querymoddownloadurl.php?modname=" #endregion #region Error Report // No plan #endregion #region ModCompile HarmonyInstance.Patch("Terraria.ModLoader.UI.UIDeveloperModeHelp", "DownloadModCompile", transpiler: NoroHelper.HarmonyMethod(() => ModCompileTranspiler(null))); Utils.LogInfo("DownloadModCompile Patched"); #endregion #region Mod Update HarmonyInstance.Patch("Terraria.ModLoader.UI.DownloadManager.DownloadModFile", "PreCopy", prefix: NoroHelper.HarmonyMethod(() => PreCopyPrefix(null))); Utils.LogInfo("PreCopy Patched"); #endregion Utils.LogInfo("ModBrowser Patched"); } catch (Exception e) { Utils.LogInfo($"ModBrowser Patch exception: {e}"); } } try { HarmonyInstance.Patch("Terraria.ModLoader.UI.DownloadManager.DownloadFile", "SetupDownloadRequest", postfix: NoroHelper.HarmonyMethod(() => PostSetupDownloadRequest(null))); Utils.LogInfo("SetupDownloadRequest Patched"); } catch (Exception e) { Utils.LogInfo($"ModBrowser Patch exception: {e}"); } } private static readonly Regex _defaultMirror = new Regex(@"mirror(?:\d*)?\.sgkoi\.dev"); private static string GetModListURL() { var mirror = Localizer.Config.ModListMirror[0]; switch (mirror) { case "mirror2.sgkoi.dev": return "http://www.mb.axeel.moe/tModLoader/listmods.php"; case "mirror3.sgkoi.dev": return "https://trbbs.cc/trmod/listmods.php"; case "mirror4.sgkoi.dev": return "http://www.mb2.axeel.moe:25555/tModLoader/listmods.php"; default: return _defaultMirror.IsMatch(mirror) ? $"https://{mirror}/tModLoader/listmods.php" : mirror; } } private static string GetModDownloadURL() { var mirror = Localizer.Config.ModDownloadMirror[0]; switch (mirror) { case "mirror2.sgkoi.dev": return "http://www.mb.axeel.moe/tModLoader/download.php?Down=mods/"; case "mirror3.sgkoi.dev": return "https://trbbs.cc/trmod/"; case "mirror4.sgkoi.dev": return "http://www.mb2.axeel.moe:25555/tModLoader/download.php?Down=mods/"; default: return _defaultMirror.IsMatch(mirror) ? $"https://{mirror}/tModLoader/download.php?Down=mods/" : mirror; } } private static string GetModDescURL() { var mirror = Localizer.Config.ModDescMirror[0]; switch (mirror) { case "mirror2.sgkoi.dev": return "http://www.mb.axeel.moe/tModLoader/moddescription.php"; case "mirror4.sgkoi.dev": return "http://www.mb2.axeel.moe:25555/tModLoader/moddescription.php"; default: return _defaultMirror.IsMatch(mirror) ? $"https://{mirror}/tModLoader/moddescription.php" : mirror; } } private static void PreCopyPrefix(object ___ModBrowserItem) { if (___ModBrowserItem.ValueOf("ModName") == "Localizer") { ___ModBrowserItem.SetField("ModName", "!Localizer"); } } private static void PostSetupDownloadRequest(object __instance) { var request = __instance.ValueOf("k__BackingField"); request.UserAgent = Utils.UserAgent(false); request.Headers[HttpRequestHeader.AcceptLanguage] = LanguageManager.Instance.ActiveCulture.CultureInfo.ToString(); } public static void UpdateHeader(WebClient wc) { wc.Headers[HttpRequestHeader.UserAgent] = Utils.UserAgent(false); wc.Headers[HttpRequestHeader.AcceptLanguage] = LanguageManager.Instance.ActiveCulture.CultureInfo.ToString(); } private static IEnumerable PopulateModBrowserTranspiler(IEnumerable instructions) { var result = instructions.ToList(); ReplaceLdstr("http://javid.ddns.net/tModLoader/listmods.php", GetModListURL(), result); for (int i = 0; i < result.Count; i++) { if (result[i].opcode == OpCodes.Callvirt && $"{result[i].operand}".Contains("UploadValuesCompleted")) { result.Insert(i + 1, new CodeInstruction(result[i + 1])); result.Insert(i + 2, new CodeInstruction(OpCodes.Call, NoroHelper.MethodInfo(() => UpdateHeader(null)))); break; } } return result; } private static IEnumerable FromJSONTranspiler(IEnumerable instructions) { var result = instructions.ToList(); ReplaceLdstr("http://javid.ddns.net/tModLoader/download.php?Down=mods/", GetModDownloadURL(), result); ReplaceLdstr("&tls12=y", "", result); return result; } private static IEnumerable OnActivateTranspiler(IEnumerable instructions) { var result = instructions.ToList(); ReplaceLdstr("http://javid.ddns.net/tModLoader/download.php?Down=mods/", GetModDownloadURL(), result); ReplaceLdstr("http://javid.ddns.net/tModLoader/moddescription.php", GetModDescURL(), result); return result; } private static IEnumerable DirectModListingTranspiler(IEnumerable instructions) { var result = instructions.ToList(); ReplaceLdstr("http://javid.ddns.net/tModLoader/DirectModDownloadListing.php", "https://mirror.sgkoi.dev/", result); return result; } private static IEnumerable ModCompileTranspiler(IEnumerable instructions) { var result = instructions.ToList(); for (int i = 0; i < result.Count; i++) { if (result[i].opcode == OpCodes.Ldstr && $"{result[i].operand}" == "https://github.com/tModLoader/tModLoader/releases/download/") { result[i].operand = "https://mirror.sgkoi.dev/direct"; result[i + 1] = new CodeInstruction(OpCodes.Ldstr, ""); } } return result; } private static void ReplaceLdstr(string o, string n, IEnumerable il) { var ins = il.FirstOrDefault(i => i?.operand?.ToString() == o); if (ins != null) { ins.operand = n; } } } } ================================================ FILE: Localizer/Modules/DefaultNetworkModule.cs ================================================ using Localizer.Network; using Ninject.Modules; namespace Localizer.Modules { public class DefaultNetworkModule : NinjectModule { public override void Load() { Bind().To().InSingletonScope(); Bind().To().InSingletonScope(); Bind().To().InSingletonScope(); } } } ================================================ FILE: Localizer/Modules/DefaultPackageModule.cs ================================================ using System; using System.Reflection; using Localizer.DataModel; using Localizer.DataModel.Default; using Localizer.Package; using Localizer.Package.Export; using Localizer.Package.Import; using Localizer.Package.Load; using Localizer.Package.Pack; using Localizer.Package.Save; using Localizer.Package.Update; using Ninject; using Ninject.Modules; namespace Localizer.Modules { public class DefaultPackageModule : NinjectModule { public override void Load() { BindLoadService(); BindManageService(); BindImportService(); BindSaveService(); BindPackService(); BindExportService(); BindUpdateService(); } public override void Unload() { Kernel.Get().Dispose(); Kernel.Get().Dispose(); Kernel.Get().Dispose(); } private void BindLoadService() { Bind().To().InSingletonScope(); Bind>() .To>().InSingletonScope(); Bind>().ToSelf().InSingletonScope(); Bind>() .To>().InSingletonScope(); Bind>().ToSelf().InSingletonScope(); } private void BindManageService() { Bind().To(); } private void BindImportService() { Bind().To().InSingletonScope(); var packageImportService = Kernel.Get(); if (Localizer.Config.ImporBasictAfterSetupContent) { packageImportService.RegisterImporter(typeof(BasicImporterPostContentLoad)); packageImportService.RegisterImporter(typeof(BasicImporterPostContentLoad)); packageImportService.RegisterImporter(typeof(BasicImporterPostContentLoad)); packageImportService.RegisterImporter(typeof(BasicImporterPostContentLoad)); packageImportService.RegisterImporter(typeof(BasicImporterPostContentLoad)); } else { packageImportService.RegisterImporter(typeof(BasicImporterBeforeContentLoad)); packageImportService.RegisterImporter(typeof(BasicImporterBeforeContentLoad)); packageImportService.RegisterImporter(typeof(BasicImporterBeforeContentLoad)); packageImportService.RegisterImporter(typeof(BasicImporterBeforeContentLoad)); packageImportService.RegisterImporter(typeof(BasicImporterBeforeContentLoad)); } packageImportService.RegisterImporter(typeof(CustomModTranslationImporter)); if (!string.IsNullOrWhiteSpace(Localizer.Config.LdstrImporter)) { packageImportService.RegisterImporter(Assembly.GetExecutingAssembly().GetType($"Localizer.Package.Import.{Localizer.Config.LdstrImporter}LdstrImporter")); } else { packageImportService.RegisterImporter(typeof(CecilLdstrImporter)); } Bind().ToSelf().InSingletonScope(); Bind().ToSelf().InSingletonScope(); } private void BindSaveService() { Bind().To().InSingletonScope(); Bind().To().InSingletonScope(); } private void BindPackService() { Bind().To>().InSingletonScope(); Bind>().ToSelf().InSingletonScope(); } private void BindExportService() { Bind().To().InSingletonScope(); Bind().To>().InSingletonScope(); Bind().To>().InSingletonScope(); Bind().To>().InSingletonScope(); Bind().To>().InSingletonScope(); Bind().To>().InSingletonScope(); Bind().To().InSingletonScope(); Bind().To().InSingletonScope(); } private void BindUpdateService() { void BindUpdate(Type serviceType) where T : IFile { var updateService = Kernel.Get(); Bind(typeof(FileUpdater), serviceType).To(serviceType).InSingletonScope(); updateService.RegisterUpdater(Kernel.Get(serviceType) as FileUpdater); } Bind().To().InSingletonScope(); BindUpdate(typeof(BasicFileUpdater)); BindUpdate(typeof(BasicFileUpdater)); BindUpdate(typeof(BasicFileUpdater)); BindUpdate(typeof(BasicFileUpdater)); BindUpdate(typeof(BasicFileUpdater)); BindUpdate(typeof(CustomModTranslationUpdater)); BindUpdate(typeof(LdstrFileUpdater)); Bind().To(); } } } ================================================ FILE: Localizer/Network/DownloadManager.cs ================================================ using System; using System.Net; namespace Localizer.Network { public class DownloadManager : IDownloadManagerService { public void Download(string url, string path) { var wc= new WebClient(); wc.Headers[HttpRequestHeader.UserAgent] = Utils.UserAgent(); wc.Headers[HttpRequestHeader.AcceptLanguage] = Terraria.Localization.LanguageManager.Instance.ActiveCulture.CultureInfo.ToString(); wc.DownloadFile(new Uri(url), path); } public void Dispose() { } } } ================================================ FILE: Localizer/Network/GitHubModUpdate.cs ================================================ using System; using System.Collections.Generic; using Localizer.DataModel; using Localizer.DataModel.Default; using Newtonsoft.Json.Linq; namespace Localizer.Network { public sealed class GitHubModUpdate : IUpdateService { private JObject lastCheckResult; public bool CheckUpdate(Version curVersion, out IUpdateInfo updateInfo) { var url = "https://api.github.com/repos/chi-rei-den/Localizer/releases/latest"; var response = Utils.GET(url); lastCheckResult = JObject.Parse(Utils.GetResponseBody(response)); updateInfo = GetUpdateInfo(lastCheckResult); if (updateInfo.Type == UpdateType.None) { return false; } return updateInfo.Version > curVersion; } internal GitHubUpdateInfo GetUpdateInfo(JObject jObject) { return new GitHubUpdateInfo(jObject["tag_name"].ToObject()); } public Dictionary GetChangeLog(Version from, Version to) { throw new NotImplementedException(); } public string GetDownloadURL() { return GetDownloadURLInternal(lastCheckResult); } internal string GetDownloadURLInternal(JObject jObject) { var assets = jObject["assets"] as JArray; if (assets == null || assets.Count == 0) { throw new Exception("Release has no assets!"); } return assets[0]["browser_download_url"].ToObject(); } public void Dispose() { } } } ================================================ FILE: Localizer/Network/IDownloadManagerService.cs ================================================ namespace Localizer.Network { public interface IDownloadManagerService { void Download(string url, string path); } } ================================================ FILE: Localizer/Network/IPackageBrowserService.cs ================================================ using System.Collections.Generic; using Localizer.DataModel; namespace Localizer.Network { public interface IPackageBrowserService { ICollection GetList(); int GetPageCount(); ICollection GetListByPage(int i); string GetDownloadLinkOf(IPackage package); } } ================================================ FILE: Localizer/Network/IUpdateService.cs ================================================ using System; using System.Collections.Generic; using Localizer.DataModel; namespace Localizer.Network { public interface IUpdateService { bool CheckUpdate(Version curVersion, out IUpdateInfo updateInfo); Dictionary GetChangeLog(Version from, Version to); string GetDownloadURL(); } } ================================================ FILE: Localizer/Network/PackageBrowser.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using Localizer.DataModel; using Newtonsoft.Json.Linq; namespace Localizer.Network { public class PackageBrowser : IPackageBrowserService { #if DEBUG public string serverURL = "http://127.0.0.1:8000/api/"; #else public string serverURL = "https://mirror.sgkoi.dev/Localizer/"; #endif private Dictionary packages = new Dictionary(); public ICollection GetList() { packages.Clear(); var result = new List(); var response = Utils.GET($"{serverURL}List"); var jArray = JArray.Parse(Utils.GetResponseBody(response)); foreach (JObject jo in jArray) { Utils.SafeWrap(() => { var pack = new DataModel.Default.Package() { Name = jo["name"].ToObject(), Author = jo["author"].ToObject(), Version = jo["version"].ToObject(), ModName = jo["mod"].ToObject(), Language = jo["language"].ToObject(), Description = jo["description"].ToObject(), }; packages.Add(pack, jo["id"].Value()); result.Add(pack); }); } return result; } public int GetPageCount() { throw new NotImplementedException(); } public ICollection GetListByPage(int i) { throw new NotImplementedException(); } public string GetDownloadLinkOf(IPackage package) { if (!packages.ContainsKey(package)) { return null; } return $"{serverURL}Download/{packages[package]}"; } public void Dispose() { } } } ================================================ FILE: Localizer/Package/Export/BasicFileExport.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using Localizer.DataModel; using Localizer.DataModel.Default; using Localizer.Helpers; using Terraria.ModLoader; namespace Localizer.Package.Export { public sealed class BasicFileExport : IFileExportService where T : IFile { public void Export(IPackage package, IExportConfig config) { var modName = package.ModName; var mod = Utils.GetModByName(modName); if (mod == null) { return; } var file = Activator.CreateInstance(typeof(T)) as IFile; foreach (var prop in typeof(T).ModTranslationOwnerField()) { var fieldName = prop.ModTranslationOwnerFieldName(); var field = mod.ValueOf(fieldName); var entryType = prop.PropertyType.GenericTypeArguments .FirstOrDefault(g => g.GetInterfaces().Contains(typeof(IEntry))); var entries = CreateEntries(field, entryType, package.Language, config.WithTranslation); var entriesOfFile = (IDictionary)prop.GetValue(file); foreach (var e in entries) { entriesOfFile.Add(e.Key, e.Value); } } package.AddFile(file); } private Dictionary CreateEntries(IDictionary localizeOwners, Type entryType, CultureInfo lang, bool withTranslation) { var entries = new Dictionary(); var mappings = Utils.CreateEntryMappings(entryType); foreach (string key in localizeOwners.Keys) { var entry = Activator.CreateInstance(entryType); foreach (var mapping in mappings) { var owner = localizeOwners[key]; var localizeTrans = owner?.GetType().GetProperty(mapping.Key)?.GetValue(owner) as ModTranslation; mapping.Value.SetValue(entry, new BaseEntry { Origin = localizeTrans.DefaultOrEmpty(), Translation = withTranslation ? localizeTrans?.GetTranslation(lang) : "" }); } entries.Add(key, entry); } return entries; } } } ================================================ FILE: Localizer/Package/Export/CustomModTranslationFileExport.cs ================================================ using System.Collections.Generic; using System.Reflection; using Localizer.DataModel; using Localizer.DataModel.Default; using Localizer.Helpers; using Terraria.ModLoader; namespace Localizer.Package.Export { public class CustomModTranslationFileExport : IFileExportService { public void Export(IPackage package, IExportConfig config) { if (package?.Mod == null) { return; } var translations = Utils.GetModByName(package.ModName).ValueOf>("translations"); if (translations == null) { return; } var file = new CustomModTranslationFile { Translations = new Dictionary() }; foreach (var translation in translations) { file.Translations.Add(translation.Key, new BaseEntry { Origin = translation.Value.DefaultOrEmpty(), Translation = config.WithTranslation ? translation.Value?.GetTranslation(package.Language) : "" }); } package.AddFile(file); } public void Dispose() { } } } ================================================ FILE: Localizer/Package/Export/IFileExportService.cs ================================================ using Localizer.DataModel; namespace Localizer.Package.Export { public interface IFileExportService { /// /// Extract texts from mod and add them into the package. /// /// /// void Export(IPackage package, IExportConfig config); } } ================================================ FILE: Localizer/Package/Export/IPackageExportService.cs ================================================ using Localizer.DataModel; namespace Localizer.Package.Export { public interface IPackageExportService { /// /// Extract texts from the mod and fill up the package's file list. /// /// Package with necessary information. /// void Export(IPackage package, IExportConfig config); } } ================================================ FILE: Localizer/Package/Export/LdstrFileExport.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Localizer.DataModel; using Localizer.DataModel.Default; using Mono.Cecil; using MonoMod.Utils; using Terraria.ModLoader; using static Localizer.Utils; using OpCodes = Mono.Cecil.Cil.OpCodes; namespace Localizer.Package.Export { public sealed class LdstrFileExport : IFileExportService { private static List _blackList1 = new List { GetMethodBase( "System.String Terraria.ModLoader.ModTranslation::GetTranslation(System.String)"), GetMethodBase( "System.Void Terraria.ModLoader.ModTranslation::AddTranslation(System.Int32,System.String)"), GetMethodBase( "System.Void Terraria.ModLoader.ModTranslation::AddTranslation(System.String,System.String)"), GetMethodBase( "System.Void Terraria.ModLoader.ModTranslation::AddTranslation(Terraria.Localization.GameCulture,System.String)"), GetMethodBase( "Microsoft.Xna.Framework.Graphics.Texture2D Terraria.ModLoader.Mod::GetTexture(System.String)"), GetMethodBase( "Microsoft.Xna.Framework.Audio.SoundEffect Terraria.ModLoader.Mod::GetSound(System.String)"), GetMethodBase("Terraria.ModLoader.Audio.Music Terraria.ModLoader.Mod::GetMusic(System.String)"), GetMethodBase("ReLogic.Graphics.DynamicSpriteFont Terraria.ModLoader.Mod::GetFont(System.String)"), GetMethodBase( "Microsoft.Xna.Framework.Graphics.Effect Terraria.ModLoader.Mod::GetEffect(System.String)"), GetMethodBase( "Terraria.ModLoader.Config.ModConfig Terraria.ModLoader.Mod::GetConfig(System.String)"), GetMethodBase( "Terraria.ModLoader.GlobalProjectile Terraria.ModLoader.Mod::GetGlobalProjectile(System.String)"), GetMethodBase("Terraria.ModLoader.ModNPC Terraria.ModLoader.Mod::GetNPC(System.String)"), GetMethodBase("System.Int32 Terraria.ModLoader.Mod::NPCType(System.String)"), GetMethodBase("Terraria.ModLoader.GlobalNPC Terraria.ModLoader.Mod::GetGlobalNPC(System.String)"), GetMethodBase("Terraria.ModLoader.ModPlayer Terraria.ModLoader.Mod::GetPlayer(System.String)"), GetMethodBase("Terraria.ModLoader.ModBuff Terraria.ModLoader.Mod::GetBuff(System.String)"), GetMethodBase("System.Int32 Terraria.ModLoader.Mod::BuffType(System.String)"), GetMethodBase( "Terraria.ModLoader.GlobalBuff Terraria.ModLoader.Mod::GetGlobalBuff(System.String)"), GetMethodBase("Terraria.ModLoader.ModMountData Terraria.ModLoader.Mod::GetMount(System.String)"), GetMethodBase("System.Int32 Terraria.ModLoader.Mod::MountType(System.String)"), GetMethodBase("Terraria.ModLoader.ModWorld Terraria.ModLoader.Mod::GetModWorld(System.String)"), GetMethodBase( "Terraria.ModLoader.ModUgBgStyle Terraria.ModLoader.Mod::GetUgBgStyle(System.String)"), GetMethodBase( "Terraria.ModLoader.ModSurfaceBgStyle Terraria.ModLoader.Mod::GetSurfaceBgStyle(System.String)"), GetMethodBase("System.Int32 Terraria.ModLoader.Mod::GetSurfaceBgStyleSlot(System.String)"), GetMethodBase( "Terraria.ModLoader.GlobalBgStyle Terraria.ModLoader.Mod::GetGlobalBgStyle(System.String)"), GetMethodBase( "Terraria.ModLoader.ModWaterStyle Terraria.ModLoader.Mod::GetWaterStyle(System.String)"), GetMethodBase( "Terraria.ModLoader.ModWaterfallStyle Terraria.ModLoader.Mod::GetWaterfallStyle(System.String)"), GetMethodBase("System.Int32 Terraria.ModLoader.Mod::GetWaterfallStyleSlot(System.String)"), GetMethodBase("System.Int32 Terraria.ModLoader.Mod::GetGoreSlot(System.String)"), GetMethodBase("System.Void Terraria.ModLoader.Mod::AddBackgroundTexture(System.String)"), GetMethodBase("System.Int32 Terraria.ModLoader.Mod::GetBackgroundSlot(System.String)"), GetMethodBase( "Terraria.ModLoader.ModTranslation Terraria.ModLoader.Mod::CreateTranslation(System.String)"), GetMethodBase("System.Byte[] Terraria.ModLoader.Mod::GetFileBytes(System.String)"), GetMethodBase("Terraria.ModLoader.ModItem Terraria.ModLoader.Mod::GetItem(System.String)"), GetMethodBase("System.Int32 Terraria.ModLoader.Mod::ItemType(System.String)"), GetMethodBase( "Terraria.ModLoader.GlobalItem Terraria.ModLoader.Mod::GetGlobalItem(System.String)"), GetMethodBase("Terraria.ModLoader.ModPrefix Terraria.ModLoader.Mod::GetPrefix(System.String)"), GetMethodBase("System.Byte Terraria.ModLoader.Mod::PrefixType(System.String)"), GetMethodBase("Terraria.ModLoader.ModDust Terraria.ModLoader.Mod::GetDust(System.String)"), GetMethodBase("System.Int32 Terraria.ModLoader.Mod::DustType(System.String)"), GetMethodBase("Terraria.ModLoader.ModTile Terraria.ModLoader.Mod::GetTile(System.String)"), GetMethodBase("System.Int32 Terraria.ModLoader.Mod::TileType(System.String)"), GetMethodBase( "Terraria.ModLoader.GlobalTile Terraria.ModLoader.Mod::GetGlobalTile(System.String)"), GetMethodBase( "Terraria.ModLoader.ModTileEntity Terraria.ModLoader.Mod::GetTileEntity(System.String)"), GetMethodBase("System.Int32 Terraria.ModLoader.Mod::TileEntityType(System.String)"), GetMethodBase("Terraria.ModLoader.ModWall Terraria.ModLoader.Mod::GetWall(System.String)"), GetMethodBase("System.Int32 Terraria.ModLoader.Mod::WallType(System.String)"), GetMethodBase( "Terraria.ModLoader.GlobalWall Terraria.ModLoader.Mod::GetGlobalWall(System.String)"), GetMethodBase( "Terraria.ModLoader.ModProjectile Terraria.ModLoader.Mod::GetProjectile(System.String)"), GetMethodBase("System.Int32 Terraria.ModLoader.Mod::ProjectileType(System.String)"), typeof(ModContent).FindMethod( "Microsoft.Xna.Framework.Audio.SoundEffect Terraria.ModLoader.ModContent::GetSound(System.String)"), typeof(ModContent).FindMethod("System.Byte[] Terraria.ModLoader.ModContent::GetFileBytes(System.String)"), typeof(ModContent).FindMethod("System.Boolean Terraria.ModLoader.ModContent::FileExists(System.String)"), typeof(ModContent).FindMethod( "Microsoft.Xna.Framework.Graphics.Texture2D Terraria.ModLoader.ModContent::GetTexture(System.String)"), typeof(ModContent).FindMethod("System.Boolean Terraria.ModLoader.ModContent::TextureExists(System.String)"), typeof(ModContent).FindMethod( "Microsoft.Xna.Framework.Audio.SoundEffect Terraria.ModLoader.ModContent::GetSound(System.String)"), typeof(ModContent).FindMethod("System.Boolean Terraria.ModLoader.ModContent::SoundExists(System.String)"), typeof(ModContent).FindMethod( "Terraria.ModLoader.Audio.Music Terraria.ModLoader.ModContent::GetMusic(System.String)"), typeof(ModContent).FindMethod("System.Boolean Terraria.ModLoader.ModContent::MusicExists(System.String)"), typeof(ModContent).FindMethod( "System.Int32 Terraria.ModLoader.ModContent::GetModBossHeadSlot(System.String)"), typeof(ModContent).FindMethod("System.Int32 Terraria.ModLoader.ModContent::GetModHeadSlot(System.String)"), typeof(ModContent).FindMethod( "System.Int32 Terraria.ModLoader.ModContent::GetModBackgroundSlot(System.String)"), typeof(ModContent).FindMethod("System.Boolean Terraria.ModLoader.ModContent::SoundExists(System.String)"), typeof(ModContent).FindMethod("System.Boolean Terraria.ModLoader.ModContent::SoundExists(System.String)"), typeof(ModContent).FindMethod("System.Boolean Terraria.ModLoader.ModContent::SoundExists(System.String)"), GetMethodBase( "System.Void Terraria.ModLoader.ModRecipe::AddTile(Terraria.ModLoader.Mod,System.String)"), typeof(ModLoader).FindMethod("Terraria.ModLoader.Mod Terraria.ModLoader.ModLoader::GetMod(System.String)"), }; private static List _blackList2 = new List { GetMethodBase( "System.Void Terraria.ModLoader.ModRecipe::AddIngredient(Terraria.ModLoader.Mod,System.String,System.Int32)"), }; public void Export(IPackage package, IExportConfig config) { if (package?.Mod == null) { return; } var modFile = package.Mod.File; var asmManager = "Terraria.ModLoader.Core.AssemblyManager".Type(); var assemblyName = (string)asmManager.Invoke("GetModAssemblyFileName", modFile, true); var loadedMod = asmManager.ValueOf("loadedMods").Invoke("get_Item", package.Mod.Name); var reref = (byte[])asmManager.GetNestedType("LoadedMod", NoroHelper.Any).Method("EncapsulateReferences") .Invoke(loadedMod, new object[] { modFile.GetBytes(assemblyName), null }); var asm = AssemblyDefinition.ReadAssembly(new MemoryStream(reref)); var file = new LdstrFile { LdstrEntries = new Dictionary() }; foreach (var type in asm.MainModule.GetTypes()) { if (type.Namespace == null) { continue; } foreach (var method in type.Methods) { if (method.DeclaringType?.Namespace == null || method.IsAbstract) { continue; } try { LogDebug($"Exporting method: [{method.GetID()}]"); var entry = GetEntryFromMethod(method); if (entry != null && !file.LdstrEntries.ContainsKey(method.GetID())) { file.LdstrEntries.Add(method.GetID(), entry); } } catch (Exception e) { Localizer.Log.Error(e.ToString()); } } } package.AddFile(file); } private LdstrEntry GetEntryFromMethod(MethodDefinition method) { var instructions = method?.Body?.Instructions; if (instructions == null) { return null; } var entry = new LdstrEntry { Instructions = new List() }; for (var i = 0; i < instructions.Count; i++) { var ins = instructions[i]; if (ins.OpCode == OpCodes.Ldstr && !string.IsNullOrWhiteSpace(ins.Operand.ToString())) { // Filter methods in blacklist1 if (i < instructions.Count - 1) { var next = instructions[i + 1]; var operandId = ""; if (next.OpCode == OpCodes.Call || next.OpCode == OpCodes.Callvirt) { operandId = (next.Operand as MethodReference).GetID(); } else if (next.OpCode == OpCodes.Calli) { operandId = (next.Operand as CallSite).GetID(); } if (!string.IsNullOrWhiteSpace(operandId) && _blackList1.Any(m => operandId == m?.GetID())) { continue; } } // Filter methods in blacklist2 if (i < instructions.Count - 2) { var afterNext = instructions[i + 2]; var operandId = ""; if (afterNext.OpCode == OpCodes.Call || afterNext.OpCode == OpCodes.Callvirt) { operandId = (afterNext.Operand as MethodReference).GetID(); } else if (afterNext.OpCode == OpCodes.Calli) { operandId = (afterNext.Operand as CallSite).GetID(); } if (!string.IsNullOrWhiteSpace(operandId) && _blackList2.Any(m => operandId == m?.GetID())) { continue; } } // No need to add a same string if (entry.Instructions.Exists(e => e.Origin == ins.Operand.ToString())) { continue; } entry.Instructions.Add(new BaseEntry { Origin = ins.Operand.ToString(), Translation = "" }); } } return entry.Instructions.Count == 0 ? null : entry; } public void Dispose() { _blackList1 = null; _blackList2 = null; } } } ================================================ FILE: Localizer/Package/Export/PackageExport.cs ================================================ using Localizer.DataModel; using Ninject; using Terraria.ModLoader; namespace Localizer.Package.Export { public class PackageExport : IPackageExportService { public void Export(IPackage package, IExportConfig config) { var fileExportServices = Localizer.Kernel.GetAll(); if (package.Mod == null || package.Mod.GetType() != typeof(Mod)) { package.Mod = Localizer.GetWrappedMod(package.ModName); } foreach (var service in fileExportServices) { service.Export(package, config); } } } } ================================================ FILE: Localizer/Package/IPackageManageService.cs ================================================ using System.Collections.Generic; using Localizer.DataModel; namespace Localizer.Package { public interface IPackageManageService { /// /// All added packages sorted by mod. /// ICollection PackageGroups { get; set; } /// /// Add a package. /// /// void AddPackage(IPackage package); /// /// Remove a package. /// /// void RemovePackage(IPackage package); /// /// Load saved package state. /// void LoadState(); /// /// Save the package state. /// void SaveState(); } } ================================================ FILE: Localizer/Package/Import/AutoImportService.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using Localizer.DataModel; using Localizer.DataModel.Default; using Localizer.Helpers; using Localizer.Package.Load; using Localizer.Package.Pack; using Localizer.UIs; using Ninject; using PackageModel = Localizer.DataModel.Default.Package; namespace Localizer.Package.Import { public sealed class AutoImportService : Disposable { public bool Imported => _imported; private readonly IPackageManageService _packageManage; private readonly SourcePackageLoad _sourcePackageLoad; private readonly PackedPackageLoad _packedPackageLoad; private readonly IPackageImportService _packageImport; private readonly IPackagePackService _packagePack; private readonly IFileLoadService _fileLoad; private bool _imported = false; [Inject] public AutoImportService(IPackageManageService packageManage, SourcePackageLoad sourcePackageLoad, PackedPackageLoad packedPackageLoad, IPackageImportService packageImport, IPackagePackService packagePack, IFileLoadService fileLoad) { _packageManage = packageManage ?? throw new ArgumentNullException(nameof(packageManage)); _sourcePackageLoad = sourcePackageLoad ?? throw new ArgumentNullException(nameof(sourcePackageLoad)); _packedPackageLoad = packedPackageLoad ?? throw new ArgumentNullException(nameof(packedPackageLoad)); _packageImport = packageImport ?? throw new ArgumentNullException(nameof(packageImport)); _packagePack = packagePack ?? throw new ArgumentNullException(nameof(packagePack)); _fileLoad = fileLoad ?? throw new ArgumentNullException(nameof(fileLoad)); LoadPackages(); Hooks.BeforeModCtor += OnBeforeModCtor; Hooks.PostSetupContent += OnPostSetupContent; } private void OnBeforeModCtor(object mod) { if (_imported) { return; } try { if (Localizer.Config.AutoImport) { var wrapped = new LoadedModWrapper(mod); Utils.LogInfo($"Early auto import for mod: [{wrapped.Name}]"); Import(wrapped); } } catch { } } private void OnPostSetupContent() { if (_imported) { return; } try { if (Localizer.Config.AutoImport) { Utils.LogInfo($"Late auto import begin."); Import(); } } catch (Exception e) { Utils.LogError(e); } finally { _imported = true; } } private void LoadPackages() { try { _packageManage.PackageGroups = new List(); var type = Localizer.Config.AutoImportType; if (type != AutoImportType.DownloadedOnly) { LoadSourcePackages(); } if (type != AutoImportType.SourceOnly) { LoadPackedPackages(); } _packageManage.LoadState(); UIModsPatch.ModsExtraInfo = _packageManage.PackageGroups.ToDictionary(group => group.Mod.Name, group => { var localizedModName = group.Packages.FirstOrDefault(pack => !string.IsNullOrWhiteSpace(pack.LocalizedModName))?.LocalizedModName; return $"{localizedModName}{Environment.NewLine}{string.Join(Environment.NewLine, group.Packages.Select(UI.GetPkgLabelText))}"; }); } catch (Exception e) { Utils.LogError(e); } } private void LoadSourcePackages() { foreach (var dir in new DirectoryInfo(Localizer.SourcePackageDirPath).GetDirectories()) { try { var pack = _sourcePackageLoad.Load(dir.FullName, _fileLoad); if (pack != null) { _packageManage.AddPackage(pack); _packagePack.Pack(Path.Combine(dir.FullName, "Package.json")); } } catch { } } } private void LoadPackedPackages() { var list = Directory.GetFiles(Localizer.DownloadPackageDirPath).ToList(); list.AddRange(Directory.GetFiles(Path.Combine(Terraria.Main.SavePath, "Mods"), "*.locpack")); foreach (var file in list) { try { var pack = _packedPackageLoad.Load(file, _fileLoad); if (pack != null) { _packageManage.AddPackage(pack); } } catch { } } } private void Import(IMod mod = null) { try { _packageImport.Clear(); if (mod is null) { foreach (var pg in _packageManage.PackageGroups) { QueuePackageGroup(pg); } } else { QueuePackageGroup(_packageManage.PackageGroups.FirstOrDefault(pg => pg.Mod.Name == mod.Name)); } _packageImport.Import(true); Localizer.RefreshLanguages(); Utils.LogDebug("Auto import end."); } catch { } } private void QueuePackageGroup(IPackageGroup packageGroup) { if (packageGroup is null || !packageGroup.Mod.Enabled) { return; } foreach (var p in packageGroup.Packages) { if (p.Enabled) { _packageImport.Queue(p); } } } protected override void DisposeUnmanaged() { Hooks.PostSetupContent -= OnPostSetupContent; Hooks.BeforeModCtor -= OnBeforeModCtor; } } } ================================================ FILE: Localizer/Package/Import/BasicImporter.cs ================================================ using System; using System.Collections; using System.Globalization; using System.Linq; using System.Reflection; using Localizer.Attributes; using Localizer.DataModel; using Localizer.DataModel.Default; using Localizer.Helpers; using Terraria.ModLoader; namespace Localizer.Package.Import { public class BasicImporter : FileImporter where T : IFile { public override void Import(IFile file, IMod mod, CultureInfo culture) { ImportInternal((T)file, mod, culture); } private void ImportInternal(T file, IMod mod, CultureInfo culture) { foreach (var prop in typeof(T).ModTranslationOwnerField()) { var fieldName = prop.ModTranslationOwnerFieldName(); var field = Utils.GetModByName(mod.Name).ValueOf(fieldName); var entryType = prop.PropertyType.GenericTypeArguments .FirstOrDefault(g => g.GetInterfaces().Contains(typeof(IEntry))); var entries = (IDictionary)prop.GetValue(file); ApplyEntries(entries, field, entryType, culture); } } public override IFile Merge(IFile main, IFile addition) { return MergeInternal((T)main, (T)addition); } internal T MergeInternal(T main, T addition) { var result = Activator.CreateInstance(typeof(T)); foreach (var prop in typeof(T).ModTranslationOwnerField()) { var entries = (IDictionary)Activator.CreateInstance(prop.PropertyType); var mainEntryDict = (IDictionary)prop.GetValue(main); var additionEntryDict = (IDictionary)prop.GetValue(addition); foreach (string key in mainEntryDict.Keys) { entries.Add(key, (mainEntryDict[key] as IEntry)?.Clone()); } foreach (string key in additionEntryDict.Keys) { if (entries.Contains(key)) { entries[key] = Merge((IEntry)mainEntryDict[key], (IEntry)additionEntryDict[key]); } else { entries.Add(key, additionEntryDict[key]); } } prop.SetValue(result, entries); } return (T)result; } public IEntry Merge(IEntry main, IEntry addition) { if (main.GetType() != addition.GetType()) { return main; } var result = Activator.CreateInstance(main.GetType()) as IEntry; var props = result.GetType().ModTranslationProp(); foreach (var prop in props) { var merged = Utils.GetTranslationOfEntry(main, prop); if (string.IsNullOrEmpty(merged)) { merged = Utils.GetTranslationOfEntry(addition, prop) ?? ""; } var baseEntry = Activator.CreateInstance(prop.PropertyType) as BaseEntry; baseEntry.Translation = merged; prop.SetValue(result, baseEntry); } return result; } private void ApplyEntries(IDictionary entries, IDictionary field, Type entryType, CultureInfo culture) { var mappings = Utils.CreateEntryMappings(entryType); foreach (string eKey in entries.Keys) { if (!field.Contains(eKey)) { continue; } foreach (var mapping in mappings) { var localizeOwner = field[eKey]; var modTrans = localizeOwner?.GetType().GetProperty(mapping.Key)?.GetValue(localizeOwner) as ModTranslation; modTrans?.Import(mapping.Value.GetValue(entries[eKey]) as BaseEntry, culture); } } } } [OperationTiming(OperationTiming.PostContentLoad)] public class BasicImporterPostContentLoad : BasicImporter where T : IFile { } [OperationTiming(OperationTiming.BeforeContentLoad)] public class BasicImporterBeforeContentLoad : BasicImporter where T : IFile { } } ================================================ FILE: Localizer/Package/Import/CecilLdstrImporter.cs ================================================ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using Harmony; using Localizer.Attributes; using Localizer.DataModel; using Localizer.DataModel.Default; using Mono.Cecil; using Mono.Cecil.Cil; using Ninject; namespace Localizer.Package.Import { [OperationTiming(OperationTiming.BeforeModCtor)] public class CecilLdstrImporter : LdstrImporterBase { public bool Importing = false; public LdstrFile ImportingFile; public IMod ImportingMod; private HarmonyInstance _harmony; public CecilLdstrImporter() { _harmony = HarmonyInstance.Create(nameof(CecilLdstrImporter)); _harmony.Patch("Terraria.ModLoader.Core.AssemblyManager", "GetModAssembly", postfix: new HarmonyMethod(typeof(CecilLdstrImporter).Method(nameof(PostGetModAssembly)))); } public static void PostGetModAssembly(ref byte[] __result) { try { var instance = Localizer.Kernel.Get(); if (!instance.Importing || !Localizer.Config.ImportLdstr) { return; } using (var ms = new MemoryStream(__result)) { var asmDef = AssemblyDefinition.ReadAssembly(ms); instance.PatchAssembly(asmDef); var result = new MemoryStream(); asmDef.Write(result); __result = result.ToArray(); } } catch { } } private void PatchAssembly(AssemblyDefinition asm) { var module = asm.MainModule; var entryDict = ImportingFile.LdstrEntries; foreach (var entryPair in entryDict) { Utils.SafeWrap(() => { if (!HaveTranslation(entryPair.Value)) { return; } Utils.LogDebug($"Finding method: [{entryPair.Key}]"); var method = Utils.FindMethodByID(module, entryPair.Key); if (method == null) { Utils.LogDebug($"Cannot find."); return; } var instructions = method.Body?.Instructions; if (instructions == null || !instructions.Any()) { return; } var result = instructions.ToList(); foreach (var translation in entryPair.Value.Instructions) { ReplaceLdstr(translation.Origin, translation.Translation, result); } Utils.LogDebug($"Patched: {entryPair.Key}"); }); } } protected override void ImportInternal(LdstrFile file, IMod mod, CultureInfo culture) { Importing = true; try { ImportingFile = file; ImportingMod = mod; if ((mod as LoadedModWrapper).wrapped.TryGetTarget(out var loadedMod)) { loadedMod.Invoke("set_NeedsReload", true); loadedMod.Invoke("LoadAssemblies"); } } finally { Importing = false; } } private static void ReplaceLdstr(string o, string n, IEnumerable il) { if (string.IsNullOrEmpty(n)) { return; } foreach (var i in il) { if (i.OpCode == OpCodes.Ldstr && i?.Operand?.ToString() == o) { i.Operand = n; } } } protected override void DisposeUnmanaged() { _harmony.UnpatchAll(nameof(CecilLdstrImporter)); } } } ================================================ FILE: Localizer/Package/Import/CustomModTranslationImporter.cs ================================================ using System.Collections.Generic; using System.Globalization; using System.Reflection; using Localizer.Attributes; using Localizer.DataModel; using Localizer.DataModel.Default; using Localizer.Helpers; using Terraria.ModLoader; namespace Localizer.Package.Import { [OperationTiming(OperationTiming.PostContentLoad)] public class CustomModTranslationImporter : FileImporter { public override void Import(IFile file, IMod mod, CultureInfo culture) { ImportInternal(file as CustomModTranslationFile, mod, culture); } private void ImportInternal(CustomModTranslationFile file, IMod mod, CultureInfo culture) { var entryDict = file.Translations; var translations = Utils.GetModByName(mod.Name).ValueOf>("translations"); if (translations == null) { return; } foreach (var pair in entryDict) { if (!translations.ContainsKey(pair.Key)) { continue; } var translation = translations[pair.Key]; translation?.Import(pair.Value, culture); translations[pair.Key] = translation; } } public override IFile Merge(IFile main, IFile addition) { return MergeInternal(main as CustomModTranslationFile, addition as CustomModTranslationFile); } internal CustomModTranslationFile MergeInternal(CustomModTranslationFile main, CustomModTranslationFile addition) { var result = new CustomModTranslationFile { Translations = new Dictionary() }; foreach (var t in main.Translations) { result.Translations.Add(t.Key, t.Value.Clone() as BaseEntry); } foreach (var pair in addition.Translations) { if (result.Translations.ContainsKey(pair.Key)) { result.Translations[pair.Key] = Merge(main.Translations[pair.Key], pair.Value); } else { result.Translations.Add(pair.Key, pair.Value.Clone() as BaseEntry); } } return result; } public BaseEntry Merge(BaseEntry main, BaseEntry addition) { var e = main.Clone() as BaseEntry; if (string.IsNullOrWhiteSpace(main.Translation)) { e.Translation = addition.Translation; } return e; } } } ================================================ FILE: Localizer/Package/Import/FileImporter.cs ================================================ using System.Globalization; using Localizer.DataModel; namespace Localizer.Package.Import { public abstract class FileImporter : Disposable { /// /// Import a file into correspond mod. /// /// /// /// public abstract void Import(IFile file, IMod mod, CultureInfo culture); /// /// Merge an entry into another one. /// /// /// /// public abstract IFile Merge(IFile main, IFile addition); public virtual void Reset() { } } } ================================================ FILE: Localizer/Package/Import/HarmonyLdstrImporter.cs ================================================ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using Harmony; using Localizer.DataModel; using Localizer.DataModel.Default; namespace Localizer.Package.Import { public sealed class HarmonyLdstrImporter : LdstrImporterBase { private HarmonyInstance harmony; private static Dictionary entries; public HarmonyLdstrImporter() { harmony = HarmonyInstance.Create("LdstrFileImport"); } protected override void ImportInternal(LdstrFile file, IMod mod, CultureInfo culture) { entries = new Dictionary(); var module = mod.Code.ManifestModule; var entryDict = file.LdstrEntries; foreach (var entryPair in entryDict) { Utils.SafeWrap(() => { if (!HaveTranslation(entryPair.Value)) { return; } Utils.LogDebug($"Finding method: [{entryPair.Key}]"); var method = Utils.FindMethodByID(module, entryPair.Key); if (method == null) { Utils.LogDebug($"Cannot find."); return; } entries.Add(method, entryPair.Value); harmony.Patch(method, transpiler: new HarmonyMethod(NoroHelper.MethodInfo(() => Transpile(null, null)))); Utils.LogDebug($"Patched: {entryPair.Key}"); }); } } public override void Reset() { harmony.UnpatchAll("LdstrFileImport"); } private static IEnumerable Transpile(IEnumerable instructions, MethodBase original) { if (!entries.ContainsKey(original) || instructions == null || instructions.Count() == 0) { return instructions; } var result = instructions.ToList(); var entry = entries[original]; foreach (var translation in entry.Instructions) { ReplaceLdstr(translation.Origin, translation.Translation, result); } return result; } private static void ReplaceLdstr(string o, string n, IEnumerable il) { if (string.IsNullOrEmpty(n)) { return; } var ins = il.FirstOrDefault(i => i?.operand?.ToString() == o); if (ins != null) { ins.operand = n; } } protected override void DisposeUnmanaged() { entries = null; harmony.UnpatchAll("LdstrFileImport"); } } } ================================================ FILE: Localizer/Package/Import/IPackageImportService.cs ================================================ using System; using Localizer.DataModel; namespace Localizer.Package.Import { public interface IPackageImportService { void RegisterImporter(Type importerType) where T : IFile; void UnregisterImporter() where T : IFile; /// /// Add a package into the internal queue, /// earlier packages have more priorities. /// /// void Queue(IPackage package); /// /// Start the import process. /// void Import(bool preferEarly); /// /// Clear internal queue and ready for next work. /// void Reset(); /// /// Clear internal queue. /// void Clear(); } } ================================================ FILE: Localizer/Package/Import/LdstrImporterBase.cs ================================================ using System.Collections.Generic; using System.Globalization; using Localizer.DataModel; using Localizer.DataModel.Default; namespace Localizer.Package.Import { public abstract class LdstrImporterBase : FileImporter { internal bool HaveTranslation(LdstrEntry entry) { foreach (var ins in entry.Instructions) { if (!string.IsNullOrEmpty(ins.Translation)) { return true; } } return false; } public override void Import(IFile file, IMod mod, CultureInfo culture) { ImportInternal(file as LdstrFile, mod, culture); } public override IFile Merge(IFile main, IFile addition) { return MergeInternal(main as LdstrFile, addition as LdstrFile); } protected abstract void ImportInternal(LdstrFile file, IMod mod, CultureInfo culture); internal LdstrFile MergeInternal(LdstrFile main, LdstrFile addition) { var result = new LdstrFile { LdstrEntries = new Dictionary() }; foreach (var e in main.LdstrEntries) { result.LdstrEntries.Add(e.Key, e.Value.Clone() as LdstrEntry); } foreach (var pair in addition.LdstrEntries) { if (result.LdstrEntries.ContainsKey(pair.Key)) { result.LdstrEntries[pair.Key] = Merge(main.LdstrEntries[pair.Key], pair.Value); } else { result.LdstrEntries.Add(pair.Key, pair.Value); } } return result; } internal LdstrEntry Merge(LdstrEntry main, LdstrEntry addition) { var result = new LdstrEntry { Instructions = new List() }; foreach (var ins in main.Instructions) { if (!result.Instructions.Exists(i => i.Origin == ins.Origin)) { result.Instructions.Add(ins.Clone() as BaseEntry); } } foreach (var ins in addition.Instructions) { if (!result.Instructions.Exists(i => i.Origin == ins.Origin)) { result.Instructions.Add(ins.Clone() as BaseEntry); } } return result; } } } ================================================ FILE: Localizer/Package/Import/MonoModLdstrImporter.cs ================================================ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using Localizer.DataModel; using Localizer.DataModel.Default; using MonoMod.Cil; using MonoMod.RuntimeDetour.HookGen; namespace Localizer.Package.Import { public class MonoModLdstrImporter : LdstrImporterBase { private Dictionary modifications; public MonoModLdstrImporter() { modifications = new Dictionary(); } protected override void ImportInternal(LdstrFile file, IMod mod, CultureInfo culture) { Terraria.ModLoader.ContentInstance.Register(Utils.GetModByName(mod.Name)); var module = mod.Code.ManifestModule; var entryDict = file.LdstrEntries; foreach (var entryPair in entryDict) { var method = Utils.FindMethodByID(module, entryPair.Key); if (method == null) { continue; } var e = entryPair.Value; if (!HaveTranslation(e)) { continue; } var modification = new ILContext.Manipulator(il => { foreach (var instruction in il.Instrs) { var ins = e.Instructions.FirstOrDefault(i => instruction.MatchLdstr(i.Origin)); if (ins == null || string.IsNullOrEmpty(ins.Translation)) { continue; } instruction.Operand = ins.Translation; foreach (var label in il.Labels) { if (label.Target.MatchLdstr(ins.Origin)) { label.Target = instruction; } } } }); if (!modifications.ContainsKey(method)) { HookEndpointManager.Modify(method, modification); modifications.Add(method, modification); } } } public override void Reset() { return; } protected override void DisposeUnmanaged() { modifications = null; } } } ================================================ FILE: Localizer/Package/Import/PackageImportService.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Localizer.Attributes; using Localizer.DataModel; using Localizer.DataModel.Default; using Ninject; namespace Localizer.Package.Import { public class PackageImportService : IPackageImportService { private readonly List packageGroups = new List(); private Dictionary _importers; public PackageImportService() { _importers = new Dictionary(); } public void RegisterImporter(Type importerType) where T : IFile { if (importerType is null) { throw new ArgumentNullException(nameof(importerType)); } Localizer.Kernel.Bind(typeof(FileImporter), importerType) .To(importerType).InSingletonScope(); var importer = Localizer.Kernel.Get(importerType) as FileImporter; if (importer is null) { Utils.LogError("Importer binding failed."); return; } if (_importers.ContainsKey(typeof(T))) { _importers[typeof(T)] = importer; } else { _importers.Add(typeof(T), importer); } Utils.LogInfo($"Importer: [{importer.GetType().FullName}] registered for file type: [{typeof(T).FullName}]."); } public void UnregisterImporter() where T : IFile { if (_importers.ContainsKey(typeof(T))) { _importers.Remove(typeof(T)); Utils.LogInfo($"Unregistered importer of type [{typeof(T).FullName}]"); } } public void Queue(IPackage package) { if (packageGroups.All(pg => pg.Mod != package.Mod)) { packageGroups.Add(new PackageGroup { Mod = package.Mod, Packages = new List { package } }); } else { packageGroups.FirstOrDefault(pg => pg.Mod == package.Mod)?.Packages.Add(package); } Utils.LogDebug($"Queued [{package.Name}]"); } public void Import(bool preferEarly = true) { Utils.LogInfo($"Begin importing"); foreach (var group in packageGroups) { Utils.LogInfo($"Importing Mod: [{group.Mod.Name}]"); Utils.SafeWrap(() => { var merged = Merge(group); foreach (var f in merged.Files) { Utils.SafeWrap(() => { var importer = GetImporter(f); if (importer is null) { return; } Import(f, group, importer, preferEarly); }); } }); } } private void Import(IFile f, IPackageGroup group, FileImporter importer, bool preferEarly) { var importerTiming = importer.GetType().GetCustomAttribute() ?.Timing ?? OperationTiming.Any; Utils.LogDebug($"Trying to Import [{f.GetType()}] using [{importer.GetType()}]" + $"\n ImporterTiming: [{importerTiming}]" + $"\n State: [{Localizer.State}]" + $"\n PreferEarly: [{preferEarly}]"); if (!Localizer.CanDoOperationNow(importer.GetType()) || (preferEarly && importerTiming > Localizer.State && importerTiming == OperationTiming.Any && Localizer.State != OperationTiming.BeforeModCtor)) { return; } importer.Import(f, group.Mod, group.Packages.ToList()[0].Language); Utils.LogDebug($"Import Complete"); } public void Reset() { Utils.LogInfo($"Resetting importers..."); foreach (var importers in _importers.Values) { importers.Reset(); } packageGroups.Clear(); Utils.LogInfo($"Reset completed."); } public void Clear() { Utils.LogInfo($"Clearing import queue..."); packageGroups.Clear(); Utils.LogInfo($"Cleared."); } private FileImporter GetImporter(IFile file) { if (_importers.TryGetValue(file.GetType(), out var importer)) { return importer; } Utils.LogWarn($"No registered importer for file type: [{file.GetType()}]"); return null; } internal DataModel.Default.Package Merge(IPackageGroup group) { var result = new DataModel.Default.Package { Mod = group.Mod, ModName = group.Mod.Name, Files = new List(), FileList = new List() }; foreach (var package in group.Packages) { Utils.SafeWrap(() => { foreach (var file in package.Files) { if (result.Files.All(f => f.GetType() != file.GetType())) { result.Files.Add(file); } else { var main = package.Files.FirstOrDefault(f => f.GetType() == file.GetType()); var importer = GetImporter(file); if (importer is null) { continue; } var merged = importer.Merge(main, file); result.Files.Remove(main); result.Files.Add(merged); } } }); } return result; } public void Dispose() { foreach (var importer in _importers.Values) { Utils.SafeWrap(() => importer.Dispose()); } _importers = null; } } } ================================================ FILE: Localizer/Package/Import/RefreshLanguageService.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Threading.Tasks; using Harmony; using Terraria.Localization; using Terraria.ModLoader; namespace Localizer.Package.Import { public sealed class RefreshLanguageService : Disposable { private static RefreshLanguageService _instance; private List items; private bool _rebuilding = false; private bool _cleaning = false; private HarmonyInstance _harmony; private int _cleanUpCounter = 0; private bool _firstRun = true; public RefreshLanguageService() { _instance = this; items = new List(); _harmony = HarmonyInstance.Create(nameof(RefreshLanguageService)); _harmony.Patch(typeof(ModItem).GetConstructors()[0], null, NoroHelper.HarmonyMethod(() => OnModItemCtor(null))); } private static void OnModItemCtor(ModItem __instance) { if (!Localizer.Config.RebuildTooltips) { return; } if (Localizer.Config.RebuildTooltipsOnce && !_instance._firstRun) { return; } if (!_instance._rebuilding && !_instance._cleaning) { _instance.items.Add(new WeakReference(__instance)); _instance._cleanUpCounter++; if (_instance._cleanUpCounter > 20000 && !_instance._firstRun) { Task.Run(() => _instance.CleanUpItems()); _instance._cleanUpCounter = 0; } } } public void Refresh() { Utils.SafeWrap(() => { if (Localizer.State != OperationTiming.BeforeModCtor) { ModContent.RefreshModLanguage(LanguageManager.Instance.ActiveCulture); } if (Localizer.Config.RebuildTooltips && Localizer.State == OperationTiming.PostContentLoad) { _rebuilding = true; CleanUpItems(); var stopWatch = new Stopwatch(); Utils.LogInfo($"Rebuilding tooltips, count: {items.Count}"); stopWatch.Start(); foreach (var i in items) { (i.Target as ModItem)?.item.RebuildTooltip(); } stopWatch.Stop(); Utils.LogInfo( $"Rebuilding completed. count: {items.Count}, take {stopWatch.Elapsed.TotalSeconds} seconds"); _rebuilding = false; } }); } private void CleanUpItems() { var deads = new List(); _cleaning = true; var stopWatch = new Stopwatch(); Utils.LogInfo($"Cleaning item caches, count: {items.Count}"); stopWatch.Start(); lock (items) { foreach (var wr in items) { if (!wr.IsAlive) { deads.Add(wr); } } foreach (var d in deads) { items.Remove(d); } } stopWatch.Stop(); Utils.LogInfo($"Item caches cleaned. count: {items.Count}, take {stopWatch.Elapsed.TotalSeconds} seconds"); if (_firstRun) { _firstRun = false; } _cleaning = false; } protected override void DisposeUnmanaged() { _instance = null; _harmony.UnpatchAll(nameof(RefreshLanguageService)); } } } ================================================ FILE: Localizer/Package/Load/IFileLoadService.cs ================================================ using System.IO; using Localizer.DataModel; namespace Localizer.Package.Load { public interface IFileLoadService { /// /// Load a file from stream. /// /// /// /// IFile Load(Stream stream, string typeName); } } ================================================ FILE: Localizer/Package/Load/IPackageLoadService.cs ================================================ using Localizer.DataModel; namespace Localizer.Package.Load { public interface IPackageLoadService where T : IPackage { /// /// Load a package. /// /// /// /// IPackage Load(string path, IFileLoadService fileLoadService); } } ================================================ FILE: Localizer/Package/Load/JsonFileLoad.cs ================================================ using System; using System.Collections.Generic; using System.IO; using Localizer.DataModel; using Localizer.DataModel.Default; namespace Localizer.Package.Load { public class JsonFileLoad : IFileLoadService { private static Dictionary fileTypes = new Dictionary { {typeof(BasicItemFile).Name, typeof(BasicItemFile)}, {typeof(BasicBuffFile).Name, typeof(BasicBuffFile)}, {typeof(CustomModTranslationFile).Name, typeof(CustomModTranslationFile)}, {typeof(BasicNPCFile).Name, typeof(BasicNPCFile)}, {typeof(BasicProjectileFile).Name, typeof(BasicProjectileFile)}, {typeof(BasicPrefixFile).Name, typeof(BasicPrefixFile)}, {typeof(LdstrFile).Name, typeof(LdstrFile)} }; public IFile Load(Stream stream, string typeName) { if (!fileTypes.ContainsKey(typeName)) { Localizer.Log.Error(string.Format("Not supported file type: {0}", typeName)); return null; } var type = fileTypes[typeName]; var file = Utils.ReadFileAndDeserializeJson(type, stream) as IFile; if (file == null) { Localizer.Log.Error(string.Format("File deserialization failed!, FileType: {0}", type.FullName)); } return file; } public void RegisterType(string typeName, Type type) { if (fileTypes == null) { fileTypes = new Dictionary(); } if (fileTypes.ContainsKey(typeName)) { fileTypes[typeName] = type; } else { fileTypes.Add(typeName, type); } } public void Dispose() { } } } ================================================ FILE: Localizer/Package/Load/PackedPackageLoad.cs ================================================ using System.IO; using System.IO.Compression; using Localizer.DataModel; namespace Localizer.Package.Load { public sealed class PackedPackageLoad : IPackageLoadService where T : IPackage { private readonly string _packageMainFileName = "Package.json"; public IPackage Load(string path, IFileLoadService fileLoadService) { Utils.LogDebug($"Loading package from {path}"); if (!System.IO.File.Exists(path)) { Utils.LogError("Package file doesn't exist!"); return null; } using (var zipFileToOpen = new FileStream(path, FileMode.Open)) { using (var archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Read)) { var packageStream = archive.GetEntry(_packageMainFileName)?.Open(); IPackage package = Utils.ReadFileAndDeserializeJson(packageStream); if (package == null) { Utils.LogError("Package main file deserialization failed!"); return null; } var mod = Localizer.GetWrappedMod(package.ModName); if (mod == null) { Utils.LogError($"Package Mod {package.ModName} not loaded!"); return null; } package.Mod = mod; foreach (var fileTypeName in package.FileList) { Utils.LogDebug($"Loading file [{fileTypeName}]"); var fs = archive.GetEntry($"{fileTypeName}.json")?.Open(); var file = fileLoadService.Load(fs, fileTypeName); package.AddFile(file); } Utils.LogDebug($"Package [{package.Name} loaded.]"); return package; } } } public void Dispose() { } } } ================================================ FILE: Localizer/Package/Load/SourcePackageLoad.cs ================================================ using System.IO; using Localizer.DataModel; using File = System.IO.File; namespace Localizer.Package.Load { public sealed class SourcePackageLoad : IPackageLoadService where T : IPackage { private readonly string _packageMainFileName = "Package.json"; public IPackage Load(string path, IFileLoadService fileLoadService) { Utils.LogDebug($"Loading package from {path}"); if (!Directory.Exists(path)) { Utils.LogError("Package directory doesn't exist!"); return null; } var packDir = new DirectoryInfo(path); var packageFilePath = Path.Combine(packDir.FullName, _packageMainFileName); if (!File.Exists(packageFilePath)) { Utils.LogError("Package main file doesn't exist!"); return null; } IPackage package = Utils.ReadFileAndDeserializeJson(packageFilePath); if (package == null) { Utils.LogError("Package main file deserialization failed!"); return null; } var mod = Localizer.GetWrappedMod(package.ModName); if (mod == null) { Utils.LogError($"Package Mod {package.ModName} not loaded!"); return null; } package.Mod = mod; foreach (var fileTypeName in package.FileList) { Utils.LogDebug($"Loading file [{fileTypeName}]"); var filePath = Path.Combine(packDir.FullName, fileTypeName + ".json"); using (var fs = new FileStream(filePath, FileMode.Open)) { var file = fileLoadService.Load(fs, fileTypeName); package.AddFile(file); } } Utils.LogDebug($"Package [{package.Name} loaded.]"); return package; } public void Dispose() { } } } ================================================ FILE: Localizer/Package/Pack/IPackagePackService.cs ================================================ namespace Localizer.Package.Pack { public interface IPackagePackService { /// /// Pack up a package. /// /// Path of the package main file. void Pack(string path); } } ================================================ FILE: Localizer/Package/Pack/ZipPackagePackService.cs ================================================ using System.IO; using System.IO.Compression; using Localizer.DataModel; namespace Localizer.Package.Pack { public class ZipPackagePackService : IPackagePackService where T : IPackage { private readonly string _packageMainFileName = "Package.json"; public void Pack(string path) { Utils.LogDebug($"Packing package from {path}"); if (!System.IO.File.Exists(path)) { Utils.LogError("Cannot find the package file!"); return; } var packDir = new FileInfo(path).Directory; var package = Utils.ReadFileAndDeserializeJson(path); using (var zipFileToOpen = new FileStream($"{packDir.FullName}/{package.Name}.locpack", FileMode.Create)) { using (var archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Create)) { Utils.WriteZipArchiveEntry(archive, path, _packageMainFileName); foreach (var filename in package.FileList) { Utils.LogDebug($"Writing {filename}"); var filePath = Path.Combine(packDir.FullName, filename + ".json"); if (!System.IO.File.Exists(filePath)) { Utils.LogError($"Cannot find file: {filePath}!"); continue; } Utils.WriteZipArchiveEntry(archive, filePath, filename + ".json"); } } } Utils.LogDebug("Packed"); } public void Dispose() { } } } ================================================ FILE: Localizer/Package/PackageManageService.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Localizer.DataModel; using Localizer.DataModel.Default; namespace Localizer.Package { public class PackageManageService : IPackageManageService { private readonly string stateSavePath = Localizer.SavePath + "PackageStates.json"; public ICollection PackageGroups { get; set; } private List oldPackageGroupStates = new List(); /// /// Add a package into PackageGroups. /// /// public void AddPackage(IPackage package) { if (package == null) { return; } if (PackageGroups.All(pg => pg.Mod.Name != package.Mod.Name)) { PackageGroups.Add(new PackageGroup { Mod = package.Mod, Packages = new List { package } }); } else { PackageGroups.FirstOrDefault( pg => pg.Mod.Name == package.Mod.Name && pg.Packages.All(p => p.Name != package.Name))?.Packages.Add(package); } } public void RemovePackage(IPackage package) { throw new NotImplementedException(); } public void LoadState() { if (!System.IO.File.Exists(stateSavePath)) { return; } oldPackageGroupStates = Utils.ReadFileAndDeserializeJson>(stateSavePath) ?? new List(); foreach (var state in oldPackageGroupStates) { var packageGroup = PackageGroups.FirstOrDefault(pg => pg.Mod.Name == state.ModName); if (packageGroup == null) { continue; } foreach (var p in packageGroup.Packages) { if (state.Packages.Contains(p.Name)) { p.Enabled = (bool)state.Packages[p.Name]; } } } } public void SaveState() { foreach (var pg in PackageGroups) { var state = oldPackageGroupStates.FirstOrDefault(s => s.ModName == pg.Mod.Name); if (state != null) { oldPackageGroupStates.Remove(state); } oldPackageGroupStates.Add(new PackageGroupState(pg)); } Utils.SerializeJsonAndCreateFile(oldPackageGroupStates, stateSavePath); } public void Dispose() { } } } ================================================ FILE: Localizer/Package/Save/IFileSaveService.cs ================================================ using Localizer.DataModel; namespace Localizer.Package.Save { public interface IFileSaveService { /// /// Save a file. /// /// /// void Save(IFile file, string path); } } ================================================ FILE: Localizer/Package/Save/IPackageSaveService.cs ================================================ using Localizer.DataModel; namespace Localizer.Package.Save { public interface IPackageSaveService { /// /// Save a package to filesystem. /// /// /// /// void Save(IPackage package, string path, IFileSaveService fileSaveDisposable); } } ================================================ FILE: Localizer/Package/Save/JsonFileSaveService.cs ================================================ using Localizer.DataModel; namespace Localizer.Package.Save { public class JsonFileSaveService : IFileSaveService { public void Save(IFile file, string path) { Utils.SerializeJsonAndCreateFile(file, path); } public void Dispose() { } } } ================================================ FILE: Localizer/Package/Save/PackageSaveService.cs ================================================ using System.IO; using Localizer.DataModel; namespace Localizer.Package.Save { public class PackageSave : IPackageSaveService { public void Save(IPackage package, string path, IFileSaveService fileSaveDisposable) { Utils.SerializeJsonAndCreateFile(package, Path.Combine(path, "Package.json")); foreach (var file in package.Files) { fileSaveDisposable.Save(file, Path.Combine(path, file.GetType().Name + ".json")); } } public void Dispose() { } } } ================================================ FILE: Localizer/Package/Update/BasicFileUpdater.cs ================================================ using System.Collections; using System.Collections.Generic; using Localizer.DataModel; using Localizer.DataModel.Default; using Localizer.Helpers; namespace Localizer.Package.Update { public sealed class BasicFileUpdater : FileUpdater where T : IFile { public override void Update(IFile oldFile, IFile newFile, IUpdateLogger logger) { CheckArgs(oldFile, newFile, logger); UpdateInternal((T)oldFile, (T)newFile, logger); } public void UpdateInternal(T oldFile, T newFile, IUpdateLogger logger) { if (oldFile.GetType() != typeof(T) || newFile.GetType() != typeof(T)) { return; } foreach (var prop in typeof(T).ModTranslationOwnerField()) { var oldEntries = (IDictionary)prop.GetValue(oldFile); var newEntries = (IDictionary)prop.GetValue(newFile); foreach (string newEntryKey in newEntries.Keys) { if (oldEntries.Contains(newEntryKey)) { UpdateEntry(newEntryKey, oldFile.GetValue(newEntryKey), newFile.GetValue(newEntryKey), logger); } else { logger.Add($"[{newEntryKey}]"); var entry = (newEntries[newEntryKey] as IEntry).Clone(); oldEntries.Add(newEntryKey, entry); } } var removed = new List(); foreach (string k in oldEntries.Keys) { if (!newEntries.Contains(k)) { removed.Add(k); } } foreach (var r in removed) { logger.Remove($"[{r}]"); } prop.SetValue(oldFile, oldEntries); } } internal void UpdateEntry(string key, IEntry oldEntry, IEntry newEntry, IUpdateLogger logger) { foreach (var prop in oldEntry.GetType().ModTranslationProp()) { var o = prop.GetValue(oldEntry) as BaseEntry; var n = prop.GetValue(newEntry) as BaseEntry; if (o.Origin != n.Origin) { logger.Change($"{key}'s {prop.Name}\r\n[Old: \"{o.Origin}\"]\r\n => \r\n[New: \"{n.Origin}\"]\r\n"); o.Origin = n.Origin; o.Translation = n.Translation; } } } } } ================================================ FILE: Localizer/Package/Update/CustomModTranslationUpdater.cs ================================================ using System.Linq; using Localizer.DataModel; using Localizer.DataModel.Default; namespace Localizer.Package.Update { public class CustomModTranslationUpdater : FileUpdater { public override void Update(IFile oldFile, IFile newFile, IUpdateLogger logger) { CheckArgs(oldFile, newFile, logger); UpdateInternal(oldFile as CustomModTranslationFile, newFile as CustomModTranslationFile, logger); } public void UpdateInternal(CustomModTranslationFile oldFile, CustomModTranslationFile newFile, IUpdateLogger logger) { var oldEntries = oldFile.Translations; var newEntries = newFile.Translations; foreach (var newEntryKey in newEntries.Keys) { if (oldEntries.Keys.Contains(newEntryKey)) { var o = oldEntries[newEntryKey]; var n = newEntries[newEntryKey]; if (o.Origin != n.Origin) { logger.Change($"{newEntryKey}\r\n[Old: \"{o.Origin}\"]\r\n => \r\n[New: \"{n.Origin}\"]\r\n"); o.Origin = n.Origin; o.Translation = n.Translation; } } else { logger.Add($"[{newEntryKey}]"); var entry = newEntries[newEntryKey]; oldEntries.Add(newEntryKey, entry); } } var removed = oldEntries.Keys.Where(k => !newEntries.ContainsKey(k)); foreach (var r in removed) { logger.Remove($"[{r}]"); } } public void Dispose() { } } } ================================================ FILE: Localizer/Package/Update/FileUpdater.cs ================================================ using System; using Localizer.DataModel; namespace Localizer.Package.Update { public abstract class FileUpdater { /// /// Compare two packages and merge differences into old one. /// Generate reports with logger. /// /// /// /// public abstract void Update(IFile oldFile, IFile newFile, IUpdateLogger logger); internal void CheckArgs(IFile oldFile, IFile newFile, IUpdateLogger logger) { if (oldFile is null) { throw new ArgumentNullException(nameof(oldFile)); } if (newFile is null) { throw new ArgumentNullException(nameof(newFile)); } if (logger is null) { throw new ArgumentNullException(nameof(logger)); } if (oldFile.GetType() != newFile.GetType()) { throw new Exception($"Different file type: [{oldFile.GetType().FullName}] and [{newFile.GetType().FullName}]"); } } } } ================================================ FILE: Localizer/Package/Update/IPackageUpdateService.cs ================================================ using Localizer.DataModel; namespace Localizer.Package.Update { public interface IPackageUpdateService { void RegisterUpdater(FileUpdater updater) where T : IFile; void UnregisterUpdater() where T : IFile; /// /// Compare two packages and merge differences into old one. /// Generate reports with logger. /// /// /// /// void Update(IPackage oldPackage, IPackage newPackage, IUpdateLogger logger); } } ================================================ FILE: Localizer/Package/Update/IUpdateLogger.cs ================================================ namespace Localizer.Package.Update { public interface IUpdateLogger { /// /// Initialization works of the logger. /// /// void Init(string name); /// /// Used when something has been added. /// /// void Add(object content); /// /// Used when something has been removed. /// /// void Remove(object content); /// /// Used when something has been changed. /// /// void Change(object content); } } ================================================ FILE: Localizer/Package/Update/LdstrFileUpdater.cs ================================================ using System.Linq; using Localizer.DataModel; using Localizer.DataModel.Default; namespace Localizer.Package.Update { public class LdstrFileUpdater : FileUpdater { public override void Update(IFile oldFile, IFile newFile, IUpdateLogger logger) { CheckArgs(oldFile, newFile, logger); UpdateInternal(oldFile as LdstrFile, newFile as LdstrFile, logger); } public void UpdateInternal(LdstrFile oldFile, LdstrFile newFile, IUpdateLogger logger) { var oldEntries = oldFile.LdstrEntries; var newEntries = newFile.LdstrEntries; foreach (var newEntryKey in newEntries.Keys) { if (oldEntries.Keys.Contains(newEntryKey)) { var o = oldEntries[newEntryKey]; var n = newEntries[newEntryKey]; foreach (var newIns in n.Instructions) { if (o.Instructions.Exists(oi => oi.Origin == newIns.Origin)) { continue; } o.Instructions.Add(newIns); logger.Change($"New instruction of {newEntryKey}: [{newIns}]"); } } else { logger.Add($"[{newEntryKey}]"); var entry = newEntries[newEntryKey]; oldEntries.Add(newEntryKey, entry); } } var removed = oldEntries.Keys.Where(k => !newEntries.ContainsKey(k)); foreach (var r in removed) { logger.Remove($"[{r}]"); } } public void Dispose() { } } } ================================================ FILE: Localizer/Package/Update/PackageUpdateService.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Localizer.DataModel; namespace Localizer.Package.Update { public sealed class PackageUpdateService : IPackageUpdateService { private Dictionary _updaters; public PackageUpdateService() { _updaters = new Dictionary(); } public void RegisterUpdater(FileUpdater updater) where T : IFile { if (updater is null) { throw new ArgumentNullException(nameof(updater)); } if (_updaters.ContainsKey(typeof(T))) { _updaters[typeof(T)] = updater; } else { _updaters.Add(typeof(T), updater); } Utils.LogInfo($"Updater: [{updater.GetType().FullName}] registered for file type: [{typeof(T).FullName}]."); } public void UnregisterUpdater() where T : IFile { if (_updaters.ContainsKey(typeof(T))) { _updaters.Remove(typeof(T)); Utils.LogInfo($"Unregistered updater of type [{typeof(T).FullName}]"); } } public void Update(IPackage oldPackage, IPackage newPackage, IUpdateLogger logger) { Utils.LogDebug($"Updating package [{oldPackage.Name}]"); foreach (var oldFile in oldPackage.Files) { var updater = GetUpdater(oldFile); if (updater is null) { continue; } Utils.SafeWrap(() => { updater.Update(oldFile, newPackage.Files.FirstOrDefault(f => f.GetType() == oldFile.GetType()), logger); }); } foreach (var file in newPackage.Files) { if (oldPackage.Files.All(f => f.GetType() != file.GetType())) { oldPackage.AddFile(file); } } Utils.LogDebug($"Package [{oldPackage.Name}] updated."); } private FileUpdater GetUpdater(T file) where T : IFile { if (_updaters.TryGetValue(file.GetType(), out var updater)) { return updater; } Utils.LogWarn($"No registered importer for file type: [{file.GetType()}]"); return null; } } } ================================================ FILE: Localizer/Package/Update/PlainUpdateLogger.cs ================================================ using System.IO; namespace Localizer.Package.Update { public class PlainUpdateLogger : IUpdateLogger { private static readonly string logDirPath = Path.Combine(Localizer.SavePath, "UpdateLogs"); private string path; public void Init(string name) { Utils.EnsureDir(logDirPath); path = Path.Combine(logDirPath, name + ".txt"); } public void Add(object content) { System.IO.File.AppendAllText(path, $"[Content Added]: {content} \r\n"); } public void Remove(object content) { System.IO.File.AppendAllText(path, $"[Content Removed]: {content} \r\n"); } public void Change(object content) { System.IO.File.AppendAllText(path, $"[Content Changed]: {content} \r\n"); } public void Dispose() { } } } ================================================ FILE: Localizer/Properties/AssemblyInfo.cs ================================================ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("LocalizerTest")] ================================================ FILE: Localizer/UIs/Components/BasicListBox.cs ================================================ using Squid; namespace Localizer.UIs.Components { public class BasicListBox : ListBox { public BasicListBox() { base.Dock = DockStyle.Fill; base.Scrollbar.Size = new Point(14, 10); base.Scrollbar.Slider.Style = "vscrollTrack"; base.Scrollbar.Slider.Button.Style = "vscrollButton"; base.Scrollbar.ButtonUp.Style = "vscrollUp"; base.Scrollbar.ButtonUp.Size = new Point(10, 20); base.Scrollbar.ButtonDown.Style = "vscrollUp"; base.Scrollbar.ButtonDown.Size = new Point(10, 20); } } } ================================================ FILE: Localizer/UIs/Components/BasicWindow.cs ================================================ using Squid; namespace Localizer.UIs.Components { public class BasicWindow : Window { public TitleBar Titlebar { get; private set; } public BasicWindow() { AllowDragOut = true; Padding = new Margin(4); Titlebar = new TitleBar { Dock = DockStyle.Top, Size = new Point(122, 35) }; Titlebar.MouseDown += (sender, args) => StartDrag(); Titlebar.MouseUp += (sender, args) => StopDrag(); Titlebar.Cursor = CursorNames.Move; Titlebar.Style = "frame"; Titlebar.Margin = new Margin(-4, -4, -4, -1); Titlebar.Button.MouseClick += Button_OnMouseClick; Titlebar.TextAlign = Alignment.MiddleLeft; Titlebar.BBCodeEnabled = true; AllowDragOut = false; Controls.Add(Titlebar); } private void Button_OnMouseClick(Control sender, MouseEventArgs args) { } } } ================================================ FILE: Localizer/UIs/Components/LabelListBoxItem.cs ================================================ using Squid; namespace Localizer.UIs.Components { public class LabelListBoxItem : ListBoxItem { public Label Label { get; set; } public new string Text => Label.Text; public LabelListBoxItem(string text) { base.Margin = new Margin(0, 5, 0, 5); Label = new Label { Text = text, Dock = DockStyle.Fill, Style = "label" }; } } } ================================================ FILE: Localizer/UIs/Components/TitleBar.cs ================================================ using Squid; namespace Localizer.UIs.Components { public class TitleBar : Label { public Button Button { get; private set; } public TitleBar() { Button = new Button { Size = new Point(30, 30), Style = "button", Text = "X", TextAlign = Alignment.MiddleCenter, Tooltip = "Close Window", Dock = DockStyle.Right, Margin = new Margin(0, 8, 8, 8) }; Elements.Add(Button); } } } ================================================ FILE: Localizer/UIs/MainWindow.cs ================================================ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using Localizer.DataModel; using Localizer.Helpers; using Localizer.Network; using Localizer.Package; using Localizer.Package.Export; using Localizer.Package.Load; using Localizer.Package.Save; using Localizer.Package.Update; using Localizer.UIs.Components; using Ninject; using Squid; using Terraria.Localization; using static Localizer.Lang; namespace Localizer.UIs { public class MainWindow : BasicWindow { private Panel _menuBar; private SplitContainer _split; private BasicListBox _modList = new BasicListBox(); private BasicListBox _pkgList = new BasicListBox { MaxSelected = 0, AllowDrop = true }; private IPackageManageService pkgManager; private IFileLoadService fileLoadService; private IFileSaveService fileSaveService; private IPackageExportService packageExportService; private IPackageSaveService packageSaveService; private IPackageUpdateService packageUpdateService; private IPackageLoadService packedPackageLoadServiceService; private IPackageLoadService sourcePackageLoadServiceService; private IPackageBrowserService packageBrowserService; private IDownloadManagerService downloadManagerService; private List onlinePackages = new List(); private bool loading = false; public MainWindow() { Button AddButton(string text, string tooltip, MouseEvent action) { var button = new Button { Text = text, Tooltip = tooltip, Dock = DockStyle.Left }; button.MouseClick += action; _menuBar.Content.Controls.Add(button); return button; } loading = true; pkgManager = Localizer.Kernel.Get(); sourcePackageLoadServiceService = Localizer.Kernel.Get>(); packedPackageLoadServiceService = Localizer.Kernel.Get>(); packageExportService = Localizer.Kernel.Get(); packageSaveService = Localizer.Kernel.Get(); packageUpdateService = Localizer.Kernel.Get(); fileLoadService = Localizer.Kernel.Get(); fileSaveService = Localizer.Kernel.Get(); packageBrowserService = Localizer.Kernel.Get(); downloadManagerService = Localizer.Kernel.Get(); pkgManager.PackageGroups = new ObservableCollection(); Size = new Point(800, 340); Position = new Point(40, 200); Titlebar.Text = _("PackageManage"); Titlebar.Button.MouseClick += (sender, args) => Visible = false; Resizable = true; _menuBar = new Panel { Dock = DockStyle.Top, Size = new Point(0, 30) }; Controls.Add(_menuBar); AddButton(_("Reload"), _("ReloadDesc"), (sender, args) => { if (args.Button == 0) { LoadPackages(); } }); var refreshBtn = AddButton(_("RefreshOnline"), _("RefreshOnlineDesc"), (sender, args) => { if (args.Button == 0) { RefreshOnlinePackages(sender); } }); AddButton(_("OpenFolder"), _("OpenFolderDesc"), (sender, args) => { if (args.Button == 0) { Process.Start($"file://{Path.Combine(Environment.CurrentDirectory, "Localizer")}"); } }); AddButton(_("Export"), _("ExportDesc"), (sender, args) => { if (args.Button == 0) { Export(false); } }); AddButton(_("ExportWithTranslation"), _("ExportWithTranslationDesc"), (sender, args) => { if (args.Button == 0) { Export(true); } }); _split = new SplitContainer { Margin = new Margin(0, 10, 0, 0), Dock = DockStyle.Fill }; _split.SplitButton.Style = "button"; _split.SplitFrame1.AutoSize = AutoSize.Horizontal; _split.SplitFrame2.AutoSize = AutoSize.Horizontal; Controls.Add(_split); _split.SplitFrame1.Controls.Add(_modList); _modList.SelectedItemChanged += (sender, value) => RefreshPkgList(); _split.SplitFrame2.Controls.Add(_pkgList); RefreshModList(); LoadPackages().ContinueWith(_ => RefreshOnlinePackages(refreshBtn)); } private void Export(bool withTranslation) { try { if (string.IsNullOrWhiteSpace(_modList.SelectedItem?.Text ?? "")) { return; } var name = _modList.SelectedItem.Text; var mod = Localizer.GetWrappedMod(name); var enabledPackages = pkgManager.PackageGroups .FirstOrDefault(g => g.Mod.Name == name)?.Packages .Where(p => p.Enabled) .OrderBy(p => p.ModVersion ?? new Version(0, 0, 0, 0)) .ToList(); var oldPack = enabledPackages?.FirstOrDefault(); var package = new DataModel.Default.Package { Name = oldPack?.Name ?? name, LocalizedModName = oldPack?.LocalizedModName ?? name, Language = CultureInfo.GetCultureInfo(Language.ActiveCulture.Name), ModName = name, Files = new ObservableCollection(), Version = oldPack?.Version ?? new Version("1.0.0.0"), Author = oldPack?.Author ?? "", Description = oldPack?.Description ?? "", Mod = mod, ModVersion = Version.Parse($"{Math.Max(mod.Version.Major, 0)}.{Math.Max(mod.Version.Minor, 0)}.{Math.Max(mod.Version.Build, 0)}.{Math.Max(mod.Version.Revision, 0)}") }; var dirPath = Utils.EscapePath(Path.Combine(Localizer.SourcePackageDirPath, name)); packageExportService.Export(package, new DataModel.Default.ExportConfig { WithTranslation = withTranslation }); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } if (enabledPackages != null && enabledPackages.Count > 0) { oldPack.ModVersion = package.ModVersion; var updateLogger = Localizer.Kernel.Get(); updateLogger.Init($"{package.Name}-{Utils.DateTimeToFileName(DateTime.Now)}"); foreach (var item in enabledPackages.Skip(1)) { packageUpdateService.Update(oldPack, item, updateLogger); } packageUpdateService.Update(oldPack, package, updateLogger); packageSaveService.Save(oldPack, dirPath, fileSaveService); } else { packageSaveService.Save(package, dirPath, fileSaveService); } } catch (Exception e) { Localizer.Log.Error(e); } } private Task RefreshOnlinePackages(Control sender) { return Task.Run(() => { try { loading = true; sender.Enabled = false; onlinePackages?.Clear(); onlinePackages = packageBrowserService.GetList().ToList(); } catch { } finally { loading = false; sender.Enabled = true; RefreshPkgList(); } }); } private Task LoadPackages() { return Task.Run(() => { try { loading = true; pkgManager.PackageGroups = new List(); foreach (var dir in new DirectoryInfo(Localizer.SourcePackageDirPath).GetDirectories()) { try { var package2 = sourcePackageLoadServiceService.Load(dir.FullName, fileLoadService); if (package2 != null) { pkgManager.AddPackage(package2); } } catch { } } var list = Directory.GetFiles(Localizer.DownloadPackageDirPath).ToList(); list.AddRange(Directory.GetFiles(Path.Combine(Terraria.Main.SavePath, "Mods"), "*.locpack")); foreach (var file in list) { try { var package = packedPackageLoadServiceService.Load(file, fileLoadService); if (package != null) { pkgManager.AddPackage(package); } } catch { } } pkgManager.LoadState(); } catch (Exception o) { Utils.LogError(o); } finally { loading = false; RefreshPkgList(); } }); } private object refreshLock = new object(); private void RefreshPkgList() { string TrimEndingZero(string input) { while (input.EndsWith(".0")) { input = input.Substring(0, input.Length - 2); } return input; } lock (refreshLock) { UIModsPatch.ModsExtraInfo = pkgManager.PackageGroups.ToDictionary(group => group.Mod.Name, group => { var localizedModName = group.Packages.FirstOrDefault(pack => !string.IsNullOrWhiteSpace(pack.LocalizedModName))?.LocalizedModName; return $"{localizedModName}{Environment.NewLine}{string.Join(Environment.NewLine, group.Packages.Select(UI.GetPkgLabelText))}"; }); var modName = _modList.SelectedItem?.Text ?? ""; try { _split.SplitFrame2.Controls.Clear(); _pkgList.Items.Clear(); _split.SplitFrame2.Controls.Add(_pkgList); var packageGroup = pkgManager.PackageGroups.FirstOrDefault(g => g.Mod.Name == modName)?.Packages.ToList(); var onlineGroup = onlinePackages.Where(g => g.ModName == modName).ToList(); var displayedPackages = new Dictionary(); if (packageGroup != null) { foreach (var p in packageGroup) { // TODO: Use better key for HashSet var item = new ListBoxItem { Text = UI.GetPkgLabelText(p), Tooltip = (Gui.Renderer as UIRenderer).WordWrap(p.Description, 400), TextWrap = true, Dock = DockStyle.Top, AutoSize = AutoSize.Vertical }; item.MouseClick += (sender, args) => { if (args.Button == 0) { UIModsPatch.ReloadRequired = true; p.Enabled = !p.Enabled; item.Text = UI.GetPkgLabelText(p); pkgManager.SaveState(); } }; displayedPackages.Add(TrimEndingZero($"{p.ModName}_{p.Author}_{p.Version}"), item); _pkgList.Items.Add(item); } } if (onlineGroup != null) { foreach (var p in onlineGroup) { if (displayedPackages.ContainsKey(TrimEndingZero($"{p.ModName}_{p.Author}_{p.Version}"))) { continue; } var update = displayedPackages.Any(kvp => kvp.Key.StartsWith($"{p.ModName}_{p.Author}_")); if (update) { var existing = displayedPackages.FirstOrDefault(kvp => kvp.Key.StartsWith($"{p.ModName}_{p.Author}_")).Key.Substring($"{p.ModName}_{p.Author}_".Length); if (Version.TryParse(existing, out var localVer) && localVer >= p.Version) { update = false; } } var item = new ListBoxItem { Text = _("PackageDisplay", _(update ? "PackageUpdate" : "PackageOnline"), p.Name, p.Version, p.Author), Tooltip = (Gui.Renderer as UIRenderer).WordWrap(p.Description, 400), TextWrap = true, Dock = DockStyle.Top, AutoSize = AutoSize.Vertical }; item.MouseClick += (sender, args) => DownloadPackage(args, p); displayedPackages.Add(TrimEndingZero($"{p.ModName}_{p.Author}_{p.Version}"), item); _pkgList.Items.Add(item); } } if (displayedPackages.Count == 0) { _split.SplitFrame2.Controls.Add(new Label { Text = _(loading ? "PackageLoading" : "NoPackageFound"), TextWrap = true, AutoSize = AutoSize.Vertical, Dock = DockStyle.Fill, AllowFocus = false }); } } catch (Exception o) { Utils.LogError(o); } } } private void DownloadPackage(MouseEventArgs args, IPackage p) { if (args.Button == 0) { Task.Run(() => { try { Utils.LogDebug($"Requesting {p.Name} download"); var url = packageBrowserService.GetDownloadLinkOf(p); var path = Utils.EscapePath(Path.Combine(Localizer.DownloadPackageDirPath, $"{p.Name}_{p.Author}.locpack")); downloadManagerService.Download(url, path); UIModsPatch.ReloadRequired = true; Utils.LogDebug($"{p.Name} is downloaded"); LoadPackages(); } catch { } }); } } private void RefreshModList() { _modList.Items.Clear(); foreach (var loadedMod in Utils.GetLoadedMods()) { if (loadedMod != null && loadedMod.Name != Localizer.LoadedLocalizer.Name) { _modList.Items.Add(new ListBoxItem { Text = loadedMod.Name, Tooltip = $"{loadedMod.DisplayName} (v{loadedMod.Version})" }); } } } } } ================================================ FILE: Localizer/UIs/Stylesheet.cs ================================================ using System.Collections.Generic; using Squid; namespace Localizer.UIs { public class Stylesheet { public static Skin GetSkin() { var skin = new Skin(); foreach (var s in GetControlStyles()) { skin.Add(s.Key, s.Value); } return skin; } public static CursorCollection GetCursorSet() { var cursorSize = new Point(32, 32); var halfSize = cursorSize / 2; return new CursorCollection() { {CursorNames.Default, new Cursor { Texture = GetTexturePath("Cursors/Arrow"), Size = cursorSize, HotSpot = Point.Zero }}, {CursorNames.Link, new Cursor { Texture = GetTexturePath("Cursors/Link"), Size = cursorSize, HotSpot = Point.Zero }}, {CursorNames.Move, new Cursor { Texture = GetTexturePath("Cursors/Move"), Size = cursorSize, HotSpot = halfSize }}, {CursorNames.Select, new Cursor { Texture = GetTexturePath("Cursors/Select"), Size = cursorSize, HotSpot = halfSize }}, {CursorNames.SizeNS, new Cursor { Texture = GetTexturePath("Cursors/SizeNS"), Size = cursorSize, HotSpot = halfSize }}, {CursorNames.SizeWE, new Cursor { Texture = GetTexturePath("Cursors/SizeWE"), Size = cursorSize, HotSpot = halfSize }}, {CursorNames.HSplit, new Cursor { Texture = GetTexturePath("Cursors/SizeNS"), Size = cursorSize, HotSpot = halfSize }}, {CursorNames.VSplit, new Cursor { Texture = GetTexturePath("Cursors/SizeWE"), Size = cursorSize, HotSpot = halfSize }}, {CursorNames.SizeNESW, new Cursor { Texture = GetTexturePath("Cursors/SizeNESW"), Size = cursorSize, HotSpot = halfSize }}, {CursorNames.SizeNWSE, new Cursor { Texture = GetTexturePath("Cursors/SizeNWSE"), Size = cursorSize, HotSpot = halfSize }}, }; } private static Dictionary GetControlStyles() { var baseStyle = new ControlStyle() { Tiling = TextureMode.Grid, Grid = new Margin(3), Texture = GetTexturePath("button_hot"), Default = { Texture = GetTexturePath("button_default"), }, Pressed = { Texture = GetTexturePath("button_down"), }, Selected = { Texture = GetTexturePath("button_down"), }, Focused = { Texture = GetTexturePath("button_down"), }, SelectedPressed = { Texture = GetTexturePath("button_down"), }, SelectedHot = { Texture = GetTexturePath("button_down"), }, }; return new Dictionary() { {"item", new ControlStyle(baseStyle) { TextPadding = new Margin(8, 0, 8, 0), TextAlign = Alignment.MiddleLeft, }}, {"button", new ControlStyle(baseStyle) { TextPadding = new Margin(0), TextAlign = Alignment.MiddleCenter, }}, {"tooltip", new ControlStyle(baseStyle) { TextPadding = new Margin(8), TextAlign = Alignment.TopLeft, }}, {"textbox", new ControlStyle(baseStyle) { Texture = GetTexturePath("input_default"), TextPadding = new Margin(8), Tiling = TextureMode.Grid, Grid = new Margin(3), Hot = { Texture = GetTexturePath("input_focused") }, Focused = { Texture = GetTexturePath("input_focused"), Tint = ColorInt.ARGB(1, 1, 0, 0), }, }}, {"window", new ControlStyle() { Tiling = TextureMode.Grid, Grid = new Margin(9), Texture = GetTexturePath("window"), }}, {"frame", new ControlStyle() { Tiling = TextureMode.Grid, Grid = new Margin(4), Texture = GetTexturePath("frame"), TextPadding = new Margin(8), }}, {"vscrollTrack", new ControlStyle() { Tiling = TextureMode.Grid, Grid = new Margin(3), Texture = GetTexturePath("vscroll_track"), }}, {"vscrollButton", new ControlStyle() { Tiling = TextureMode.Grid, Grid = new Margin(3), Texture = GetTexturePath("vscroll_button"), Hot = { Texture = GetTexturePath("vscroll_button_hot"), }, Pressed = { Texture = GetTexturePath("vscroll_button_down"), }, }}, {"vscrollUp", new ControlStyle() { Default = { Texture = GetTexturePath("vscrollUp_default"), }, Hot = { Texture = GetTexturePath("vscrollUp_hot"), }, Pressed = { Texture = GetTexturePath("vscrollUp_down"), }, Focused = { Texture = GetTexturePath("vscrollUp_hot"), }, }}, {"hscrollTrack", new ControlStyle() { Tiling = TextureMode.Grid, Grid = new Margin(3), Texture = GetTexturePath("hscroll_track"), }}, {"hscrollButton", new ControlStyle() { Tiling = TextureMode.Grid, Grid = new Margin(3), Texture = GetTexturePath("hscroll_button"), Hot = { Texture = GetTexturePath("hscroll_button_hot"), }, Pressed = { Texture = GetTexturePath("hscroll_button_down"), }, }}, {"hscrollUp", new ControlStyle() { Default = { Texture = GetTexturePath("hscrollUp_default"), }, Hot = { Texture = GetTexturePath("hscrollUp_hot"), }, Pressed = { Texture = GetTexturePath("hscrollUp_down"), }, Focused = { Texture = GetTexturePath("hscrollUp_hot"), }, }}, {"checkBox", new ControlStyle() { Default = { Texture = GetTexturePath("checkbox_default"), }, Hot = { Texture = GetTexturePath("checkbox_hot"), }, Pressed = { Texture = GetTexturePath("checkbox_down"), }, Checked = { Texture = GetTexturePath("checkbox_checked"), }, CheckedFocused = { Texture = GetTexturePath("checkbox_checked_hot"), }, CheckedHot = { Texture = GetTexturePath("checkbox_checked_hot"), }, CheckedPressed = { Texture = GetTexturePath("checkbox_down"), }, }}, {"comboLabel", new ControlStyle() { TextPadding = new Margin(10, 0, 0, 0), Tiling = TextureMode.Grid, Grid = new Margin(3, 0, 0, 0), Default = { Texture = GetTexturePath("combo_default"), }, Hot = { Texture = GetTexturePath("combo_hot"), }, Pressed = { Texture = GetTexturePath("combo_down"), }, Focused = { Texture = GetTexturePath("combo_hot"), }, }}, {"comboButton", new ControlStyle() { Default = { Texture = GetTexturePath("combo_button_default"), }, Hot = { Texture = GetTexturePath("combo_button_hot"), }, Pressed = { Texture = GetTexturePath("combo_button_down"), }, Focused = { Texture = GetTexturePath("combo_button_hot"), }, }}, {"multiline", new ControlStyle() { TextPadding = new Margin(8), TextAlign = Alignment.TopLeft, }}, {"label", new ControlStyle() { TextPadding = new Margin(8, 0, 8, 0), TextAlign = Alignment.MiddleLeft, TextColor = ColorInt.ARGB(1, .8f, .8f, .8f), BackColor = 0, }}, }; } private static string GetTexturePath(string name) { return $"UIs/Assets/{name}"; } } } ================================================ FILE: Localizer/UIs/UIDesktop.cs ================================================ using Localizer.UIs.Views; using Squid; namespace Localizer.UIs { public class UIDesktop : Desktop { public TestView TestView; public ReloadPluginView ReloadPluginView; public UIDesktop() { // TestView = new TestView(); // TestView.Parent = this; //ReloadPluginView = new ReloadPluginView //{ //Parent = this //}; } public void AddWindow(Window window) { window.Parent = this; } } } ================================================ FILE: Localizer/UIs/UIHost.cs ================================================ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Squid; using Terraria; using ButtonState = Microsoft.Xna.Framework.Input.ButtonState; namespace Localizer.UIs { public class UIHost : Disposable { public UIDesktop Desktop { get; private set; } private int _lastScroll; private GraphicsDevice gd; public UIHost() { gd = Main.graphics.GraphicsDevice; Gui.Renderer = new UIRenderer(); Desktop = new UIDesktop { Name = "localizer" }; Desktop.ShowCursor = true; Desktop.Skin = Stylesheet.GetSkin(); Desktop.Size = new Squid.Point(gd.Viewport.Width, gd.Viewport.Height); } internal void Update(GameTime time) { Gui.TimeElapsed = (float)time.ElapsedGameTime.TotalMilliseconds; if (Main.graphics.GraphicsDevice.Viewport.Width != Desktop.Size.x || Main.graphics.GraphicsDevice.Viewport.Height != Desktop.Size.y) { Desktop.Size = new Squid.Point(gd.Viewport.Width, gd.Viewport.Height); } if (!Main.hasFocus) { return; } // Mouse var mouseState = Mouse.GetState(); var wheel = mouseState.ScrollWheelValue > _lastScroll ? -1 : (mouseState.ScrollWheelValue < _lastScroll ? 1 : 0); _lastScroll = mouseState.ScrollWheelValue; Gui.SetMouse(mouseState.X, mouseState.Y, wheel); Gui.SetButtons(mouseState.LeftButton == ButtonState.Pressed, mouseState.RightButton == ButtonState.Pressed); //TODO: Keyboard Input Support } internal void Draw(GameTime time) { Desktop.Update(); Desktop.Draw(); } protected override void DisposeUnmanaged() { Gui.Renderer = null; } } } ================================================ FILE: Localizer/UIs/UIModsPatch.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; using Harmony; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.GameContent.UI.Elements; using Terraria.Localization; using Terraria.UI.Chat; using static Localizer.Lang; namespace Localizer.UIs { internal static class UIModsPatch { internal static bool ReloadRequired; private static int frameCounter; internal static Dictionary ModsExtraInfo; public static void Patch() { ReloadRequired = false; frameCounter = 0; if (ModsExtraInfo == null) { ModsExtraInfo = new Dictionary(); } var refHolder = false; Localizer.Harmony.Patch("Terraria.ModLoader.Config.ConfigManager", "ModNeedsReload", postfix: NoroHelper.HarmonyMethod(() => ModNeedsReloadPostfix(ref refHolder))); Localizer.Harmony.Patch("Terraria.ModLoader.UI.UIModItem", "OnInitialize", postfix: NoroHelper.HarmonyMethod(() => UIModItemPostfix(null))); Localizer.Harmony.Patch("Terraria.ModLoader.UI.UIModItem", "DrawSelf", postfix: NoroHelper.HarmonyMethod(() => DrawSelfPostfix(null, null))); Localizer.Harmony.Patch("Terraria.ModLoader.UI.ModBrowser.UIModBrowser", "PopulateFromJson", prefix: NoroHelper.HarmonyMethod(() => PopulateFromJsonPrefix()), postfix: NoroHelper.HarmonyMethod(() => PopulateFromJsonPostfix())); } private static void PopulateFromJsonPrefix() { Localizer.LoadedLocalizer.File.SetField("k__BackingField", "Localizer"); Localizer.LoadedLocalizer.SetField("name", "Localizer"); } private static void PopulateFromJsonPostfix() { Localizer.LoadedLocalizer.File.SetField("k__BackingField", "!Localizer"); Localizer.LoadedLocalizer.SetField("name", "!Localizer"); } private static void ModNeedsReloadPostfix(ref bool __result) { if (ReloadRequired) { __result = true; } } private static void DrawSelfPostfix(object __instance, SpriteBatch spriteBatch) { var current = __instance as UIPanel; var modName = __instance.ValueOf("_mod")?.ValueOf("Name")?.ToString(); var modNameHovering = current.ValueOf("_modName")?.IsMouseHovering ?? false; if (modName == "!Localizer") { frameCounter++; current.ValueOf("_modName") .SetField("_text", $"{Utils.AsRainbow("Localizer", frameCounter)} v{current.ValueOf("_mod").ValueOf("modFile").ValueOf("version")}"); var tooltip = ""; if (modNameHovering) { var modAuthor = current.ValueOf("_mod")?.ValueOf("properties").ValueOf("author"); if (modAuthor.Length > 0) { tooltip = _("OpenUI", Language.GetTextValue("tModLoader.ModsByline", Utils.AsRainbow(modAuthor, frameCounter + 150, 9)), $"{Utils.AsRainbow("Localizer", frameCounter)}"); } } if (!string.IsNullOrEmpty(tooltip)) { current.SetField("_tooltip", ""); var snippets = ChatManager.ParseMessage(tooltip, Color.White).ToArray(); var x = ChatManager.GetStringSize(Main.fontMouseText, snippets, Vector2.One).X; var pos = Main.MouseScreen + new Vector2(16f); pos.X = Math.Min(pos.X, Main.screenWidth - x - 16f); pos.Y = Math.Min(pos.Y, Main.screenHeight - 30); ChatManager.DrawColorCodedStringWithShadow(spriteBatch, Main.fontMouseText, snippets, pos, 0, Vector2.Zero, Vector2.One, out var _); } } else if (modNameHovering && ModsExtraInfo.ContainsKey(modName)) { current.SetField("_tooltip", current.ValueOf("_tooltip") + Environment.NewLine + ModsExtraInfo[modName]); } } private static void UIModItemPostfix(object __instance) { var modName = __instance.ValueOf("_mod")?.ValueOf("Name")?.ToString(); if (modName == "!Localizer") { __instance.ValueOf("_modName").OnClick += (evt, element) => { if (Localizer.PackageUI != null) { Localizer.PackageUI.Visible = true; } else { Localizer.PackageUI = new MainWindow(); Localizer.Instance.UIHost.Desktop.AddWindow(Localizer.PackageUI); } }; } } } } ================================================ FILE: Localizer/UIs/UIRenderer.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Localizer.Helpers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ReLogic.Graphics; using Squid; using Terraria; using Terraria.UI.Chat; using Point = Squid.Point; using Rectangle = Microsoft.Xna.Framework.Rectangle; namespace Localizer.UIs { public class UIRenderer : ISquidRenderer { private SpriteBatch _spriteBatch; private Dictionary textureIDs; private Dictionary textures; private Dictionary fontIDs; private Dictionary fonts; private Texture2D _blankTexture; private RasterizerState _rasterizer; private SamplerState _sampler; public UIRenderer() { _spriteBatch = new SpriteBatch(Main.graphics.GraphicsDevice); _blankTexture = new Texture2D(_spriteBatch.GraphicsDevice, 1, 1); _blankTexture.SetData(new[] { new Color(255, 255, 255, 255) }); textureIDs = new Dictionary(); textures = new Dictionary(); fontIDs = new Dictionary(); fonts = new Dictionary(); var modTextures = Localizer.Instance.ValueOf>("textures"); foreach (var t in modTextures) { AddTexture(t.Key, t.Value); } AddFont("default", Main.fontMouseText); AddFont("mouse", Main.fontMouseText); AddFont("item", Main.fontItemStack); AddFont("death", Main.fontDeathText); _rasterizer = new RasterizerState { ScissorTestEnable = true }; _sampler = new SamplerState { Filter = TextureFilter.Anisotropic }; } public void AddFont(string key, DynamicSpriteFont font) { var index = fontIDs.Count; fontIDs.Add(key, index); fonts.Add(index, font); } public void AddTexture(string key, Texture2D tex) { var index = textureIDs.Count; textureIDs.Add(key, index); textures.Add(index, tex); } public void Dispose() { } public int GetTexture(string name) { return textureIDs[name]; } public int GetFont(string name) { return fontIDs[name]; } public Point GetTextSize(string text, int font) { var size = ChatManager.GetStringSize(fonts[fontIDs["default"]], text, new Vector2(1)); return new Point((int)size.X, (int)size.Y); } public string WordWrap(string text, int width) { var result = Terraria.Utils.WordwrapStringSmart(text, Color.White, fonts[fontIDs["default"]], width, -1); return string.Join(Environment.NewLine, result.Select(line => string.Join("", line.Select(ts => ts.Text)))); } public Point GetTextureSize(int texture) { var tex = textures[texture]; return new Point(tex.Width, tex.Height); } public void Scissor(int x, int y, int w, int h) { Main.graphics.GraphicsDevice.ScissorRectangle = new Rectangle(Math.Max(x, 0), Math.Max(y, 0), Math.Min(w, Main.screenWidth), Math.Min(h, Main.screenHeight)); } public void DrawBox(int x, int y, int w, int h, int color) { var rect = new Rectangle(x, y, w, h); _spriteBatch.Draw(_blankTexture, rect, rect, ColorFromtInt32(color)); } private Color ColorFromtInt32(int color) { var bytes = BitConverter.GetBytes(color); return new Color(bytes[2], bytes[1], bytes[0], bytes[3]); } public void DrawText(string text, int x, int y, int font, int color) { var snippets = ChatManager.ParseMessage(text, ColorFromtInt32(color)).ToArray(); // Terraria.Utils.DrawBorderStringFourWay(_spriteBatch, // fonts[font], text, x, y + 3, // ColorFromtInt32(color), // Color.Black, Vector2.Zero, 1f); ChatManager.DrawColorCodedString( _spriteBatch, fonts[font], snippets, new Vector2(x, y + 3), ColorFromtInt32(color), 0, Vector2.Zero, Vector2.One, out var i, 99999); } public void DrawTexture(int texture, int x, int y, int w, int h, Squid.Rectangle rect, int color) { var destination = new Rectangle(x, y, w, h); var source = new Rectangle(rect.Left, rect.Top, rect.Width, rect.Height); _spriteBatch.Draw(textures[texture], destination, source, ColorFromtInt32(color)); } public bool TranslateKey(int scancode, ref char character) { character = ' '; return true; } public void StartBatch() { _spriteBatch.SafeBegin(); } public void EndBatch(bool final) { _spriteBatch.SafeEnd(); } } } ================================================ FILE: Localizer/UIs/Views/ManagerView.cs ================================================ namespace Localizer.UIs.Views { } ================================================ FILE: Localizer/UIs/Views/ReloadPluginView.cs ================================================ using Localizer.UIs.Components; using Squid; namespace Localizer.UIs.Views { public class ReloadPluginView : BasicWindow { public ReloadPluginView() { Size = new Point(40, 40); Position = new Point(0, 0); Resizable = false; var reloadPlugins = new Button() { Size = new Point(40, 40), Style = "button", }; reloadPlugins.MouseClick += (sender, args) => { Localizer.Kernel.UnloadAllPlugins(); Localizer.Kernel.LoadPlugins(); }; Controls.Add(reloadPlugins); } } } ================================================ FILE: Localizer/UIs/Views/TestView.cs ================================================ using Localizer.UIs.Components; using Squid; namespace Localizer.UIs.Views { public class TestView : BasicWindow { public TestView() { Size = new Point(440, 340); Position = new Point(40, 40); Titlebar.Text = "[color=FfFfFf00]BBCode[/color]中文测试"; Resizable = true; var label1 = new Label { Text = "Username:", Size = new Point(122, 35), Position = new Point(60, 100), Parent = this }; label1.MousePress += (sender, args) => { }; var textbox1 = new TextBox { Name = "textbox" }; textbox1.Text = "username"; textbox1.Size = new Point(222, 35); textbox1.Position = new Point(180, 100); textbox1.Style = "textbox"; textbox1.Parent = this; textbox1.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right; var label2 = new Label { Text = "Password:", Size = new Point(122, 35), Position = new Point(60, 140), Parent = this }; var textbox2 = new TextBox { Name = "textbox" }; textbox2.PasswordChar = char.Parse("*"); textbox2.IsPassword = true; textbox2.Text = "password"; textbox2.Size = new Point(222, 35); textbox2.Position = new Point(180, 140); textbox2.Style = "textbox"; textbox2.Parent = this; textbox2.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right; var button = new Button { Size = new Point(157, 35), Position = new Point(437 - 192, 346 - 52), Text = "Login", Style = "button", Parent = this, Anchor = AnchorStyles.Bottom | AnchorStyles.Right, Cursor = CursorNames.Link }; button.MouseClick += (sender, args) => { }; var combo = new DropDownList { Size = new Point(222, 35), Position = new Point(180, 180), Parent = this }; combo.Label.Style = "comboLabel"; combo.Button.Style = "comboButton"; combo.Listbox.Margin = new Margin(0, 6, 0, 0); combo.Listbox.Style = "frame"; combo.Listbox.ClipFrame.Margin = new Margin(8, 8, 8, 8); combo.Listbox.Scrollbar.Margin = new Margin(0, 4, 4, 4); combo.Listbox.Scrollbar.Size = new Point(14, 10); combo.Listbox.Scrollbar.ButtonUp.Style = "vscrollUp"; combo.Listbox.Scrollbar.ButtonUp.Size = new Point(10, 20); combo.Listbox.Scrollbar.ButtonDown.Style = "vscrollUp"; combo.Listbox.Scrollbar.ButtonDown.Size = new Point(10, 20); combo.Listbox.Scrollbar.Slider.Margin = new Margin(0, 2, 0, 2); combo.Listbox.Scrollbar.Slider.Style = "vscrollTrack"; combo.Listbox.Scrollbar.Slider.Button.Style = "vscrollButton"; combo.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right; for (var i = 0; i < 10; i++) { var item = new ListBoxItem(); var label = new Label() { Text = "listboxitem", Size = new Point(100, 35), Margin = new Margin(0, 0, 0, 4), Style = "item", }; item.Container.Controls.Add(label); combo.Items.Add(item); if (i == 3) { item.Selected = true; } } var box = new CheckBox { Size = new Point(157, 26), Position = new Point(180, 220), Text = "Remember me", Parent = this }; box.Button.Style = "checkBox"; box.Button.Size = new Point(26, 26); box.Button.Cursor = CursorNames.Link; } } } ================================================ FILE: Localizer/build.txt ================================================ author = Chireiden Team version = 1.5.0.19 displayName = Localizer hideCode = true hideResources = false includeSource = false homepage = https://github.com/chi-rei-den/Localizer/ buildIgnore = *.user, obj\*, bin\*, .vs\*, .git*, referenceImages*.png, .gitattributes, *.csproj includePDB = false dllReferences = Ninject,0Harmony,Squid side = NoSync ================================================ FILE: Localizer/description.txt ================================================ Provide localization functions include: - Extract texts from mods - Apply translations to mods - Create your own translation package - Download user generated packages from Localizer Currently this mod is in hard developing, docs and manuals are not built. ================================================ FILE: Localizer.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.29324.140 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Localizer", "Localizer\Localizer.csproj", "{95D54B28-B67B-4248-B83A-B5E5426C3806}" ProjectSection(ProjectDependencies) = postProject {D05E5CFB-866F-43D1-BBFE-7CA84249CF36} = {D05E5CFB-866F-43D1-BBFE-7CA84249CF36} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LocalizerTest", "LocalizerTest\LocalizerTest.csproj", "{019C1A68-7B2C-400C-BCAE-FC9EF658A3BC}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModPatch", "ModPatch\ModPatch.csproj", "{D05E5CFB-866F-43D1-BBFE-7CA84249CF36}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Squid", "Squid\Squid.csproj", "{205C6E4A-4F9C-44FE-BB81-48F9914F048F}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {95D54B28-B67B-4248-B83A-B5E5426C3806}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {95D54B28-B67B-4248-B83A-B5E5426C3806}.Debug|Any CPU.Build.0 = Debug|Any CPU {95D54B28-B67B-4248-B83A-B5E5426C3806}.Debug|x86.ActiveCfg = Debug|Any CPU {95D54B28-B67B-4248-B83A-B5E5426C3806}.Debug|x86.Build.0 = Debug|Any CPU {95D54B28-B67B-4248-B83A-B5E5426C3806}.Release|Any CPU.ActiveCfg = Release|Any CPU {95D54B28-B67B-4248-B83A-B5E5426C3806}.Release|Any CPU.Build.0 = Release|Any CPU {95D54B28-B67B-4248-B83A-B5E5426C3806}.Release|x86.ActiveCfg = Release|Any CPU {95D54B28-B67B-4248-B83A-B5E5426C3806}.Release|x86.Build.0 = Release|Any CPU {019C1A68-7B2C-400C-BCAE-FC9EF658A3BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {019C1A68-7B2C-400C-BCAE-FC9EF658A3BC}.Debug|Any CPU.Build.0 = Debug|Any CPU {019C1A68-7B2C-400C-BCAE-FC9EF658A3BC}.Debug|x86.ActiveCfg = Debug|Any CPU {019C1A68-7B2C-400C-BCAE-FC9EF658A3BC}.Debug|x86.Build.0 = Debug|Any CPU {019C1A68-7B2C-400C-BCAE-FC9EF658A3BC}.Release|Any CPU.ActiveCfg = Release|Any CPU {019C1A68-7B2C-400C-BCAE-FC9EF658A3BC}.Release|Any CPU.Build.0 = Release|Any CPU {019C1A68-7B2C-400C-BCAE-FC9EF658A3BC}.Release|x86.ActiveCfg = Release|Any CPU {019C1A68-7B2C-400C-BCAE-FC9EF658A3BC}.Release|x86.Build.0 = Release|Any CPU {D05E5CFB-866F-43D1-BBFE-7CA84249CF36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D05E5CFB-866F-43D1-BBFE-7CA84249CF36}.Debug|Any CPU.Build.0 = Debug|Any CPU {D05E5CFB-866F-43D1-BBFE-7CA84249CF36}.Debug|x86.ActiveCfg = Debug|Any CPU {D05E5CFB-866F-43D1-BBFE-7CA84249CF36}.Debug|x86.Build.0 = Debug|Any CPU {D05E5CFB-866F-43D1-BBFE-7CA84249CF36}.Release|Any CPU.ActiveCfg = Release|Any CPU {D05E5CFB-866F-43D1-BBFE-7CA84249CF36}.Release|Any CPU.Build.0 = Release|Any CPU {D05E5CFB-866F-43D1-BBFE-7CA84249CF36}.Release|x86.ActiveCfg = Release|Any CPU {D05E5CFB-866F-43D1-BBFE-7CA84249CF36}.Release|x86.Build.0 = Release|Any CPU {205C6E4A-4F9C-44FE-BB81-48F9914F048F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {205C6E4A-4F9C-44FE-BB81-48F9914F048F}.Debug|Any CPU.Build.0 = Debug|Any CPU {205C6E4A-4F9C-44FE-BB81-48F9914F048F}.Debug|x86.ActiveCfg = Debug|Any CPU {205C6E4A-4F9C-44FE-BB81-48F9914F048F}.Debug|x86.Build.0 = Debug|Any CPU {205C6E4A-4F9C-44FE-BB81-48F9914F048F}.Release|Any CPU.ActiveCfg = Release|Any CPU {205C6E4A-4F9C-44FE-BB81-48F9914F048F}.Release|Any CPU.Build.0 = Release|Any CPU {205C6E4A-4F9C-44FE-BB81-48F9914F048F}.Release|x86.ActiveCfg = Release|Any CPU {205C6E4A-4F9C-44FE-BB81-48F9914F048F}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {205BC2C0-6C22-4D90-B9CA-A44D33E09BAC} EndGlobalSection EndGlobal ================================================ FILE: Localizer.sln.DotSettings ================================================  True True ================================================ FILE: LocalizerTest/DataModel/GitHubUpdateInfoTest.cs ================================================ using System; using FluentAssertions; using Localizer.DataModel; using Localizer.DataModel.Default; using Xunit; namespace LocalizerTest.DataModel { public class GitHubUpdateInfoTest { [Fact] public void Parse_Correct() { var info = new GitHubUpdateInfo("a1.2.3.4"); info.Type.Should().Be(UpdateType.Minor); info.Version.Should().BeEquivalentTo(Version.Parse("1.2.3.4")); } } } ================================================ FILE: LocalizerTest/Helper/ExtensionsTest.cs ================================================ using System; using FluentAssertions; using Localizer.DataModel.Default; using Localizer.Helpers; using Xunit; namespace LocalizerTest.Helper { public class ExtensionsTest { [Theory] [InlineData(typeof(BasicItemFile), 1, "Items")] [InlineData(typeof(BasicNPCFile), 1, "NPCs")] [InlineData(typeof(BasicBuffFile), 1, "Buffs")] [InlineData(typeof(BasicPrefixFile), 1, "Prefixes")] [InlineData(typeof(BasicProjectileFile), 1, "Projectiles")] public void ModTranslationOwnerField_Correct(Type type, int count, string name) { type.ModTranslationOwnerField().Length.Should().Be(count); type.ModTranslationOwnerField()[0].Name.Should().Be(name); } [Fact] public void ModTranslationOwnerFieldName_Correct() { var prop = typeof(BasicItemFile).ModTranslationOwnerField()[0]; prop.ModTranslationOwnerFieldName().Should().Be("items"); } [Fact] public void ModTranslationProp_Correct() { var props = typeof(ItemEntry).ModTranslationProp(); props.Length.Should().Be(2); props.Should().ContainSingle(p => p.Name == "Name"); props.Should().ContainSingle(p => p.Name == "Tooltip"); } } } ================================================ FILE: LocalizerTest/Helper/UtilsTest.cs ================================================ using FluentAssertions; using Localizer.DataModel.Default; using Xunit; using ModUtils = Localizer.Utils; namespace LocalizerTest.Helper { public class UtilsTest { [Fact] public void CreateEntryMappings_Correct() { var mappings = ModUtils.CreateEntryMappings(typeof(ItemEntry)); mappings["DisplayName"].Name.Should().Be("Name"); mappings["Tooltip"].Name.Should().Be("Tooltip"); } [Fact] public void GetMethodBase_Correct() { var thisMethod = ModUtils.GetMethodBase("System.Void LocalizerTest.Helper.UtilsTest::GetMethodBase_Correct()"); thisMethod.Name.Should().Be(nameof(GetMethodBase_Correct)); } [Fact] public void GetMethodBase_Wrong() { var thisMethod = ModUtils.GetMethodBase(""); thisMethod.Should().BeNull(); } [Fact] public void GetTranslationEntry_Correct() { var testEntry = new ItemEntry { Name = new BaseEntry { Origin = "Test", Translation = "Case" }, Tooltip = new BaseEntry { Origin = "Test", Translation = "Case" } }; var nameTranslation = ModUtils.GetTranslationOfEntry(testEntry, typeof(ItemEntry).GetProperty("Name")); nameTranslation.Should().Be("Case"); var tooltipTranlation = ModUtils.GetTranslationOfEntry(testEntry, typeof(ItemEntry).GetProperty("Tooltip")); tooltipTranlation.Should().Be("Case"); } } } ================================================ FILE: LocalizerTest/LocalizerTest.cs ================================================ using System; using FluentAssertions; using Localizer; using Localizer.Attributes; using Xunit; namespace LocalizerTest { [OperationTiming(OperationTiming.BeforeModCtor)] internal class FooA { } [OperationTiming(OperationTiming.BeforeModLoad)] internal class FooB { } [OperationTiming(OperationTiming.PostContentLoad)] internal class FooC { } [OperationTiming(OperationTiming.Any)] internal class FooD { } internal class FooE { } public class LocalizerTest { [Theory] [InlineData(OperationTiming.BeforeModCtor, OperationTiming.Any)] [InlineData(OperationTiming.BeforeModCtor, OperationTiming.BeforeModCtor)] [InlineData(OperationTiming.BeforeModLoad, OperationTiming.Any)] [InlineData(OperationTiming.BeforeModLoad, OperationTiming.BeforeModLoad)] [InlineData(OperationTiming.PostContentLoad, OperationTiming.Any)] [InlineData(OperationTiming.PostContentLoad, OperationTiming.PostContentLoad)] [InlineData(OperationTiming.PostContentLoad, OperationTiming.PostContentLoad | OperationTiming.BeforeModLoad)] public void CanDoOperationNow_True(OperationTiming state, OperationTiming operation) { Localizer.Localizer.State = state; Localizer.Localizer.CanDoOperationNow(operation).Should().BeTrue(); } [Theory] [InlineData(OperationTiming.BeforeModCtor, typeof(FooA))] [InlineData(OperationTiming.BeforeModLoad, typeof(FooD))] [InlineData(OperationTiming.PostContentLoad, typeof(FooE))] [InlineData(OperationTiming.BeforeModCtor, typeof(FooD))] [InlineData(OperationTiming.BeforeModCtor, typeof(FooE))] public void CanDoOperationNow_Type_True(OperationTiming state, Type t) { Localizer.Localizer.State = state; Localizer.Localizer.CanDoOperationNow(t).Should().BeTrue(); } [Theory] [InlineData(OperationTiming.BeforeModCtor, OperationTiming.BeforeModLoad)] [InlineData(OperationTiming.BeforeModCtor, OperationTiming.PostContentLoad)] [InlineData(OperationTiming.BeforeModLoad, OperationTiming.PostContentLoad)] [InlineData(OperationTiming.PostContentLoad, OperationTiming.BeforeModCtor)] [InlineData(OperationTiming.PostContentLoad, OperationTiming.BeforeModCtor | OperationTiming.BeforeModLoad)] public void CanDoOperationNow_False(OperationTiming state, OperationTiming operation) { Localizer.Localizer.State = state; Localizer.Localizer.CanDoOperationNow(operation).Should().BeFalse(); } [Theory] [InlineData(OperationTiming.BeforeModCtor, typeof(FooB))] [InlineData(OperationTiming.BeforeModCtor, typeof(FooC))] [InlineData(OperationTiming.PostContentLoad, typeof(FooB))] [InlineData(OperationTiming.PostContentLoad, typeof(FooA))] public void CanDoOperationNow_Type_False(OperationTiming state, Type t) { Localizer.Localizer.State = state; Localizer.Localizer.CanDoOperationNow(t).Should().BeFalse(); } } } ================================================ FILE: LocalizerTest/LocalizerTest.csproj ================================================  {019C1A68-7B2C-400C-BCAE-FC9EF658A3BC} {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} LocalizerTest net472 x86 7.3 {95d54b28-b67b-4248-b83a-b5e5426c3806} Localizer 5.9.0 3.3.4 2.4.1 2.4.1 runtime; build; native; contentfiles; analyzers; buildtransitive all ================================================ FILE: LocalizerTest/Network/GitHubModUpdateService.cs ================================================ using System; using FluentAssertions; using Localizer.DataModel; using Localizer.Network; using Newtonsoft.Json.Linq; using Xunit; namespace LocalizerTest.Network { public class GitHubModUpdateServiceTest { private GitHubModUpdate service; private JObject releaseInfo; public GitHubModUpdateServiceTest() { // From GitHub API doc's example. https://developer.github.com/v3/repos/releases/#get-the-latest-release // Modified the tag_name to b4.3.2.1 var jsonString = "{\"url\":\"https://api.github.com/repos/octocat/Hello-World/releases/1\",\"html_url\":\"https://github.com/octocat/Hello-World/releases/v1.0.0\",\"assets_url\":\"https://api.github.com/repos/octocat/Hello-World/releases/1/assets\",\"upload_url\":\"https://uploads.github.com/repos/octocat/Hello-World/releases/1/assets{?name,label}\",\"tarball_url\":\"https://api.github.com/repos/octocat/Hello-World/tarball/v1.0.0\",\"zipball_url\":\"https://api.github.com/repos/octocat/Hello-World/zipball/v1.0.0\",\"id\":1,\"node_id\":\"MDc6UmVsZWFzZTE=\",\"tag_name\":\"b4.3.2.1\",\"target_commitish\":\"master\",\"name\":\"v1.0.0\",\"body\":\"Description of the release\",\"draft\":false,\"prerelease\":false,\"created_at\":\"2013-02-27T19:35:32Z\",\"published_at\":\"2013-02-27T19:35:32Z\",\"author\":{\"login\":\"octocat\",\"id\":1,\"node_id\":\"MDQ6VXNlcjE=\",\"avatar_url\":\"https://github.com/images/error/octocat_happy.gif\",\"gravatar_id\":\"\",\"url\":\"https://api.github.com/users/octocat\",\"html_url\":\"https://github.com/octocat\",\"followers_url\":\"https://api.github.com/users/octocat/followers\",\"following_url\":\"https://api.github.com/users/octocat/following{/other_user}\",\"gists_url\":\"https://api.github.com/users/octocat/gists{/gist_id}\",\"starred_url\":\"https://api.github.com/users/octocat/starred{/owner}{/repo}\",\"subscriptions_url\":\"https://api.github.com/users/octocat/subscriptions\",\"organizations_url\":\"https://api.github.com/users/octocat/orgs\",\"repos_url\":\"https://api.github.com/users/octocat/repos\",\"events_url\":\"https://api.github.com/users/octocat/events{/privacy}\",\"received_events_url\":\"https://api.github.com/users/octocat/received_events\",\"type\":\"User\",\"site_admin\":false},\"assets\":[{\"url\":\"https://api.github.com/repos/octocat/Hello-World/releases/assets/1\",\"browser_download_url\":\"https://github.com/octocat/Hello-World/releases/download/v1.0.0/example.zip\",\"id\":1,\"node_id\":\"MDEyOlJlbGVhc2VBc3NldDE=\",\"name\":\"example.zip\",\"label\":\"short description\",\"state\":\"uploaded\",\"content_type\":\"application/zip\",\"size\":1024,\"download_count\":42,\"created_at\":\"2013-02-27T19:35:32Z\",\"updated_at\":\"2013-02-27T19:35:32Z\",\"uploader\":{\"login\":\"octocat\",\"id\":1,\"node_id\":\"MDQ6VXNlcjE=\",\"avatar_url\":\"https://github.com/images/error/octocat_happy.gif\",\"gravatar_id\":\"\",\"url\":\"https://api.github.com/users/octocat\",\"html_url\":\"https://github.com/octocat\",\"followers_url\":\"https://api.github.com/users/octocat/followers\",\"following_url\":\"https://api.github.com/users/octocat/following{/other_user}\",\"gists_url\":\"https://api.github.com/users/octocat/gists{/gist_id}\",\"starred_url\":\"https://api.github.com/users/octocat/starred{/owner}{/repo}\",\"subscriptions_url\":\"https://api.github.com/users/octocat/subscriptions\",\"organizations_url\":\"https://api.github.com/users/octocat/orgs\",\"repos_url\":\"https://api.github.com/users/octocat/repos\",\"events_url\":\"https://api.github.com/users/octocat/events{/privacy}\",\"received_events_url\":\"https://api.github.com/users/octocat/received_events\",\"type\":\"User\",\"site_admin\":false}}]}"; releaseInfo = JObject.Parse(jsonString); service = new GitHubModUpdate(); } [Fact] public void GetUpdateInfo_Correct() { var updateInfo = service.GetUpdateInfo(releaseInfo); updateInfo.Type.Should().Be(UpdateType.Major); updateInfo.Version.Should().BeEquivalentTo(Version.Parse("4.3.2.1")); } [Fact] public void GetDownlaodURL_Correct() { var url = service.GetDownloadURLInternal(releaseInfo); url.Should().Be("https://github.com/octocat/Hello-World/releases/download/v1.0.0/example.zip"); } } } ================================================ FILE: LocalizerTest/Ninject.cs ================================================ using System.Linq; using FluentAssertions; using Ninject; using Xunit; namespace LocalizerTest { public interface IFoo { } public interface IBar where T : IFoo { } public sealed class A : IFoo { } public sealed class B : IFoo { } public sealed class ABar : IBar { } public sealed class BBar : IBar { } public class NinjectTest { private StandardKernel _kernel; public NinjectTest() { _kernel = new StandardKernel(); } [Fact] public void GenericTypeBinding() { _kernel.Bind(typeof(IBar<>)).To().InSingletonScope(); _kernel.Bind(typeof(IBar<>)).To().InSingletonScope(); var bars = _kernel.GetAll(typeof(IBar<>)); bars.Count().Should().Be(2); } [Fact] public void MultiSingletonBinding() { _kernel.Bind(typeof(IBar<>), typeof(IBar)).To().InSingletonScope(); var abar1 = _kernel.Get(typeof(IBar<>)); var abar2 = _kernel.Get>(); abar1.GetType().Should().Be(abar2.GetType()); abar1.Should().Be(abar2); } } } ================================================ FILE: LocalizerTest/NonTest/UpdateLogger.cs ================================================ using System.Collections.Generic; using Localizer.Package.Update; namespace LocalizerTest.NonTest { public sealed class UpdateLogger : IUpdateLogger { public List Added { get; private set; } public List Removed { get; private set; } public List Changed { get; private set; } public UpdateLogger() { Added = new List(); Removed = new List(); Changed = new List(); } public void Dispose() { } public void Init(string name) { } public void Add(object content) { Added.Add(content.ToString()); } public void Remove(object content) { Removed.Add(content.ToString()); } public void Change(object content) { Changed.Add(content.ToString()); } } } ================================================ FILE: LocalizerTest/Package/Import/BasicFileImportTest.cs ================================================ using System.Collections.Generic; using FluentAssertions; using Localizer.DataModel.Default; using Localizer.Package.Import; using Xunit; namespace LocalizerTest.Package.Import { public class BasicFileImportTest { [Fact] public void MergeFile_Correct() { var importer = new BasicImporter(); var main = new BasicItemFile() { Items = new Dictionary() { { "Key1", new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin1", Translation = "NameTranslation1" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin1", Translation = "TooltipTranslation1" }, } }, { "Key2", new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin2", Translation = "NameTranslation2" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin2", Translation = "" }, } }, { "Key3", new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin3", Translation = "" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin3", Translation = "" }, } }, } }; var addition = new BasicItemFile() { Items = new Dictionary() { { "Key1", new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin1", Translation = "AnotherNameTranslation1" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin1", Translation = "AnotherTooltipTranslation1" }, } }, { "Key2", new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin2", Translation = "" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin2", Translation = "AnotherTooltipTranslation2" }, } }, { "Key3", new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin3", Translation = "AnotherNameTranslation3" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin3", Translation = "AnotherTooltipTranslation3" }, } }, { "Key4", new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin4", Translation = "NameTranslation4" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin4", Translation = "TooltipTranslation4" }, } }, } }; var result = importer.MergeInternal(main, addition); result.Items.Count.Should().Be(4); result.Items["Key1"].Name.Translation.Should().Be("NameTranslation1"); result.Items["Key1"].Tooltip.Translation.Should().Be("TooltipTranslation1"); result.Items["Key4"].Name.Origin.Should().Be("NameOrigin4"); result.Items["Key4"].Name.Translation.Should().Be("NameTranslation4"); result.Items["Key4"].Tooltip.Origin.Should().Be("TooltipOrigin4"); result.Items["Key4"].Tooltip.Translation.Should().Be("TooltipTranslation4"); result.Items["Key2"].Name.Translation.Should().Be("NameTranslation2"); result.Items["Key2"].Tooltip.Translation.Should().Be("AnotherTooltipTranslation2"); result.Items["Key3"].Name.Translation.Should().Be("AnotherNameTranslation3"); result.Items["Key3"].Tooltip.Translation.Should().Be("AnotherTooltipTranslation3"); } [Fact] public void MergeEntry_Correct() { var service = new BasicImporter(); var main1 = new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin", Translation = "NameTranslation" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin", Translation = "TooltipTranslation" }, }; var addition1 = new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin", Translation = "AnotherNameTranslation" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin", Translation = "AnotherTooltipTranslation" }, }; var result1 = service.Merge(main1, addition1) as ItemEntry; result1.Name.Translation.Should().Be("NameTranslation"); result1.Tooltip.Translation.Should().Be("TooltipTranslation"); var main2 = new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin", Translation = "" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin", Translation = "" }, }; var addition2 = new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin", Translation = "AnotherNameTranslation" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin", Translation = "AnotherTooltipTranslation" }, }; var result2 = service.Merge(main2, addition2) as ItemEntry; result2.Name.Translation.Should().Be("AnotherNameTranslation"); result2.Tooltip.Translation.Should().Be("AnotherTooltipTranslation"); var main3 = new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin", Translation = "NameTranslation" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin", Translation = "" }, }; var addition3 = new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin", Translation = "AnotherNameTranslation" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin", Translation = "AnotherTooltipTranslation" }, }; var result3 = service.Merge(main3, addition3) as ItemEntry; result3.Name.Translation.Should().Be("NameTranslation"); result3.Tooltip.Translation.Should().Be("AnotherTooltipTranslation"); } } } ================================================ FILE: LocalizerTest/Package/Import/CustomModTranslationFileImportTest.cs ================================================ using System.Collections.Generic; using FluentAssertions; using Localizer.DataModel.Default; using Localizer.Package.Import; using Xunit; namespace LocalizerTest.Package.Import { public class CustomModTranslationFileImportTest { [Fact] public void Merge_Correct() { var importer = new CustomModTranslationImporter(); var main = new CustomModTranslationFile() { Translations = new Dictionary() { { "Key1", new BaseEntry(){ Origin = "Origin1", Translation = "Translation1" } }, { "Key2", new BaseEntry(){ Origin = "Origin2", Translation = "Translation2" } }, { "Key3", new BaseEntry(){ Origin = "Origin3", Translation = "Translation3" } }, } }; var addition = new CustomModTranslationFile() { Translations = new Dictionary() { { "Key1", new BaseEntry(){ Origin = "Origin1", Translation = "AnotherTranslation1" } }, { "Key4", new BaseEntry(){ Origin = "Origin4", Translation = "Translation4" } }, } }; var result = importer.MergeInternal(main, addition); result.Translations.Count.Should().Be(4); result.Translations["Key1"].Translation.Should().Be("Translation1"); result.Translations["Key4"].Origin.Should().Be("Origin4"); result.Translations["Key4"].Translation.Should().Be("Translation4"); } } } ================================================ FILE: LocalizerTest/Package/Import/LdstrFileImportBaseTest.cs ================================================ using System.Collections.Generic; using FluentAssertions; using Localizer.DataModel.Default; using Localizer.Package.Import; using Xunit; namespace LocalizerTest.Package.Import { public class LdstrFileImportBaseTest { [Fact] public void MergeEntry_Correct() { var service = new HarmonyLdstrImporter(); var main = new LdstrEntry() { Instructions = new List() { new BaseEntry() { Origin = "Origin1", Translation = "Translation1" }, new BaseEntry() { Origin = "Origin2", Translation = "Translation2" }, } }; var addition = new LdstrEntry() { Instructions = new List() { new BaseEntry() { Origin = "Origin1", Translation = "AnotherTranslation1" }, new BaseEntry() { Origin = "AnotherOrigin2", Translation = "Translation2" }, new BaseEntry() { Origin = "Origin3", Translation = "Translation3" }, } }; var result = service.Merge(main, addition); result.Instructions.Count.Should().Be(4); result.Instructions.Should().ContainSingle(i => i.Origin == "Origin1" && i.Translation == "Translation1"); result.Instructions.Should().ContainSingle(i => i.Origin == "Origin2" && i.Translation == "Translation2"); result.Instructions.Should().ContainSingle(i => i.Origin == "AnotherOrigin2" && i.Translation == "Translation2"); result.Instructions.Should().ContainSingle(i => i.Origin == "Origin3" && i.Translation == "Translation3"); } [Fact] public void MergeFile_Correct() { var importer = new HarmonyLdstrImporter(); var main = new LdstrFile() { LdstrEntries = new Dictionary() { { "Key1", new LdstrEntry() { Instructions = new List() { new BaseEntry(){ Origin = "Origin1", Translation = "Translation1"}, new BaseEntry(){ Origin = "Origin2", Translation = "Translation2"}, } } }, { "Key2", new LdstrEntry() { Instructions = new List() { new BaseEntry(){ Origin = "Origin3", Translation = "Translation3"}, new BaseEntry(){ Origin = "Origin4", Translation = "Translation4"}, } } }, } }; var addition = new LdstrFile() { LdstrEntries = new Dictionary() { { "Key1", new LdstrEntry() { Instructions = new List() { new BaseEntry(){ Origin = "Origin1", Translation = "AnotherTranslation1"}, new BaseEntry(){ Origin = "AnotherOrigin1", Translation = "Translation1"}, new BaseEntry(){ Origin = "Origin5", Translation = "Translation5"}, } } }, { "Key3", new LdstrEntry() { Instructions = new List() { new BaseEntry(){ Origin = "Origin6", Translation = "Translation6"} } } }, } }; var result = importer.MergeInternal(main, addition); result.LdstrEntries.Count.Should().Be(3); result.LdstrEntries["Key1"].Instructions.Should().ContainSingle(i => i.Origin == "Origin1" && i.Translation == "Translation1"); result.LdstrEntries["Key1"].Instructions.Should().ContainSingle(i => i.Origin == "AnotherOrigin1" && i.Translation == "Translation1"); result.LdstrEntries["Key1"].Instructions.Should().ContainSingle(i => i.Origin == "Origin5" && i.Translation == "Translation5"); result.LdstrEntries["Key3"].Instructions.Count.Should().Be(1); result.LdstrEntries["Key3"].Instructions[0].Origin.Should().Be("Origin6"); result.LdstrEntries["Key3"].Instructions[0].Translation.Should().Be("Translation6"); } } } ================================================ FILE: LocalizerTest/Package/Update/BasicFileUpdateTest.cs ================================================ using System.Collections.Generic; using FluentAssertions; using Localizer.DataModel.Default; using Localizer.Package.Update; using LocalizerTest.NonTest; using Xunit; namespace LocalizerTest.Package.Update { public class BasicFileUpdateTest { [Fact] public void UpdateFile_Correct() { var service = new BasicFileUpdater(); var logger = new UpdateLogger(); var oldFile = new BasicItemFile() { Items = new Dictionary() { { "Key1", new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin1", Translation = "NameTranslation1" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin1", Translation = "TooltipTranslation1" }, } }, { "Key2", new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin2", Translation = "NameTranslation2" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin2", Translation = "TooltipTranslation2" }, } }, { "Key3", new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin3", Translation = "NameTranslation3" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin3", Translation = "TooltipTranslation3" }, } }, } }; var newFile = new BasicItemFile() { Items = new Dictionary() { { "Key1", new ItemEntry() { Name = new BaseEntry() { Origin = "AnotherNameOrigin1", Translation = "AnotherNameTranslation1" }, Tooltip = new BaseEntry() { Origin = "AnotherTooltipOrigin1", Translation = "AnotherTooltipTranslation1" }, } }, { "Key3", new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin3", Translation = "AnotherNameTranslation3" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin3", Translation = "AnotherTooltipTranslation3" }, } }, { "Key4", new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin4", Translation = "NameTranslation4" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin4", Translation = "TooltipTranslation4" }, } }, } }; service.Update(oldFile, newFile, logger); logger.Added.Count.Should().Be(1); logger.Changed.Count.Should().Be(2); logger.Removed.Count.Should().Be(1); oldFile.Items.Count.Should().Be(4); oldFile.Items["Key1"].Name.Origin.Should().Be("AnotherNameOrigin1"); oldFile.Items["Key1"].Name.Translation.Should().Be("AnotherNameTranslation1"); oldFile.Items["Key1"].Tooltip.Origin.Should().Be("AnotherTooltipOrigin1"); oldFile.Items["Key1"].Tooltip.Translation.Should().Be("AnotherTooltipTranslation1"); oldFile.Items["Key3"].Name.Origin.Should().Be("NameOrigin3"); oldFile.Items["Key3"].Name.Translation.Should().Be("NameTranslation3"); oldFile.Items["Key3"].Tooltip.Origin.Should().Be("TooltipOrigin3"); oldFile.Items["Key3"].Tooltip.Translation.Should().Be("TooltipTranslation3"); oldFile.Items["Key4"].Name.Origin.Should().Be("NameOrigin4"); oldFile.Items["Key4"].Name.Translation.Should().Be("NameTranslation4"); oldFile.Items["Key4"].Tooltip.Origin.Should().Be("TooltipOrigin4"); oldFile.Items["Key4"].Tooltip.Translation.Should().Be("TooltipTranslation4"); } [Fact] public void UpdateEntry_Correct() { var service = new BasicFileUpdater(); var logger1 = new UpdateLogger(); var oldEntry1 = new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin", Translation = "NameTranslation" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin", Translation = "TooltipTranslation" }, }; var newEntry1 = new ItemEntry() { Name = new BaseEntry() { Origin = "AnotherNameOrigin", Translation = "AnotherNameTranslation" }, Tooltip = new BaseEntry() { Origin = "AnotherTooltipOrigin", Translation = "AnotherTooltipTranslation" }, }; service.UpdateEntry("Key", oldEntry1, newEntry1, logger1); logger1.Changed.Count.Should().Be(2); oldEntry1.Name.Origin.Should().Be("AnotherNameOrigin"); oldEntry1.Name.Translation.Should().Be("AnotherNameTranslation"); oldEntry1.Tooltip.Origin.Should().Be("AnotherTooltipOrigin"); oldEntry1.Tooltip.Translation.Should().Be("AnotherTooltipTranslation"); var logger2 = new UpdateLogger(); var oldEntry2 = new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin", Translation = "NameTranslation" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin", Translation = "TooltipTranslation" }, }; var newEntry2 = new ItemEntry() { Name = new BaseEntry() { Origin = "NameOrigin", Translation = "AnotherNameTranslation" }, Tooltip = new BaseEntry() { Origin = "TooltipOrigin", Translation = "AnotherTooltipTranslation" }, }; service.UpdateEntry("Key", oldEntry2, newEntry2, logger2); logger2.Changed.Count.Should().Be(0); oldEntry2.Name.Origin.Should().Be("NameOrigin"); oldEntry2.Name.Translation.Should().Be("NameTranslation"); oldEntry2.Tooltip.Origin.Should().Be("TooltipOrigin"); oldEntry2.Tooltip.Translation.Should().Be("TooltipTranslation"); } } } ================================================ FILE: LocalizerTest/Package/Update/CustomModTranslationFileUpdateTest.cs ================================================ using System.Collections.Generic; using FluentAssertions; using Localizer.DataModel.Default; using Localizer.Package.Update; using LocalizerTest.NonTest; using Xunit; namespace LocalizerTest.Package.Update { public class CustomModTranslationFileUpdateTest { [Fact] public void Update_Correct() { var service = new CustomModTranslationUpdater(); var logger = new UpdateLogger(); var oldFile = new CustomModTranslationFile() { Translations = new Dictionary() { { "Key1", new BaseEntry(){ Origin = "Origin1", Translation = "Translation1" } }, { "Key2", new BaseEntry(){ Origin = "Origin2", Translation = "Translation2" } }, { "Key3", new BaseEntry(){ Origin = "Origin3", Translation = "Translation3" } }, } }; var newFile = new CustomModTranslationFile() { Translations = new Dictionary() { { "Key1", new BaseEntry(){ Origin = "AnotherOrigin1", Translation = "AnotherTranslation1" } }, { "Key4", new BaseEntry(){ Origin = "Origin4", Translation = "Translation4" } }, { "Key5", new BaseEntry(){ Origin = "Origin5", Translation = "Translation5" } }, } }; service.Update(oldFile, newFile, logger); logger.Added.Count.Should().Be(2); logger.Removed.Count.Should().Be(2); logger.Changed.Count.Should().Be(1); oldFile.Translations.Count.Should().Be(5); oldFile.Translations["Key1"].Origin.Should().Be("AnotherOrigin1"); oldFile.Translations["Key1"].Translation.Should().Be("AnotherTranslation1"); oldFile.Translations["Key2"].Origin.Should().Be("Origin2"); oldFile.Translations["Key2"].Translation.Should().Be("Translation2"); oldFile.Translations["Key3"].Origin.Should().Be("Origin3"); oldFile.Translations["Key3"].Translation.Should().Be("Translation3"); oldFile.Translations["Key4"].Origin.Should().Be("Origin4"); oldFile.Translations["Key4"].Translation.Should().Be("Translation4"); oldFile.Translations["Key5"].Origin.Should().Be("Origin5"); oldFile.Translations["Key5"].Translation.Should().Be("Translation5"); } } } ================================================ FILE: LocalizerTest/Package/Update/LdstrFileUpdateTest.cs ================================================ using System.Collections.Generic; using FluentAssertions; using Localizer.DataModel.Default; using Localizer.Package.Update; using LocalizerTest.NonTest; using Xunit; namespace LocalizerTest.Package.Update { public class LdstrFileUpdateTest { [Fact] public void Update_Correct() { var service = new LdstrFileUpdater(); var logger = new UpdateLogger(); var oldFile = new LdstrFile() { LdstrEntries = new Dictionary() { { "Key1", new LdstrEntry() { Instructions = new List() { new BaseEntry(){ Origin = "Origin1", Translation = "Translation1"}, new BaseEntry(){ Origin = "Origin2", Translation = "Translation2"}, } } }, { "Key2", new LdstrEntry() { Instructions = new List() { new BaseEntry(){ Origin = "Origin3", Translation = "Translation3"}, new BaseEntry(){ Origin = "Origin4", Translation = "Translation4"}, } } }, } }; var newFile = new LdstrFile() { LdstrEntries = new Dictionary() { { "Key1", new LdstrEntry() { Instructions = new List() { new BaseEntry(){ Origin = "Origin1", Translation = ""}, new BaseEntry(){ Origin = "AnotherOrigin1", Translation = ""}, new BaseEntry(){ Origin = "Origin5", Translation = ""}, } } }, { "Key3", new LdstrEntry() { Instructions = new List() { new BaseEntry(){ Origin = "Origin6", Translation = ""} } } }, } }; service.Update(oldFile, newFile, logger); logger.Added.Count.Should().Be(1); logger.Changed.Count.Should().Be(2); logger.Added.Count.Should().Be(1); oldFile.LdstrEntries.Count.Should().Be(3); oldFile.LdstrEntries["Key1"].Instructions.Count.Should().Be(4); oldFile.LdstrEntries["Key1"].Instructions.Should().ContainSingle(i => i.Origin == "Origin1" && i.Translation == "Translation1"); oldFile.LdstrEntries["Key1"].Instructions.Should().ContainSingle(i => i.Origin == "Origin2" && i.Translation == "Translation2"); oldFile.LdstrEntries["Key1"].Instructions.Should().ContainSingle(i => i.Origin == "AnotherOrigin1" && i.Translation == ""); oldFile.LdstrEntries["Key1"].Instructions.Should().ContainSingle(i => i.Origin == "Origin5" && i.Translation == ""); oldFile.LdstrEntries["Key2"].Instructions.Count.Should().Be(2); oldFile.LdstrEntries["Key2"].Instructions.Should().ContainSingle(i => i.Origin == "Origin3" && i.Translation == "Translation3"); oldFile.LdstrEntries["Key2"].Instructions.Should().ContainSingle(i => i.Origin == "Origin4" && i.Translation == "Translation4"); oldFile.LdstrEntries["Key3"].Instructions.Count.Should().Be(1); oldFile.LdstrEntries["Key3"].Instructions.Should().ContainSingle(i => i.Origin == "Origin6" && i.Translation == ""); } } } ================================================ FILE: ModPatch/ModPatch.csproj ================================================  Exe ModPatch ModPatch net472 x86 7.3 ================================================ FILE: ModPatch/Program.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; namespace ModPatch { internal class Program { private static void Main(string[] args) { var FILE_PATH = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\Documents\My Games\Terraria\ModLoader\Mods\Localizer.tmod"); var tModLoaderVersion = ""; var modName = ""; var modVersion = ""; var files = new List<(string fileName, int length, int compressedLength, byte[] content)>(); using (var fileStream = File.OpenRead(FILE_PATH)) { using (var br = new BinaryReader(fileStream)) { br.ReadBytes(4); // TMOD tModLoaderVersion = br.ReadString(); // tModLoader version br.ReadBytes(280); // Signature modName = br.ReadString(); // Name modVersion = br.ReadString(); // Version var fileCount = br.ReadInt32(); for (var i = 0; i < fileCount; i++) { var entry = (filename: br.ReadString(), length: br.ReadInt32(), compressedLength: br.ReadInt32(), content: new byte[] { }); files.Add(entry); } for (var i = 0; i < fileCount; i++) { var file = files[i]; var content = br.ReadBytes(file.compressedLength); files[i] = (file.fileName, file.length, file.compressedLength, content); } } } if (!modName.StartsWith("!")) { modName = "!" + modName; } files = files.Select(f => (f.fileName.EndsWith("NA.dll") && !f.fileName.StartsWith("!")) ? ("!" + f.fileName, f.length, f.compressedLength, f.content) : f).ToList(); using (var fileStream = new FileStream(FILE_PATH, FileMode.Create, FileAccess.ReadWrite)) { using (var bw = new BinaryWriter(fileStream)) { bw.Write(Encoding.UTF8.GetBytes("TMOD")); bw.Write(tModLoaderVersion); var hashPos = bw.BaseStream.Position; bw.Seek(280, SeekOrigin.Current); var contentPos = bw.BaseStream.Position; bw.Write(modName); bw.Write(modVersion); bw.Write(files.Count); foreach (var file in files) { bw.Write(file.fileName); bw.Write(file.length); bw.Write(file.compressedLength); } foreach (var file in files) { bw.Write(file.content); } bw.Seek((int)contentPos, SeekOrigin.Begin); var hash = SHA1.Create().ComputeHash(bw.BaseStream); bw.Seek((int)hashPos, SeekOrigin.Begin); bw.Write(hash); } } var enabledFilePath = Environment.ExpandEnvironmentVariables( @"%USERPROFILE%\Documents\My Games\Terraria\ModLoader\Mods\enabled.json"); if (!File.Exists(enabledFilePath)) { return; } File.WriteAllText(enabledFilePath, File.ReadAllText(enabledFilePath).Replace("\"Localizer\"", "\"!Localizer\"")); } } } ================================================ FILE: README.md ================================================ # Localizer Mod ![](https://github.com/chi-rei-den/Localizer/workflows/Mod%20Build/badge.svg) ![](https://github.com/chi-rei-den/Localizer/workflows/Unit%20Test/badge.svg) ### 下载与说明请点击下方链接 #### [简体中文](https://github.com/chi-rei-den/Localizer/wiki/%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87) ## Credits * [JetBrains](https://www.jetbrains.com/): Free license for this project.