示例#1
0
 /// <summary>
 /// Instantiates the game mode.
 /// </summary>
 /// <param name="p_futFileUtility">The file utility class to be used by the game mode.</param>
 /// <returns>The game mode for which this is a factory.</returns>
 protected DarkSouls2GameMode InstantiateGameMode(FileUtil p_futFileUtility)
 {
     return(new DarkSouls2GameMode(EnvironmentInfo, p_futFileUtility));
 }
示例#2
0
文件: Nsf.cs 项目: qyf0310/vgmtoolbox
 public void UpdateArtist(string pNewValue)
 {
     FileUtil.UpdateTextField(this.filePath, pNewValue, ARTIST_OFFSET,
                              ARTIST_LENGTH);
 }
        private void DownLoad(DownLoadFile downLoadFile)
        {
            try
            {
                List <Proxy> proxyList = proxyHelper.Get();

                if (proxyList is null)
                {
                    return;
                }

                string url        = downLoadFile.Address;
                string folderName = downLoadFile.FileName;

                if (string.IsNullOrEmpty(folderName))
                {
                    folderName = "Unknown";
                }

                logger.InfoFormat("开始下载: {0}, {1}", url, folderName);
                downLoadFile.DownLoading = true;

                StringBuilder folderPath = new StringBuilder(folderName.Length + 15);
                StringBuilder filePath   = new StringBuilder(folderName.Length + 37);

                string pattern = string.Empty;
                Regex  regex   = null;

                // 删除尾部限定大小
                regex = new Regex(@"((http|https)://)(([a-zA-Z0-9\._-]+)/)+(w\d+)");
                if (regex.IsMatch(url))
                {
                    url = url.Substring(0, url.LastIndexOf('/'));
                }

                // 拼接生成文件路径
                folderPath.Append("DownLoad/coser/").Append(folderName);
                regex = new Regex(@"((http|https)://)(([a-zA-Z0-9\._-]+)/)+");
                filePath.Append("DownLoad/coser/").Append(folderName).Append('/').Append(url.Substring(regex.Match(url).Value.Length));

                string path     = folderPath.ToString();
                string fileName = filePath.ToString();

                bool isExists = false;
                if (FileUtil.CheckPathExists(path, fileName))
                {
                    isExists = true;
                    if (!FileUtil.IsJpeg(fileName))
                    {
                        isExists = false;
                    }
                }

                if (isExists)
                {
                    return;
                }

                httpUtil.DownLoad(url, fileName, proxyList, o =>
                {
                    try
                    {
                        if (o)
                        {
                            logger.InfoFormat("下载完成: {0}, {1}", url, fileName);
                            this.downLoadHelper.Remove(downLoadFile);
                            Wait();
                            downLoadFiles.Remove(downLoadFile);
                        }
                        else
                        {
                            logger.InfoFormat("下载失败: {0}, {1}", url, fileName);
                            downLoadFile.DownLoading = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                        downLoadFile.DownLoading = false;
                    }
                });
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                downLoadFile.DownLoading = false;
            }
        }
示例#4
0
        private void VerifyDragDrop(ListView listView, DragEventArgs e)
        {
            var files = e.Data.GetData(DataFormats.FileDrop) as string[];

            if (files == null)
            {
                return;
            }
            if (files.Length > 1)
            {
                MessageBox.Show(Configuration.Settings.Language.Main.DropOnlyOneFile,
                                "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string filePath = files[0];
            var    listExt  = new List <string>();

            foreach (var s in Utilities.GetOpenDialogFilter().Split(new[] { '*' }, StringSplitOptions.RemoveEmptyEntries))
            {
                if (s.EndsWith(';'))
                {
                    listExt.Add(s.Trim(';'));
                }
            }
            if (!listExt.Contains(Path.GetExtension(filePath)))
            {
                return;
            }
            if (FileUtil.IsVobSub(filePath) || FileUtil.IsBluRaySup(filePath))
            {
                MessageBox.Show(Configuration.Settings.Language.CompareSubtitles.CannotCompareWithImageBasedSubtitles);
                return;
            }
            Encoding encoding;

            if (listView.Name == "subtitleListView1")
            {
                _subtitle1 = new Subtitle();
                _subtitle1.LoadSubtitle(filePath, out encoding, null);
                subtitleListView1.Fill(_subtitle1);
                subtitleListView1.SelectIndexAndEnsureVisible(0);
                subtitleListView2.SelectIndexAndEnsureVisible(0);
                labelSubtitle1.Text = filePath;
                _language1          = LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitle1);
                if (_subtitle1.Paragraphs.Count > 0)
                {
                    CompareSubtitles();
                }
            }
            else
            {
                _subtitle2 = new Subtitle();
                _subtitle2.LoadSubtitle(filePath, out encoding, null);
                subtitleListView2.Fill(_subtitle2);
                subtitleListView1.SelectIndexAndEnsureVisible(0);
                subtitleListView2.SelectIndexAndEnsureVisible(0);
                labelSubtitle2.Text = filePath;
                if (_subtitle2.Paragraphs.Count > 0)
                {
                    CompareSubtitles();
                }
            }
        }
示例#5
0
文件: Nsf.cs 项目: qyf0310/vgmtoolbox
 public string GetSongName()
 {
     System.Text.Encoding enc = System.Text.Encoding.ASCII;
     return(enc.GetString(FileUtil.ReplaceNullByteWithSpace(this.songName)).Trim());
 }
示例#6
0
    void ParseJson(bool ishd)
    {
        if (rootJson != null)
        {
            return;
        }

        //string strDir = Common.GAME_DATA_DIR + "/config";
        string strDir = Common.RES_CONFIG_DATA + "/config";

        string fileName = "config_ios";

        //Defualt
        fileName = "config_" + osDefault;
        if (osDefault == Source.ANDROID)
        {
            fileName = "config_android";
        }
        if (osDefault == Source.IOS)
        {
            fileName = "config_ios";
        }
        if (osDefault == Source.WIN)
        {
        }


        if (Common.isAndroid)
        {
            fileName = "config_android";
        }
        if (Common.isWinUWP)
        {
            fileName = "config_" + Source.WIN;
        }

        if (ishd)//AppVersion.appForPad
        {
            fileName += "_hd";
        }
        fileName += ".json";

        string json = FileUtil.ReadStringFromResources(strDir + "/" + fileName);//ReadStringAsset

        rootJson = JsonMapper.ToObject(json);

        //appid

        JsonData jsonAppId = rootJson["APPID"];

        foreach (string key in jsonAppId.Keys)
        {
            string value = (string)jsonAppId[key];
            Debug.Log("APPID:key=" + key + " value=" + value);
            ItemInfo iteminfo = new ItemInfo();
            iteminfo.source = key;
            iteminfo.appid  = value;
            listAppStore.Add(iteminfo);
        }



        jsonShare = rootJson["SHARE"];
        jsonPay   = rootJson["PAY"];

        if (listSharePlatform == null)
        {
            listSharePlatform = new List <SharePlatformInfo>();
        }

        JsonData jsonPlatform = jsonShare["platform"];

        foreach (JsonData data in jsonPlatform)
        {
            SharePlatformInfo info = new SharePlatformInfo();
            info.source = (string)data["source"];
            info.appId  = (string)data["id"];
            info.appKey = (string)data["key"];
            if (info.appId == "0")
            {
                continue;
            }
            listSharePlatform.Add(info);
            if (info.source == Source.WEIXIN)
            {
                //同时添加朋友圈
                AddShareBrother(Source.WEIXINFRIEND, info.appId, info.appKey);
            }

            if (info.source == Source.QQ)
            {
                //同时添加qq空间
                AddShareBrother(Source.QQZONE, info.appId, info.appKey);
            }
        }

        //统一添加email和短信
        AddShareBrother(Source.EMAIL, "0", "0");
        AddShareBrother(Source.SMS, "0", "0");
    }
        private void DuplicateItemGridView()
        {
            var selectedIdList = m_GridView.GetSelection();

            if (selectedIdList.Length == 0)
            {
                return;
            }

            List <int> idList = new List <int>();

            try
            {
                m_TreeView.EndNameEditing(true);
                m_GridView.EndRename(false);
                foreach (var id in selectedIdList)
                {
                    var item = m_GridViewDataSource.GetItemByIndex(m_GridViewDataSource.GetItemIndexByItemId(id)) as FolderGridItem;
                    FolderTreeViewItem treeItem       = null;
                    FolderTreeViewItem parentTreeItem = null;
                    if (item.IsFolder)
                    {
                        treeItem       = m_TreeView.FindItem(item.Id) as FolderTreeViewItem;
                        parentTreeItem = treeItem.parent as FolderTreeViewItem;
                    }
                    else
                    {
                        parentTreeItem = m_TreeView.FindItem(item.ParentId) as FolderTreeViewItem;
                        foreach (var child in parentTreeItem.FileList)
                        {
                            if (child.id == item.Id)
                            {
                                treeItem = child;
                                break;
                            }
                        }
                    }

                    if (item.IsFolder)
                    {
                        var newPath = EditorFileUtility.GetNewFolder(item.Path);
                        FileUtil.CopyFileOrDirectory(item.Path, newPath);
                        var newItem = JsonReader.Deserialize(JsonWriter.Serialize(treeItem, new JsonWriterSettings()
                        {
                            MaxDepth = Int32.MaxValue
                        }), true) as FolderTreeViewItem;

                        newItem.id       = m_FolderTreeViewGroup.GetDataContainer().GetAutoID();
                        newItem.FileList = null;
                        newItem.children = null;
                        idList.Add(newItem.id);

                        newItem.Path        = newPath;
                        newItem.displayName = new DirectoryInfo(newPath).Name;

                        var newGridItem = JsonReader.Deserialize(JsonWriter.Serialize(item, new JsonWriterSettings()
                        {
                            MaxDepth = Int32.MaxValue
                        }), item.GetType(), true) as FolderGridItem;
                        newGridItem.Id          = newItem.id;
                        newGridItem.Path        = newItem.Path;
                        newGridItem.DisplayName = newItem.displayName;
                        m_GridViewDataSource.ItemList.Add(newGridItem);

                        parentTreeItem.AddChild(newItem);
                        var comparator = new AlphanumComparator.AlphanumComparator();
                        parentTreeItem.children.Sort((viewItem, treeViewItem) =>
                        {
                            return(comparator.Compare(viewItem.displayName, treeViewItem.displayName));
                        });
                    }
                    else
                    {
                        var newPath = EditorFileUtility.GetNewFile(item.Path);
                        FileUtil.CopyFileOrDirectory(item.Path, newPath);
                        var newItem = JsonReader.Deserialize(JsonWriter.Serialize(treeItem, new JsonWriterSettings()
                        {
                            MaxDepth = Int32.MaxValue
                        }), true) as FolderTreeViewItem;
                        newItem.id = m_FolderTreeViewGroup.GetDataContainer().GetAutoID();
                        idList.Add(newItem.id);
                        newItem.Path        = newPath;
                        newItem.displayName = Path.GetFileNameWithoutExtension(newPath);
                        parentTreeItem.FileList.Add(newItem);

                        var newGridItem = JsonReader.Deserialize(JsonWriter.Serialize(item, new JsonWriterSettings()
                        {
                            MaxDepth = Int32.MaxValue
                        }), item.GetType(), true) as FolderGridItem;
                        newGridItem.Id          = newItem.id;
                        newGridItem.Path        = newItem.Path;
                        newGridItem.DisplayName = newItem.displayName;
                        m_GridViewDataSource.ItemList.Add(newGridItem);
                    }
                }

                m_GridView.SetSelection(idList.ToArray(), false);
            }
            catch (Exception e)
            {
                Debug.LogError("复制item出错:" + e);
            }
            finally
            {
                m_FolderTreeViewGroup.GetDataContainer().UpdateValidItems();
                m_TreeView.data.RefreshData();
                UpdateGridViewContent();
                if (m_ConfigSource != null)
                {
                    m_ConfigSource.SetConfigDirty();
                }
            }
        }
示例#8
0
        private static AssemblyMetadata[] GetAvailableLibraryPathsByLibraryName(
            string[] nullableBuildFileLocalDepsList,
            string nullableProjectDirectory)
        {
            string crayonHome = CommonUtil.Environment.EnvironmentVariables.Get("CRAYON_HOME");

#if RELEASE
            if (crayonHome == null)
            {
                throw new System.InvalidOperationException("Please set the CRAYON_HOME environment variable to the location of the directory containing both 'crayon.exe' and the 'lib' directory.");
            }
#endif

            string placesWhereLibraryDirectoriesCanExist = "";

            if (crayonHome != null)
            {
                placesWhereLibraryDirectoriesCanExist += ";" + FileUtil.JoinPath(crayonHome, "libs");
            }
            placesWhereLibraryDirectoriesCanExist += ";" + (CommonUtil.Environment.EnvironmentVariables.Get("CRAYON_PATH") ?? "");

#if OSX
            placesWhereLibraryDirectoriesCanExist = placesWhereLibraryDirectoriesCanExist.Replace(':', ';');
#endif

            List<string> unverifiedLibraryDirectories = new List<string>();

            if (nullableBuildFileLocalDepsList != null)
            {
                foreach (string localDep in nullableBuildFileLocalDepsList)
                {
                    string localDepAbsolute = FileUtil.GetAbsolutePathFromRelativeOrAbsolutePath(nullableProjectDirectory, localDep);
                    unverifiedLibraryDirectories.Add(localDepAbsolute);
                }
            }

            string[] paths = StringUtil.SplitRemoveEmpty(placesWhereLibraryDirectoriesCanExist, ";");
            foreach (string path in paths)
            {
                // TODO: figure out why this says nullable yet is being used directly.
                string absolutePath = FileUtil.GetAbsolutePathFromRelativeOrAbsolutePath(nullableProjectDirectory, path);
                if (FileUtil.DirectoryExists(absolutePath))
                {
                    unverifiedLibraryDirectories.AddRange(FileUtil.DirectoryListDirectoryPaths(absolutePath));
                }
            }

            string runningFromSourceDirectory = SourceDirectoryFinder.CrayonSourceDirectory;
            if (runningFromSourceDirectory != null) // returns null on release builds.
            {
                string libraryPath = FileUtil.JoinPath(runningFromSourceDirectory, "Libraries");
                unverifiedLibraryDirectories.AddRange(FileUtil.DirectoryListDirectoryPaths(libraryPath));
            }

            List<string> verifiedLibraryPaths = new List<string>();

            foreach (string dir in unverifiedLibraryDirectories)
            {
                string manifestPath = FileUtil.JoinPath(dir, "manifest.json");
                if (FileUtil.FileExists(manifestPath))
                {
                    verifiedLibraryPaths.Add(dir);
                }
            }

            // Library name collisions will override any previous definition.
            // For example, a custom library referenced by a build file will override a built-in library.
            // An example use case of this would be to define a custom library called "Gamepad" for mobile that puts
            // buttons in the corners of the screen, but without having to change any code to be platform-aware.
            Dictionary<string, AssemblyMetadata> uniqueAssemblies = new Dictionary<string, AssemblyMetadata>();
            foreach (string path in verifiedLibraryPaths)
            {
                string defaultName = Path.GetFileName(path);
                AssemblyMetadata metadata = new AssemblyMetadata(path, defaultName);

                // TODO: don't hardcode EN
                string uniqueKey = "en:" + metadata.ID;
                uniqueAssemblies[uniqueKey] = metadata;
            }

            return uniqueAssemblies.Values
                .OrderBy(metadata => metadata.ID.ToLowerInvariant())
                .ToArray();
        }
示例#9
0
    private void ReplaceAssembly(string assemblyDefinitionFilePath)
    {
        Debug.LogFormat("Replacing scripts for assembly definition file {0}", assemblyDefinitionFilePath);
        string   asmdefDirectory   = Path.GetDirectoryName(assemblyDefinitionFilePath);
        string   assemblyName      = Path.GetFileNameWithoutExtension(assemblyDefinitionFilePath);
        Assembly assemblyToReplace = CompilationPipeline.GetAssemblies().ToList().Find(assembly => assembly.name.ToLower().Equals(assemblyName.ToLower()));
        string   assemblyPath      = assemblyToReplace.outputPath;
        string   assemblyFileName  = Path.GetFileName(assemblyPath);

        string[] assemblyFilePathInAssets = Directory.GetFiles("./Assets", assemblyFileName, SearchOption.AllDirectories);

        // save the guid/classname correspondance of the scripts that we will remove
        Dictionary <string, string> oldGUIDToClassNameMap = new Dictionary <string, string>();

        if (assemblyFilePathInAssets.Length <= 0)
        {
            // Move all script files outside the asset folder
            foreach (string sourceFile in assemblyToReplace.sourceFiles)
            {
                string tempScriptPath = Path.Combine(TempSourceFilePath, sourceFile);
                Directory.CreateDirectory(Path.GetDirectoryName(tempScriptPath));
                if (!File.Exists(sourceFile))
                {
                    Debug.LogErrorFormat("File {0} does not exist while the assembly {1} references it.", sourceFile, assemblyToReplace.name);
                }
                Debug.Log("will move " + sourceFile + " to " + tempScriptPath);
                // save the guid of the file because we may need to replace it later
                MonoScript monoScript = AssetDatabase.LoadAssetAtPath <MonoScript>(sourceFile);
                if (monoScript != null && monoScript.GetClass() != null)
                {
                    oldGUIDToClassNameMap.Add(AssetDatabase.AssetPathToGUID(sourceFile), monoScript.GetClass().FullName);
                }
                FileUtil.MoveFileOrDirectory(sourceFile, tempScriptPath);
            }

            Debug.Log("Map of GUID/Class : \n" + String.Join("\n", oldGUIDToClassNameMap.Select(pair => pair.Key + " : " + pair.Value).ToArray()));

            string finalAssemblyPath = Path.Combine(asmdefDirectory, assemblyFileName);
            Debug.Log("will move " + assemblyPath + " to " + finalAssemblyPath);
            FileUtil.MoveFileOrDirectory(assemblyPath, finalAssemblyPath);
            string tempAsmdefPath = Path.Combine(TempSourceFilePath, Path.GetFileName(assemblyDefinitionFilePath));
            Debug.Log("will move " + assemblyDefinitionFilePath + " to " + tempAsmdefPath);
            FileUtil.MoveFileOrDirectory(assemblyDefinitionFilePath, tempAsmdefPath);
            // Rename the asmdef meta file to the dll meta file so that the dll guid stays the same
            FileUtil.MoveFileOrDirectory(assemblyDefinitionFilePath + ".meta", finalAssemblyPath + ".meta");
            pathsOfAssemblyFilesInAssetFolder.Add(finalAssemblyPath);
            pathsOfAssemblyFilesCreatedByUnity.Add(assemblyPath);


            // We need to refresh before accessing the assets in the new assembly
            AssetDatabase.Refresh();


            // We need to remove .\ when using LoadAsslAssetsAtPath
            string cleanFinalAssemblyPath = finalAssemblyPath.Replace(".\\", "");
            var    assetsInAssembly       = AssetDatabase.LoadAllAssetsAtPath(cleanFinalAssemblyPath);

            // list all components in the assembly file.
            var assemblyObjects = assetsInAssembly.OfType <MonoScript>().ToArray();

            // save the new GUID and file ID for the MonoScript in the new assembly
            Dictionary <string, KeyValuePair <string, long> > newMonoScriptToIDsMap = new Dictionary <string, KeyValuePair <string, long> >();
            // for each component, replace the guid and fileID file
            for (var i = 0; i < assemblyObjects.Length; i++)
            {
                long   dllFileId;
                string dllGuid = null;
                if (AssetDatabase.TryGetGUIDAndLocalFileIdentifier(assemblyObjects[i], out dllGuid, out dllFileId))
                {
                    string fullClassName = assemblyObjects[i].GetClass().FullName;
                    newMonoScriptToIDsMap.Add(fullClassName, new KeyValuePair <string, long>(dllGuid, dllFileId));
                }
            }

            Debug.Log("Map of Class/GUID:FILEID : \n" + String.Join("\n", newMonoScriptToIDsMap.Select(pair => pair.Key + " : " + pair.Value.Key + " - " + pair.Value.Value).ToArray()));

            ReplaceIdsInAssets(oldGUIDToClassNameMap, newMonoScriptToIDsMap);
        }


        else
        {
            Debug.Log("Already found an assembly file named " + assemblyFileName + " in asset folder");
        }
    }
        public static void Convert(string title, string[] args) // E.g.: /convert *.txt SubRip
        {
            const int ATTACH_PARENT_PROCESS = -1;

            if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux())
            {
                NativeMethods.AttachConsole(ATTACH_PARENT_PROCESS);
            }

            var currentFolder = Directory.GetCurrentDirectory();

            Console.WriteLine();
            Console.WriteLine(title + " - Batch converter");
            Console.WriteLine();

            if (args.Length < 4)
            {
                if (args.Length == 3 && (args[2].Equals("/list", StringComparison.OrdinalIgnoreCase) || args[2].Equals("-list", StringComparison.OrdinalIgnoreCase)))
                {
                    Console.WriteLine("- Supported formats (input/output):");
                    foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats)
                    {
                        Console.WriteLine("    " + format.Name.Replace(" ", string.Empty));
                    }
                    Console.WriteLine();
                    Console.WriteLine("- Supported formats (input only):");
                    Console.WriteLine("    " + CapMakerPlus.NameOfFormat);
                    Console.WriteLine("    " + Captionate.NameOfFormat);
                    Console.WriteLine("    " + Cavena890.NameOfFormat);
                    Console.WriteLine("    " + CheetahCaption.NameOfFormat);
                    Console.WriteLine("    " + Chk.NameOfFormat);
                    Console.WriteLine("    Matroska (.mkv)");
                    Console.WriteLine("    Matroska subtitle (.mks)");
                    Console.WriteLine("    " + NciCaption.NameOfFormat);
                    Console.WriteLine("    " + AvidStl.NameOfFormat);
                    Console.WriteLine("    " + Pac.NameOfFormat);
                    Console.WriteLine("    " + Spt.NameOfFormat);
                    Console.WriteLine("    " + Ultech130.NameOfFormat);
                    Console.WriteLine("- For Blu-ray .sup output use: '" + BatchConvert.BluRaySubtitle.Replace(" ", string.Empty) + "'");
                    Console.WriteLine("- For VobSub .sub output use: '" + BatchConvert.VobSubSubtitle.Replace(" ", string.Empty) + "'");
                }
                else
                {
                    Console.WriteLine("- Usage: SubtitleEdit /convert <pattern> <name-of-format-without-spaces> [<optional-parameters>]");
                    Console.WriteLine();
                    Console.WriteLine("    pattern:");
                    Console.WriteLine("        one or more file name patterns separated by commas");
                    Console.WriteLine("        relative patterns are relative to /inputfolder if specified");
                    Console.WriteLine("    optional-parameters:");
                    Console.WriteLine("        /offset:hh:mm:ss:ms");
                    Console.WriteLine("        /fps:<frame rate>");
                    Console.WriteLine("        /targetfps:<frame rate>");
                    Console.WriteLine("        /encoding:<encoding name>");
                    Console.WriteLine("        /pac-codepage:<code page>");
                    Console.WriteLine("        /inputfolder:<folder name>");
                    Console.WriteLine("        /outputfolder:<folder name>");
                    Console.WriteLine("        /removetextforhi");
                    Console.WriteLine("        /fixcommonerrors");
                    Console.WriteLine("        /redocasing");
                    Console.WriteLine("        /multiplereplace");
                    Console.WriteLine();
                    Console.WriteLine("    example: SubtitleEdit /convert *.srt sami");
                    Console.WriteLine("    list available formats: SubtitleEdit /convert /list");
                }
                Console.WriteLine();

                if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux())
                {
                    Console.Write(currentFolder + ">");
                    NativeMethods.FreeConsole();
                }
                Environment.Exit(1);
            }

            int count     = 0;
            int converted = 0;
            int errors    = 0;

            try
            {
                var pattern      = args[2].Trim();
                var targetFormat = args[3].Trim().Replace(" ", string.Empty);
                var offset       = GetArgument(args, "offset:");

                double?targetFrameRate = null;
                {
                    var fps = GetArgument(args, "targetfps:");
                    if (fps.Length > 1)
                    {
                        fps = fps.Replace(',', '.').Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, ".");
                        double d;
                        if (double.TryParse(fps, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
                        {
                            targetFrameRate = d;
                        }
                    }

                    fps = GetArgument(args, "fps:");
                    if (fps.Length > 1)
                    {
                        fps = fps.Replace(',', '.').Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, ".");
                        double d;
                        if (double.TryParse(fps, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
                        {
                            Configuration.Settings.General.CurrentFrameRate = d;
                        }
                    }
                }

                var targetEncoding = Encoding.UTF8;
                try
                {
                    var encodingName = GetArgument(args, "encoding:");
                    if (encodingName.Length > 0)
                    {
                        targetEncoding = Encoding.GetEncoding(encodingName);
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Unable to set encoding (" + exception.Message + ") - using UTF-8");
                }

                var outputFolder = string.Empty;
                {
                    var folder = GetArgument(args, "outputfolder:");
                    if (folder.Length > 0 && Directory.Exists(folder))
                    {
                        outputFolder = folder;
                    }
                }

                var inputFolder = currentFolder;
                {
                    var folder = GetArgument(args, "inputFolder:");
                    if (folder.Length > 0 && Directory.Exists(folder))
                    {
                        inputFolder = folder;
                    }
                }

                int pacCodePage = -1;
                {
                    var pcp = GetArgument(args, "pac-codepage:");
                    if (pcp.Length > 0)
                    {
                        if (pcp.Equals("Latin", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageLatin;
                        }
                        else if (pcp.Equals("Greek", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageGreek;
                        }
                        else if (pcp.Equals("Czech", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageLatinCzech;
                        }
                        else if (pcp.Equals("Arabic", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageArabic;
                        }
                        else if (pcp.Equals("Hebrew", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageHebrew;
                        }
                        else if (pcp.Equals("Thai", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageThai;
                        }
                        else if (pcp.Equals("Cyrillic", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageCyrillic;
                        }
                        else if (pcp.Equals("CHT", StringComparison.OrdinalIgnoreCase) || pcp.Replace(" ", string.Empty).Equals("TraditionalChinese", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageChineseTraditional;
                        }
                        else if (pcp.Equals("CHS", StringComparison.OrdinalIgnoreCase) || pcp.Replace(" ", string.Empty).Equals("SimplifiedChinese", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageChineseSimplified;
                        }
                        else if (pcp.Equals("Korean", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageKorean;
                        }
                        else if (pcp.Equals("Japanese", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageJapanese;
                        }
                        else if (!int.TryParse(pcp, out pacCodePage) || !Pac.IsValidCodePage(pacCodePage))
                        {
                            Console.WriteLine("Unknown pac code page '" + pcp + "' - using default code page");
                            pacCodePage = -1;
                        }
                    }
                }

                bool overwrite       = GetArgument(args, "overwrite").Equals("overwrite");
                bool removeTextForHi = GetArgument(args, "removetextforhi").Equals("removetextforhi");
                bool fixCommonErrors = GetArgument(args, "fixcommonerrors").Equals("fixcommonerrors");
                bool redoCasing      = GetArgument(args, "redocasing").Equals("redocasing");
                bool multipleReplace = GetArgument(args, "multiplereplace").Equals("multiplereplace");

                var patterns = Enumerable.Empty <string>();

                if (pattern.Contains(',') && !File.Exists(pattern))
                {
                    patterns = pattern.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(fn => fn.Trim()).Where(fn => fn.Length > 0);
                }
                else
                {
                    patterns = patterns.DefaultIfEmpty(pattern);
                }

                var files = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

                foreach (var p in patterns)
                {
                    var folderName = Path.GetDirectoryName(p);
                    var fileName   = Path.GetFileName(p);
                    if (string.IsNullOrEmpty(folderName) || string.IsNullOrEmpty(fileName))
                    {
                        folderName = inputFolder;
                        fileName   = p;
                    }
                    else if (!Path.IsPathRooted(folderName))
                    {
                        folderName = Path.Combine(inputFolder, folderName);
                    }
                    foreach (var fn in Directory.EnumerateFiles(folderName, fileName))
                    {
                        files.Add(fn); // silently ignore duplicates
                    }
                }

                var formats = SubtitleFormat.AllSubtitleFormats;
                foreach (var fileName in files)
                {
                    count++;

                    var fileInfo = new FileInfo(fileName);
                    if (fileInfo.Exists)
                    {
                        var            sub    = new Subtitle();
                        SubtitleFormat format = null;
                        bool           done   = false;

                        if (fileInfo.Extension.Equals(".mkv", StringComparison.OrdinalIgnoreCase) || fileInfo.Extension.Equals(".mks", StringComparison.OrdinalIgnoreCase))
                        {
                            using (var matroska = new MatroskaFile(fileName))
                            {
                                if (matroska.IsValid)
                                {
                                    var tracks = matroska.GetTracks();
                                    if (tracks.Count > 0)
                                    {
                                        foreach (var track in tracks)
                                        {
                                            if (track.CodecId.Equals("S_VOBSUB", StringComparison.OrdinalIgnoreCase))
                                            {
                                                Console.WriteLine("{0}: {1} - Cannot convert from VobSub image based format!", fileName, targetFormat);
                                            }
                                            else if (track.CodecId.Equals("S_HDMV/PGS", StringComparison.OrdinalIgnoreCase))
                                            {
                                                Console.WriteLine("{0}: {1} - Cannot convert from Blu-ray image based format!", fileName, targetFormat);
                                            }
                                            else
                                            {
                                                var ss = matroska.GetSubtitle(track.TrackNumber, null);
                                                format = Utilities.LoadMatroskaTextSubtitle(track, matroska, ss, sub);
                                                string newFileName = fileName;
                                                if (tracks.Count > 1)
                                                {
                                                    newFileName = fileName.Insert(fileName.Length - 4, "_" + track.TrackNumber + "_" + track.Language.Replace("?", string.Empty).Replace("!", string.Empty).Replace("*", string.Empty).Replace(",", string.Empty).Replace("/", string.Empty).Trim());
                                                }

                                                if (format.GetType() == typeof(AdvancedSubStationAlpha) || format.GetType() == typeof(SubStationAlpha))
                                                {
                                                    if (!AdvancedSubStationAlpha.NameOfFormat.Replace(" ", string.Empty).Equals(targetFormat, StringComparison.OrdinalIgnoreCase) &&
                                                        !SubStationAlpha.NameOfFormat.Replace(" ", string.Empty).Equals(targetFormat, StringComparison.OrdinalIgnoreCase))
                                                    {
                                                        foreach (SubtitleFormat sf in formats)
                                                        {
                                                            if (sf.Name.Replace(" ", string.Empty).Equals(targetFormat, StringComparison.OrdinalIgnoreCase))
                                                            {
                                                                format.RemoveNativeFormatting(sub, sf);
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }

                                                BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, newFileName, sub, format, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing, multipleReplace);
                                                done = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (!done && FileUtil.IsBluRaySup(fileName))
                        {
                            Console.WriteLine("Found Blu-Ray subtitle format");
                            ConvertBluRaySubtitle(fileName, targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing, multipleReplace);
                            done = true;
                        }
                        if (!done && FileUtil.IsVobSub(fileName))
                        {
                            Console.WriteLine("Found VobSub subtitle format");
                            ConvertVobSubSubtitle(fileName, targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing, multipleReplace);
                            done = true;
                        }

                        if (!done && fileInfo.Length < 10 * 1024 * 1024) // max 10 mb
                        {
                            Encoding encoding;
                            format = sub.LoadSubtitle(fileName, out encoding, null, true);

                            if (format == null || format.GetType() == typeof(Ebu))
                            {
                                var ebu = new Ebu();
                                if (ebu.IsMine(null, fileName))
                                {
                                    ebu.LoadSubtitle(sub, null, fileName);
                                    format = ebu;
                                }
                            }
                            if (format == null)
                            {
                                var pac = new Pac();
                                if (pac.IsMine(null, fileName))
                                {
                                    pac.BatchMode = true;
                                    pac.CodePage  = pacCodePage;
                                    pac.LoadSubtitle(sub, null, fileName);
                                    format = pac;
                                }
                            }
                            if (format == null)
                            {
                                var cavena890 = new Cavena890();
                                if (cavena890.IsMine(null, fileName))
                                {
                                    cavena890.LoadSubtitle(sub, null, fileName);
                                    format = cavena890;
                                }
                            }
                            if (format == null)
                            {
                                var spt = new Spt();
                                if (spt.IsMine(null, fileName))
                                {
                                    spt.LoadSubtitle(sub, null, fileName);
                                    format = spt;
                                }
                            }
                            if (format == null)
                            {
                                var cheetahCaption = new CheetahCaption();
                                if (cheetahCaption.IsMine(null, fileName))
                                {
                                    cheetahCaption.LoadSubtitle(sub, null, fileName);
                                    format = cheetahCaption;
                                }
                            }
                            if (format == null)
                            {
                                var chk = new Chk();
                                if (chk.IsMine(null, fileName))
                                {
                                    chk.LoadSubtitle(sub, null, fileName);
                                    format = chk;
                                }
                            }
                            if (format == null)
                            {
                                var ayato = new Ayato();
                                if (ayato.IsMine(null, fileName))
                                {
                                    ayato.LoadSubtitle(sub, null, fileName);
                                    format = ayato;
                                }
                            }
                            if (format == null)
                            {
                                var capMakerPlus = new CapMakerPlus();
                                if (capMakerPlus.IsMine(null, fileName))
                                {
                                    capMakerPlus.LoadSubtitle(sub, null, fileName);
                                    format = capMakerPlus;
                                }
                            }
                            if (format == null)
                            {
                                var captionate = new Captionate();
                                if (captionate.IsMine(null, fileName))
                                {
                                    captionate.LoadSubtitle(sub, null, fileName);
                                    format = captionate;
                                }
                            }
                            if (format == null)
                            {
                                var ultech130 = new Ultech130();
                                if (ultech130.IsMine(null, fileName))
                                {
                                    ultech130.LoadSubtitle(sub, null, fileName);
                                    format = ultech130;
                                }
                            }
                            if (format == null)
                            {
                                var nciCaption = new NciCaption();
                                if (nciCaption.IsMine(null, fileName))
                                {
                                    nciCaption.LoadSubtitle(sub, null, fileName);
                                    format = nciCaption;
                                }
                            }
                            if (format == null)
                            {
                                var tsb4 = new TSB4();
                                if (tsb4.IsMine(null, fileName))
                                {
                                    tsb4.LoadSubtitle(sub, null, fileName);
                                    format = tsb4;
                                }
                            }
                            if (format == null)
                            {
                                var avidStl = new AvidStl();
                                if (avidStl.IsMine(null, fileName))
                                {
                                    avidStl.LoadSubtitle(sub, null, fileName);
                                    format = avidStl;
                                }
                            }
                            if (format == null)
                            {
                                var elr = new ELRStudioClosedCaption();
                                if (elr.IsMine(null, fileName))
                                {
                                    elr.LoadSubtitle(sub, null, fileName);
                                    format = elr;
                                }
                            }
                        }

                        if (format == null)
                        {
                            if (fileInfo.Length < 1024 * 1024) // max 1 mb
                            {
                                Console.WriteLine("{0}: {1} - input file format unknown!", fileName, targetFormat);
                            }
                            else
                            {
                                Console.WriteLine("{0}: {1} - input file too large!", fileName, targetFormat);
                            }
                        }
                        else if (!done)
                        {
                            BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, fileName, sub, format, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing, multipleReplace);
                        }
                    }
                    else
                    {
                        Console.WriteLine("{0}: {1} - file not found!", count, fileName);
                        errors++;
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine();
                Console.WriteLine("Oops - an error occured: " + exception.Message);
                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine("{0} file(s) converted", converted);
            Console.WriteLine();

            if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux())
            {
                Console.Write(currentFolder + ">");
                NativeMethods.FreeConsole();
            }

            if (count == converted && errors == 0)
            {
                Environment.Exit(0);
            }
            else
            {
                Environment.Exit(1);
            }
        }
示例#11
0
        public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName)
        {
            _errorCount = 0;

            subtitle.Paragraphs.Clear();
            subtitle.Header = null;
            byte[] buffer = FileUtil.ReadAllBytesShared(fileName);

            string title = Encoding.ASCII.GetString(buffer, 82, 66);

            int i = 128;

            while (i < buffer.Length - 66)
            {
                if (buffer[i] == 0xff && buffer[i + 1] == 0xff && buffer[i + 3] != 0xff && buffer[i - 1] != 0xff && buffer[i + 64] == 0xff && buffer[i + 65] == 0xff)
                {
                    var p  = new Paragraph();
                    var sb = new StringBuilder();
                    int j  = i + 4;
                    while (j < i + 64)
                    {
                        if (buffer[j] == 0)
                        {
                            break;
                        }
                        else if (buffer[j] == 0xd)
                        {
                            sb.AppendLine();
                            j += 3;
                        }
                        else if (buffer[j] == 0x87)
                        {
                            sb.Append('♪');
                            j++;
                        }
                        else
                        {
                            sb.Append(Encoding.GetEncoding(1252).GetString(buffer, j, 1));
                            j++;
                        }
                    }
                    p.Text = sb.ToString();
                    subtitle.Paragraphs.Add(p);
                    i += 62;
                }
                else
                {
                    i++;
                }
            }
            subtitle.Renumber();

            if (buffer[0] == 0x43 && // CAPT.1.2
                buffer[1] == 0x41 &&
                buffer[2] == 0x50 &&
                buffer[3] == 0x54 &&
                buffer[4] == 0x00 &&
                buffer[5] == 0x31 &&
                buffer[6] == 0x2e &&
                buffer[7] == 0x32)
            {
                i = 396;
                int start  = i;
                int number = 0;
                while (i < buffer.Length - 66)
                {
                    if (buffer[i] == 0xff && buffer[i + 1] == 0xff && buffer[i + 2] != 0xff && buffer[i + 28] == 0xff && buffer[i + 29] == 0xff && buffer[i + 30] != 0xff)
                    {
                        if (buffer[i + 14] == number + 1)
                        {
                            Paragraph p = subtitle.GetParagraphOrDefault(number);
                            if (p != null)
                            {
                                p.StartTime = DecodeTimeCode(buffer, i + 18);
                                p.EndTime   = DecodeTimeCode(buffer, i + 22);
                                number++;
                            }
                            i += 25;
                        }
                    }
                    i++;
                }
            }
            else
            {
                i = 230;
                int countTimecodes = 0;
                int start          = i;
                int lastNumber     = -1;
                while (i < buffer.Length - 66)
                {
                    if (buffer[i] == 0xff && buffer[i + 1] == 0xff && buffer[i + 2] == 0xff && buffer[i + 3] == 0xff)
                    {
                        int length = i - start - 2;
                        if (length >= 10)
                        {
                            int count = length / 14;
                            if (length % 14 == 10)
                            {
                                count++;
                            }
                            else
                            {
                                //System.Windows.Forms.MessageBox.Show("Problem at with a length of " + length.ToString() + " at file position " + (i + 2) + " which gives remainer: " + (length % 14));
                                if (length % 14 == 8)
                                {
                                    count++;
                                }
                            }
                            for (int k = 0; k < count; k++)
                            {
                                int index  = start + 2 + (14 * k);
                                int number = buffer[index] + buffer[index + 1] * 256;
                                if (number != lastNumber + 1)
                                {
                                    int tempNumber = buffer[index - 2] + buffer[index - 1] * 256;
                                    if (tempNumber == lastNumber + 1)
                                    {
                                        index -= 2;
                                        number = tempNumber;
                                    }
                                }
                                if (number > lastNumber)
                                {
                                    lastNumber = number;
                                    Paragraph p = subtitle.GetParagraphOrDefault(number);
                                    if (p != null)
                                    {
                                        if (k < count - 1)
                                        {
                                            p.StartTime = DecodeTimeCode(buffer, index + 6);
                                            p.EndTime   = DecodeTimeCode(buffer, index + 10);
                                        }
                                        else
                                        {
                                            p.StartTime = DecodeTimeCode(buffer, index + 6);
                                        }
                                        countTimecodes++;
                                    }
                                }
                            }
                        }
                        start = i + 2;
                        i    += 5;
                    }
                    i++;
                }
            }

            for (i = 0; i < subtitle.Paragraphs.Count; i++)
            {
                Paragraph p    = subtitle.GetParagraphOrDefault(i);
                Paragraph next = subtitle.GetParagraphOrDefault(i + 1);
                if (next != null && p.EndTime.TotalMilliseconds == 0)
                {
                    p.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - 1;
                }
            }

            for (i = 0; i < subtitle.Paragraphs.Count; i++)
            {
                Paragraph p    = subtitle.GetParagraphOrDefault(i);
                Paragraph next = subtitle.GetParagraphOrDefault(i + 1);
                if (p.Duration.TotalMilliseconds <= 0 && next != null)
                {
                    p.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - 1;
                }
            }

            subtitle.RemoveEmptyLines();
            Paragraph last = subtitle.GetParagraphOrDefault(subtitle.Paragraphs.Count - 1);

            if (last != null)
            {
                last.EndTime.TotalMilliseconds = last.StartTime.TotalMilliseconds + Utilities.GetOptimalDisplayMilliseconds(last.Text);
            }
            subtitle.Renumber();
        }
示例#12
0
        internal MonitorTestHelper(ITestHelperConfiguration config, IBasicTestHelper basic)
        {
            _config = config;
            _basic  = basic;

            basic.OnlyOnce(() =>
            {
                _logToBinFile = _config.GetBoolean("Monitor/LogToBinFile")
                                ?? _config.GetBoolean("Monitor/LogToBinFiles")
                                ?? false;
                _logToTextFile = _config.GetBoolean("Monitor/LogToTextFile")
                                 ?? _config.GetBoolean("Monitor/LogToTextFiles")
                                 ?? false;

                string logLevel = _config.Get("Monitor/LogLevel");
                if (logLevel != null)
                {
                    var lf = LogFilter.Parse(logLevel);
                    ActivityMonitor.DefaultFilter = lf;
                }
                LogFile.RootLogPath = basic.LogFolder;
                var conf            = new GrandOutputConfiguration();
                if (_logToBinFile)
                {
                    var binConf = new BinaryFileConfiguration
                    {
                        UseGzipCompression = true,
                        Path = FileUtil.CreateUniqueTimedFolder(LogFile.RootLogPath + "CKMon/", null, DateTime.UtcNow)
                    };
                    conf.AddHandler(binConf);
                }
                if (_logToTextFile)
                {
                    var txtConf = new TextFileConfiguration
                    {
                        Path = FileUtil.CreateUniqueTimedFolder(LogFile.RootLogPath + "Text/", null, DateTime.UtcNow)
                    };
                    conf.AddHandler(txtConf);
                }
                GrandOutput.EnsureActiveDefault(conf, clearExistingTraceListeners: false);
                var monitorListener = Trace.Listeners.OfType <MonitorTraceListener>().FirstOrDefault(m => m.GrandOutput == GrandOutput.Default);
                // (Defensive programming) There is no real reason for this listener to not be in the listeners, but it can be.
                if (monitorListener != null)
                {
                    // If our standard MonitorTraceListener has been injected, then we remove the StaticBasicTestHelper.SafeTraceListener
                    // that throws Exceptions instead of callinf FailFast.
                    Trace.Listeners.Remove("CK.Testing.SafeTraceListener");
                }
            });
            _monitor               = new ActivityMonitor("MonitorTestHelper");
            _console               = new ActivityMonitorConsoleClient();
            LogToConsole           = _config.GetBoolean("Monitor/LogToConsole") ?? false;
            basic.OnCleanupFolder += OnCleanupFolder;
            basic.OnlyOnce(() =>
            {
                var basePath = LogFile.RootLogPath + "Text" + FileUtil.DirectorySeparatorString;
                if (Directory.Exists(basePath))
                {
                    CleanupTimedFolders(_monitor, _basic, basePath, MaxCurrentLogFolderCount, MaxArchivedLogFolderCount);
                }
                basePath = LogFile.RootLogPath + "CKMon" + FileUtil.DirectorySeparatorString;
                if (Directory.Exists(basePath))
                {
                    CleanupTimedFolders(_monitor, _basic, basePath, MaxCurrentLogFolderCount, MaxArchivedLogFolderCount);
                }
            });
        }
        protected void InspectorGUI()
        {
            #region Object
            {
                explosionObject.edit_objectFoldout = EditorGUILayout.Foldout(explosionObject.edit_objectFoldout, "Object", guiStyleFoldoutBold);
                if (explosionObject.edit_objectFoldout)
                {
                    EditorGUILayout.BeginVertical(GUI.skin.box);
                    #region Mesh
                    {
                        EditorGUILayout.LabelField("Mesh", EditorStyles.boldLabel);
                        EditorGUI.indentLevel++;
                        #region Mesh
                        if (explosionObject.meshes != null)
                        {
                            for (int i = 0; i < explosionObject.meshes.Count; i++)
                            {
                                EditorGUILayout.BeginHorizontal();
                                {
                                    EditorGUI.BeginDisabledGroup(true);
                                    EditorGUILayout.ObjectField(explosionObject.meshes[i].mesh, typeof(Mesh), false);
                                    EditorGUI.EndDisabledGroup();
                                }
                                if (explosionObject.meshes[i].mesh != null)
                                {
                                    if (!EditorCommon.IsMainAsset(explosionObject.meshes[i].mesh))
                                    {
                                        if (GUILayout.Button("Save", GUILayout.Width(48), GUILayout.Height(16)))
                                        {
                                            #region Create Mesh
                                            string path = EditorUtility.SaveFilePanel("Save mesh", chunkCore.GetDefaultPath(), string.Format("{0}_{1}_explosion_mesh{2}.asset", voxelObject.gameObject.name, chunkObject.chunkName, i), "asset");
                                            if (!string.IsNullOrEmpty(path))
                                            {
                                                if (path.IndexOf(Application.dataPath) < 0)
                                                {
                                                    EditorCommon.SaveInsideAssetsFolderDisplayDialog();
                                                }
                                                else
                                                {
                                                    Undo.RecordObject(explosionObject, "Save Mesh");
                                                    path = FileUtil.GetProjectRelativePath(path);
                                                    AssetDatabase.CreateAsset(Mesh.Instantiate(explosionObject.meshes[i].mesh), path);
                                                    explosionObject.meshes[i].mesh = AssetDatabase.LoadAssetAtPath <Mesh>(path);
                                                    voxelExplosionCore.Generate();
                                                }
                                            }
                                            #endregion
                                        }
                                    }
                                    {
                                        if (GUILayout.Button("Reset", GUILayout.Width(48), GUILayout.Height(16)))
                                        {
                                            #region Reset Mesh
                                            Undo.RecordObject(voxelExplosionObject, "Reset Mesh");
                                            Undo.RecordObjects(voxelExplosionObject.chunksExplosion, "Reset Mesh");
                                            explosionObject.meshes[i].mesh = null;
                                            voxelExplosionCore.Generate();
                                            #endregion
                                        }
                                    }
                                }
                                EditorGUILayout.EndHorizontal();
                            }
                        }
                        #endregion
                        EditorGUI.indentLevel--;
                    }
                    #endregion
                    #region Material
                    if (voxelObject.materialMode == VoxelChunksObject.MaterialMode.Individual)
                    {
                        EditorGUILayout.LabelField("Material", EditorStyles.boldLabel);
                        EditorGUI.indentLevel++;
                        #region Material
                        for (int i = 0; i < explosionObject.materials.Count; i++)
                        {
                            EditorGUILayout.BeginHorizontal();
                            {
                                EditorGUI.BeginDisabledGroup(true);
                                EditorGUILayout.ObjectField(explosionObject.materials[i], typeof(Material), false);
                                EditorGUI.EndDisabledGroup();
                            }
                            if (explosionObject.materials[i] != null)
                            {
                                if (!EditorCommon.IsMainAsset(explosionObject.materials[i]))
                                {
                                    if (GUILayout.Button("Save", GUILayout.Width(48), GUILayout.Height(16)))
                                    {
                                        #region Create Material
                                        string defaultName = string.Format("{0}_{1}_explosion_mat{2}.mat", voxelObject.gameObject.name, chunkObject.chunkName, i);
                                        string path        = EditorUtility.SaveFilePanel("Save material", chunkCore.GetDefaultPath(), defaultName, "mat");
                                        if (!string.IsNullOrEmpty(path))
                                        {
                                            if (path.IndexOf(Application.dataPath) < 0)
                                            {
                                                EditorCommon.SaveInsideAssetsFolderDisplayDialog();
                                            }
                                            else
                                            {
                                                Undo.RecordObject(explosionObject, "Save Material");
                                                path = FileUtil.GetProjectRelativePath(path);
                                                AssetDatabase.CreateAsset(Material.Instantiate(explosionObject.materials[i]), path);
                                                explosionObject.materials[i] = AssetDatabase.LoadAssetAtPath <Material>(path);
                                                voxelExplosionCore.Generate();
                                            }
                                        }

                                        #endregion
                                    }
                                }
                                {
                                    if (GUILayout.Button("Reset", GUILayout.Width(48), GUILayout.Height(16)))
                                    {
                                        #region Reset Material
                                        Undo.RecordObject(voxelExplosionObject, "Reset Material");
                                        Undo.RecordObjects(voxelExplosionObject.chunksExplosion, "Reset Material");
                                        explosionObject.materials[i] = EditorCommon.Instantiate(explosionObject.materials[i]);
                                        voxelExplosionCore.Generate();
                                        #endregion
                                    }
                                }
                            }
                            EditorGUILayout.EndHorizontal();
                        }
                        #endregion
                        EditorGUI.indentLevel--;
                    }
                    #endregion
                    EditorGUILayout.EndVertical();
                }
            }
            #endregion

            #region Generate
            {
                if (GUILayout.Button("Generate"))
                {
                    Undo.RecordObject(voxelExplosionObject, "Generate Voxel Explosion");
                    Undo.RecordObjects(voxelExplosionObject.chunksExplosion, "Generate Voxel Explosion");
                    voxelExplosionCore.Generate();
                }
            }
            #endregion
        }
示例#14
0
 /// <summary>
 /// 删除文件夹
 /// </summary>
 /// <param name="dir"></param>
 public static void DeleteDir(string dir)
 {
     FileUtil.DeleteFileOrDirectory(dir);
 }
示例#15
0
        /// <summary>
        ///  Carrega Arquivo de cliente
        /// </summary>
        /// <param name="loadclient">boolean</param>
        /// <param name="loadendereco">boolean</param>
        /// <returns>Retorna lisat de clientes</returns>
        public List <Cliente> LoadFromFile(bool loadclient, bool loadendereco)
        {
            List <Cliente> listaCliente = new List <Cliente>();

            FileUtil      fileutilCliente = new FileUtil(EnumTipoArquivo.Cliente);
            List <string> temp            = fileutilCliente.CarregarFromFile('#');

            foreach (var item in temp)
            {
                List <string> parametros = fileutilCliente.CarregarFromString('|', item);

                Cliente clienteNovo = new Cliente();
                if (loadclient)
                {
                    int count = parametros.Count;
                    if (count >= 7)
                    {
                        var tipoClinte = parametros[0];
                        if (tipoClinte.Trim() == "Fisica")
                        {
                            clienteNovo.TipoCliente = EnumTipoCliente.Fisica;
                        }
                        else
                        {
                            clienteNovo.TipoCliente = EnumTipoCliente.Juridica;
                        }

                        var codigoDoCliente = parametros[1];
                        clienteNovo.CodigoDoCliente = Guid.Parse(codigoDoCliente);
                        var nome = parametros[2];
                        clienteNovo.Nome = nome;
                        var idade = parametros[3];
                        clienteNovo.Idade = Convert.ToInt32(idade);

                        var estadoCivil = parametros[4];
                        if (estadoCivil.Trim() == "Solteiro")
                        {
                            clienteNovo.EstadoCivil = EnumEstadoCivil.Solteiro;
                        }
                        else if (estadoCivil.Trim() == "Casado")
                        {
                            clienteNovo.EstadoCivil = EnumEstadoCivil.Casado;
                        }
                        else if (estadoCivil.Trim() == "Viuvo")
                        {
                            clienteNovo.EstadoCivil = EnumEstadoCivil.Viuvo;
                        }
                        else
                        {
                            clienteNovo.EstadoCivil = EnumEstadoCivil.Divorciado;
                        }

                        var genero = parametros[5];
                        if (genero.Trim() == "Feminino")
                        {
                            clienteNovo.Genero = EnumGenero.Feminino;
                        }
                        else if (genero.Trim() == "Masculino")
                        {
                            clienteNovo.Genero = EnumGenero.Masculino;
                        }
                        else
                        {
                            clienteNovo.Genero = EnumGenero.NA;
                        }
                    }
                    if (loadendereco)
                    {
                        Endereco endereco = new Endereco();
                        clienteNovo.listaEndereco = endereco.LoadFromFile(clienteNovo.CodigoDoCliente);
                    }
                    listaCliente.Add(clienteNovo);
                }
            }
            return(listaCliente);
        }
示例#16
0
        private void UpdatePACFile()
        {
            string gfwlist;

            try
            {
                gfwlist = File.ReadAllText(Path.Combine(directory, gfwlist_file), Encoding.UTF8);
            }
            catch
            {
                gfwlist = Resources.gfwlist;
                File.WriteAllText(Path.Combine(directory, gfwlist_file), gfwlist, Encoding.UTF8);
            }
            string userRule;
            string userPath = Path.Combine(directory, user_rule_file);

            if (!File.Exists(userPath))
            {
                userRule = Resources.user_rule;
                File.WriteAllText(Path.Combine(directory, user_rule_file), userRule, Encoding.UTF8);
            }
            else
            {
                //以只读共享方式打开文件
                using (FileStream fs = new FileStream(userPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    int    length  = (int)fs.Length;
                    byte[] content = new byte[length];
                    fs.Read(content, 0, content.Length);
                    userRule = Encoding.UTF8.GetString(content);
                }
            }
            string abpContent;

            try
            {
                abpContent = File.ReadAllText(Path.Combine(directory, abp_js_file), Encoding.UTF8);
            }
            catch
            {
                FileUtil.UnGzip(Path.Combine(directory, abp_js_file), Resources.abp_js);
                abpContent = File.ReadAllText(Path.Combine(directory, abp_js_file), Encoding.UTF8);
            }
            try
            {
                List <string> lines = FileUtil.ParseResult(gfwlist);
                using (var sr = new StringReader(userRule))
                {
                    foreach (var rule in sr.NonWhiteSpaceLines())
                    {
                        if (rule.BeginWithAny(FileUtil.IgnoredLineBegins))
                        {
                            continue;
                        }
                        lines.Add(rule);
                    }
                }
                abpContent = abpContent.Replace("__PROXY__", $"PROXY 127.0.0.1:{remotePort}");
                abpContent = abpContent.Replace("__RULES__", JsonUtil.SerializeObject(lines));
                if (File.Exists(Path.Combine(directory, pac_file)))
                {
                    string original = File.ReadAllText(Path.Combine(directory, pac_file), Encoding.UTF8);
                    if (original == abpContent)
                    {
                        return;
                    }
                }
                File.WriteAllText(Path.Combine(directory, pac_file), abpContent, Encoding.UTF8);
                BalloonTip tip = new BalloonTip()
                {
                    IconIndex = 1,
                    Message   = "Update PAC file success",
                    timeout   = 3000
                };
                ShowBalloonTip?.Invoke(this, tip);
            }
            catch (Exception)
            {
                BalloonTip tip = new BalloonTip()
                {
                    IconIndex = 1,
                    Message   = "Update PAC file fail",
                    timeout   = 3000
                };
                ShowBalloonTip?.Invoke(this, tip);
            }
        }
示例#17
0
        public async Task Install(string uploadFileId, InstallWay installWay = InstallWay.Merge)
        {
            var zipFile = await _fileSeviceProvider.DownloadFileAsync(uploadFileId);

            var fileNameWithoutExt = FileUtil.GetFileNameWithoutExt(zipFile.FileName);
            var restoreFolderPath  = Path.Combine(Environment.CurrentDirectory, "Temp", "InstallationPackages");

            Directory.CreateDirectory(restoreFolderPath);
            var restoreFilePath = Path.Combine(restoreFolderPath, zipFile.FileName);

            using (var fileStream = File.Create(restoreFilePath))
            {
                fileStream.Write(zipFile.FileBytes, 0, zipFile.FileBytes.Length);
            }
            // Release file in memory
            zipFile.FileBytes = null;
            var folderExtractingPath = Path.Combine(restoreFolderPath, fileNameWithoutExt);

            if (Directory.Exists(folderExtractingPath))
            {
                Directory.Delete(folderExtractingPath, true);
            }
            ZipFile.ExtractToDirectory(restoreFilePath, folderExtractingPath);

            var jsonAppPackageFilePath = Path.Combine(folderExtractingPath, fileNameWithoutExt + ".json");

            var jsonAppPackageString = File.ReadAllText(jsonAppPackageFilePath);
            var appFlatternModel     = ConvertUtil.DeserializeObject <AppPackageFlatternModel>(jsonAppPackageString);

            var isExist = await _appRepository.IsExistAsync(a => a.Id == appFlatternModel.App.Id);

            switch (installWay)
            {
            case InstallWay.Merge:
                break;

            case InstallWay.Wipe:
                if (isExist)
                {
                    // Wipe all data
                    await _standardServiceProvider.DeleteAllByAppIdAsync(appFlatternModel.App.Id);

                    await _dynamicListServiceProvider.DeleteByAppIdAsync(appFlatternModel.App.Id);

                    await _chartServiceProvider.DeleteByAppIdAsync(appFlatternModel.App.Id);

                    await _pageServiceProvider.DeleteByAppIdAsync(appFlatternModel.App.Id);

                    await _localizationProvider.DeleteByAppIdAsync(appFlatternModel.App.Id);
                }
                break;
            }

            foreach (var chainingFile in appFlatternModel.ChainingFiles)
            {
                switch (chainingFile)
                {
                case STANDARD_FILE:
                    var standardFilePath = Path.Combine(folderExtractingPath, STANDARD_FILE);
                    var standardsString  = File.ReadAllText(standardFilePath);
                    var standardsList    = ConvertUtil.DeserializeObject <IEnumerable <StandardComponent> >(standardsString);
                    await _standardServiceProvider.ForceUpdateStandards(standardsList);

                    break;

                case DYNAMICLIST_FILE:
                    var dynamicListFilePath = Path.Combine(folderExtractingPath, DYNAMICLIST_FILE);
                    var dynamicListString   = File.ReadAllText(dynamicListFilePath);
                    var dynamicListsList    = ConvertUtil.DeserializeObject <IEnumerable <DynamicList> >(dynamicListString);
                    await _dynamicListServiceProvider.ForceUpdateDynamicLists(dynamicListsList);

                    break;

                case CHART_FILE:
                    var chartFilePath = Path.Combine(folderExtractingPath, CHART_FILE);
                    var chartsString  = File.ReadAllText(chartFilePath);
                    var chartsList    = ConvertUtil.DeserializeObject <IEnumerable <Chart> >(chartsString);
                    await _chartServiceProvider.ForceUpdateCharts(chartsList);

                    break;

                case PAGE_FILE:
                    var pageFilePath = Path.Combine(folderExtractingPath, PAGE_FILE);
                    var pagesString  = File.ReadAllText(pageFilePath);
                    var pagesList    = ConvertUtil.DeserializeObject <IEnumerable <Page> >(pagesString);
                    await _pageServiceProvider.ForceUpdatePages(pagesList);

                    break;

                case LOCALE_FILE:
                    var localeFilePath = Path.Combine(folderExtractingPath, LOCALE_FILE);
                    var localesString  = File.ReadAllText(localeFilePath);
                    var localesList    = ConvertUtil.DeserializeObject <IEnumerable <Localization> >(localesString);
                    await _localizationProvider.ForceUpdateLocalizations(localesList);

                    break;
                }
            }

            await _appRepository.ForceUpdateAsync(appFlatternModel.App.Id, appFlatternModel.App);

            Directory.Delete(folderExtractingPath, true);
            File.Delete(restoreFilePath);
        }
示例#18
0
 public static void ClearData()
 {
     FileUtil.DeleteFileOrDirectory(Application.persistentDataPath + "/" + GameDataKeeper.FileName);
 }
示例#19
0
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        PackagePullPushMono myScript = (PackagePullPushMono)target;
        string gitPath      = myScript.GetProjectPathInUnity() + "/.git";
        string projectPath  = myScript.GetProjectPathInUnity();
        string gitFolderUrl = "";

        QuickGit.GetGitUrl(projectPath, out gitFolderUrl);
        bool   isGitFolderDefine      = !string.IsNullOrEmpty(gitFolderUrl);
        string projectPathTmp         = projectPath + "tmp";
        string requiredPathFile       = projectPath + "/requiredpackages.json";
        ListOfClassicPackages package = ListOfClassicPackages.FromJsonPath(requiredPathFile);

        if (string.IsNullOrEmpty(myScript.GetGitLink()))
        {
            return;
        }
        GUILayout.Label("Commands", EditorStyles.boldLabel);
        bool isLinkValide       = myScript.IsGitLinkValide();
        bool isDirectoryCreated = myScript.IsDirectoryCreated();

        GUILayout.BeginHorizontal();
        var disableStyle = new GUIStyle(GUI.skin.button);

        disableStyle.normal.textColor = new Color(0.6627451f, 0.6627451f, 0.6627451f);
        var enableStyle = new GUIStyle(GUI.skin.button);

        enableStyle.normal.textColor = new Color(0f, 0.4f, 0f);
        if (GUILayout.Button("Down", isDirectoryCreated?disableStyle: enableStyle))
        {
            if (!isDirectoryCreated)
            {
                UnityPackageUtility.Down(projectPath, myScript.GetGitLink(), myScript.m_affectPackageManager);
            }
        }
        if (GUILayout.Button("Up", (isDirectoryCreated && isGitFolderDefine) ? enableStyle : disableStyle))
        {
            if (isGitFolderDefine)
            {
                UnityPackageUtility.Up(projectPath, myScript.m_namespaceId, myScript.GetGitLink(), myScript.m_affectPackageManager);
            }
        }
        GUILayout.EndHorizontal();
        GUILayout.Space(6);


        GUILayout.BeginHorizontal();
        //if (isLinkValide && !isDirectoryCreated && GUILayout.Button("Clone"))
        //{
        //    myScript.PullProject();
        //}
        if (isGitFolderDefine && GUILayout.Button("Pull"))
        {
            myScript.UpdateProject();
        }
        if (isGitFolderDefine && GUILayout.Button("Pull & Push"))
        {
            myScript.PullAndPush();
        }
        if (isDirectoryCreated && GUILayout.Button("Remove Project"))
        {
            RemoveFolderWithUnityTool(myScript);
        }
        GUILayout.EndHorizontal();
        GUILayout.BeginHorizontal();
        if (isDirectoryCreated && GUILayout.Button("Open Folder"))
        {
            myScript.OpenDirectory();
        }
        if (isDirectoryCreated && isGitFolderDefine && GUILayout.Button("Open Cmd"))
        {
            myScript.OpenStatusInCommentLine();
        }
        if (isLinkValide && GUILayout.Button("Open Git Server"))
        {
            Application.OpenURL(myScript.GetGitLink());
        }
        GUILayout.EndHorizontal();
        GUILayout.BeginHorizontal();

        if (isDirectoryCreated && isGitFolderDefine && GUILayout.Button("Remove Git Info"))
        {
            FileUtil.DeleteFileOrDirectory(gitPath);
        }
        if (isDirectoryCreated && !isGitFolderDefine && GUILayout.Button("Add Git Info"))
        {
            Directory.CreateDirectory(projectPathTmp);
            FileUtil.ReplaceDirectory(projectPath, projectPathTmp);
            FileUtil.DeleteFileOrDirectory(projectPath);
            Directory.CreateDirectory(projectPath);

            //QuickGit.CreateLocal(projectPath);
            // QuickGit.PushLocalToGitLab(projectPath, myScript.m_gitUserName, GetProjectDatedNameId(myScript), out gitUrl);
            QuickGit.Clone(myScript.GetGitLink(), projectPath);
            FileUtil.ReplaceDirectory(gitPath, projectPathTmp + "/.git");
            FileUtil.DeleteFileOrDirectory(projectPath);
            FileUtil.ReplaceDirectory(projectPathTmp, projectPath);
            FileUtil.DeleteFileOrDirectory(projectPathTmp);

            //FileUtil.ReplaceDirectory(projectPathTmp, projectPath);
            // FileUtil.DeleteFileOrDirectory(projectPathTmp);
        }

        GUILayout.EndHorizontal();


        if (package.m_packageLinks.Length > 0)
        {
            GUILayout.Label("Required Unitypackage:", EditorStyles.boldLabel);
        }
        GUILayout.BeginHorizontal();
        for (int i = 0; i < package.m_packageLinks.Length; i++)
        {
            ClassicUnityPackageLink link = package.m_packageLinks[i];
            string path = package.m_packageLinks[i].m_pathOrLink;

            if (link.IsUnityPackage())
            {
                if (link.IsWebPath() && GUILayout.Button("Web: " + link.m_name))
                {
                    string pathUnityPackage = Application.dataPath + "/../Temp/lastpackagedownloaded.unitypackage";
                    using (var client = new WebClient())
                    {
                        File.WriteAllBytes(pathUnityPackage, client.DownloadData(path));
                    }
                    Application.OpenURL(pathUnityPackage);
                    // FileUtil.DeleteFileOrDirectory(pathUnityPackage);
                }
                else if (link.IsWindowPath() && GUILayout.Button("Local: " + link.m_name))
                {
                    Application.OpenURL(path);
                }
            }

            if (link.IsAssetStoreLink() && GUILayout.Button("Store: " + link.m_name))
            {
                Application.OpenURL(path);
            }
        }
        GUILayout.EndHorizontal();
    }
示例#20
0
        public static void Convert(string title, string[] args) // E.g.: /convert *.txt SubRip
        {
            const int ATTACH_PARENT_PROCESS = -1;

            if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux())
            {
                NativeMethods.AttachConsole(ATTACH_PARENT_PROCESS);
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine(title + " - Batch converter");
            Console.WriteLine();
            Console.WriteLine("- Syntax: SubtitleEdit /convert <pattern> <name-of-format-without-spaces> [/offset:hh:mm:ss:ms] [/encoding:<encoding name>] [/fps:<frame rate>] [/targetfps:<frame rate>] [/inputfolder:<input folder>] [/outputfolder:<output folder>] [/removetextforhi] [/fixcommonerrors] [/pac-codepage:<code page>]");
            Console.WriteLine();
            Console.WriteLine("    example: SubtitleEdit /convert *.srt sami");
            Console.WriteLine("    list available formats: SubtitleEdit /convert /list");
            Console.WriteLine();

            string currentDir = Directory.GetCurrentDirectory();

            if (args.Length < 4)
            {
                if (args.Length == 3 && (args[2].Equals("/list", StringComparison.OrdinalIgnoreCase) || args[2].Equals("-list", StringComparison.OrdinalIgnoreCase)))
                {
                    Console.WriteLine("- Supported formats (input/output):");
                    foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats)
                    {
                        Console.WriteLine("    " + format.Name.Replace(" ", string.Empty));
                    }
                    Console.WriteLine();
                    Console.WriteLine("- Supported formats (input only):");
                    Console.WriteLine("    " + CapMakerPlus.NameOfFormat);
                    Console.WriteLine("    " + Captionate.NameOfFormat);
                    Console.WriteLine("    " + Cavena890.NameOfFormat);
                    Console.WriteLine("    " + CheetahCaption.NameOfFormat);
                    Console.WriteLine("    " + Chk.NameOfFormat);
                    Console.WriteLine("    Matroska (.mkv)");
                    Console.WriteLine("    Matroska subtitle (.mks)");
                    Console.WriteLine("    " + NciCaption.NameOfFormat);
                    Console.WriteLine("    " + AvidStl.NameOfFormat);
                    Console.WriteLine("    " + Pac.NameOfFormat);
                    Console.WriteLine("    " + Spt.NameOfFormat);
                    Console.WriteLine("    " + Ultech130.NameOfFormat);
                    Console.WriteLine("- For Blu-ray .sup output use: '" + BatchConvert.BluRaySubtitle.Replace(" ", string.Empty) + "'");
                    Console.WriteLine("- For VobSub .sub output use: '" + BatchConvert.VobSubSubtitle.Replace(" ", string.Empty) + "'");
                }

                Console.WriteLine();
                Console.Write(currentDir + ">");
                if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux())
                {
                    NativeMethods.FreeConsole();
                }
                Environment.Exit(1);
            }

            int count     = 0;
            int converted = 0;
            int errors    = 0;

            try
            {
                string pattern  = args[2];
                string toFormat = args[3];
                string offset   = GetArgument(args, "/offset:");

                var fps = GetArgument(args, "/fps:");
                if (fps.Length > 6)
                {
                    fps = fps.Remove(0, 5).Replace(',', '.').Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, ".").Trim();
                    double d;
                    if (double.TryParse(fps, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
                    {
                        Configuration.Settings.General.CurrentFrameRate = d;
                    }
                }

                var    targetFps       = GetArgument(args, "/targetfps:");
                double?targetFrameRate = null;
                if (targetFps.Length > 12)
                {
                    targetFps = targetFps.Remove(0, 11).Replace(',', '.').Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, ".").Trim();
                    double d;
                    if (double.TryParse(targetFps, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
                    {
                        targetFrameRate = d;
                    }
                }

                var targetEncodingName = GetArgument(args, "/encoding:");;
                var targetEncoding     = Encoding.UTF8;
                try
                {
                    if (!string.IsNullOrEmpty(targetEncodingName))
                    {
                        targetEncodingName = targetEncodingName.Substring(10);
                        if (!string.IsNullOrEmpty(targetEncodingName))
                        {
                            targetEncoding = Encoding.GetEncoding(targetEncodingName);
                        }
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Unable to set encoding (" + exception.Message + ") - using UTF-8");
                    targetEncoding = Encoding.UTF8;
                }

                var outputFolder = GetArgument(args, "/outputfolder:");;
                if (outputFolder.Length > "/outputFolder:".Length)
                {
                    outputFolder = outputFolder.Remove(0, "/outputFolder:".Length);
                    if (!Directory.Exists(outputFolder))
                    {
                        outputFolder = string.Empty;
                    }
                }

                var inputFolder = GetArgument(args, "/inputFolder:", Directory.GetCurrentDirectory());
                if (inputFolder.Length > "/inputFolder:".Length)
                {
                    inputFolder = inputFolder.Remove(0, "/inputFolder:".Length);
                    if (!Directory.Exists(inputFolder))
                    {
                        inputFolder = Directory.GetCurrentDirectory();
                    }
                }

                var pacCodePage = GetArgument(args, "/pac-codepage:");
                if (pacCodePage.Length > "/pac-codepage:".Length)
                {
                    pacCodePage = pacCodePage.Remove(0, "/pac-codepage:".Length);
                    if (string.Compare("Latin", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        pacCodePage = "0";
                    }
                    else if (string.Compare("Greek", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        pacCodePage = "1";
                    }
                    else if (string.Compare("Czech", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        pacCodePage = "2";
                    }
                    else if (string.Compare("Arabic", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        pacCodePage = "3";
                    }
                    else if (string.Compare("Hebrew", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        pacCodePage = "4";
                    }
                    else if (string.Compare("Encoding", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        pacCodePage = "5";
                    }
                    else if (string.Compare("Cyrillic", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        pacCodePage = "6";
                    }
                }

                bool overwrite       = GetArgument(args, "/overwrite", string.Empty).Equals("/overwrite");
                bool removeTextForHi = GetArgument(args, "/removetextforhi", string.Empty).Equals("/removetextforhi");
                bool fixCommonErrors = GetArgument(args, "/fixcommonerrors", string.Empty).Equals("/fixcommonerrors");
                bool redoCasing      = GetArgument(args, "/redocasing", string.Empty).Equals("/redocasing");

                string[] files;
                string   inputDirectory = Directory.GetCurrentDirectory();
                if (!string.IsNullOrEmpty(inputFolder))
                {
                    inputDirectory = inputFolder;
                }

                if (pattern.Contains(',') && !File.Exists(pattern))
                {
                    files = pattern.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int k = 0; k < files.Length; k++)
                    {
                        files[k] = files[k].Trim();
                    }
                }
                else
                {
                    int indexOfDirectorySeparatorChar = pattern.LastIndexOf(Path.DirectorySeparatorChar);
                    if (indexOfDirectorySeparatorChar > 0 && indexOfDirectorySeparatorChar < pattern.Length)
                    {
                        pattern        = pattern.Substring(indexOfDirectorySeparatorChar + 1);
                        inputDirectory = args[2].Substring(0, indexOfDirectorySeparatorChar);
                    }
                    files = Directory.GetFiles(inputDirectory, pattern);
                }

                var formats = SubtitleFormat.AllSubtitleFormats;
                foreach (string fName in files)
                {
                    string fileName = fName;
                    count++;

                    if (!string.IsNullOrEmpty(inputFolder) && File.Exists(Path.Combine(inputFolder, fileName)))
                    {
                        fileName = Path.Combine(inputFolder, fileName);
                    }

                    if (File.Exists(fileName))
                    {
                        var            sub    = new Subtitle();
                        SubtitleFormat format = null;
                        bool           done   = false;

                        if (Path.GetExtension(fileName).Equals(".mkv", StringComparison.OrdinalIgnoreCase) || Path.GetExtension(fileName).Equals(".mks", StringComparison.OrdinalIgnoreCase))
                        {
                            using (var matroska = new MatroskaFile(fileName))
                            {
                                if (matroska.IsValid)
                                {
                                    var tracks = matroska.GetTracks();
                                    if (tracks.Count > 0)
                                    {
                                        foreach (var track in tracks)
                                        {
                                            if (track.CodecId.Equals("S_VOBSUB", StringComparison.OrdinalIgnoreCase))
                                            {
                                                Console.WriteLine("{0}: {1} - Cannot convert from VobSub image based format!", fileName, toFormat);
                                            }
                                            else if (track.CodecId.Equals("S_HDMV/PGS", StringComparison.OrdinalIgnoreCase))
                                            {
                                                Console.WriteLine("{0}: {1} - Cannot convert from Blu-ray image based format!", fileName, toFormat);
                                            }
                                            else
                                            {
                                                var ss = matroska.GetSubtitle(track.TrackNumber, null);
                                                format = Utilities.LoadMatroskaTextSubtitle(track, matroska, ss, sub);
                                                string newFileName = fileName;
                                                if (tracks.Count > 1)
                                                {
                                                    newFileName = fileName.Insert(fileName.Length - 4, "_" + track.TrackNumber + "_" + track.Language.Replace("?", string.Empty).Replace("!", string.Empty).Replace("*", string.Empty).Replace(",", string.Empty).Replace("/", string.Empty).Trim());
                                                }

                                                if (format.GetType() == typeof(AdvancedSubStationAlpha) || format.GetType() == typeof(SubStationAlpha))
                                                {
                                                    if (toFormat.ToLower() != AdvancedSubStationAlpha.NameOfFormat.ToLower().Replace(" ", string.Empty) &&
                                                        toFormat.ToLower() != SubStationAlpha.NameOfFormat.ToLower().Replace(" ", string.Empty))
                                                    {
                                                        foreach (SubtitleFormat sf in formats)
                                                        {
                                                            if (sf.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) || sf.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase))
                                                            {
                                                                format.RemoveNativeFormatting(sub, sf);
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }

                                                BatchConvertSave(toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, newFileName, sub, format, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing);
                                                done = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (FileUtil.IsBluRaySup(fileName))
                        {
                            Console.WriteLine("Found Blu-Ray subtitle format");
                            ConvertBluRaySubtitle(fileName, toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing);
                            done = true;
                        }
                        if (!done && FileUtil.IsVobSub(fileName))
                        {
                            Console.WriteLine("Found VobSub subtitle format");
                            ConvertVobSubSubtitle(fileName, toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing);
                            done = true;
                        }

                        var fi = new FileInfo(fileName);
                        if (fi.Length < 10 * 1024 * 1024 && !done) // max 10 mb
                        {
                            Encoding encoding;
                            format = sub.LoadSubtitle(fileName, out encoding, null, true);

                            if (format == null || format.GetType() == typeof(Ebu))
                            {
                                var ebu = new Ebu();
                                if (ebu.IsMine(null, fileName))
                                {
                                    ebu.LoadSubtitle(sub, null, fileName);
                                    format = ebu;
                                }
                            }
                            if (format == null)
                            {
                                var pac = new Pac();
                                if (pac.IsMine(null, fileName))
                                {
                                    pac.BatchMode = true;

                                    if (!string.IsNullOrEmpty(pacCodePage) && Utilities.IsInteger(pacCodePage))
                                    {
                                        pac.CodePage = int.Parse(pacCodePage);
                                    }
                                    else
                                    {
                                        pac.CodePage = -1;
                                    }

                                    pac.LoadSubtitle(sub, null, fileName);
                                    format = pac;
                                }
                            }
                            if (format == null)
                            {
                                var cavena890 = new Cavena890();
                                if (cavena890.IsMine(null, fileName))
                                {
                                    cavena890.LoadSubtitle(sub, null, fileName);
                                    format = cavena890;
                                }
                            }
                            if (format == null)
                            {
                                var spt = new Spt();
                                if (spt.IsMine(null, fileName))
                                {
                                    spt.LoadSubtitle(sub, null, fileName);
                                    format = spt;
                                }
                            }
                            if (format == null)
                            {
                                var cheetahCaption = new CheetahCaption();
                                if (cheetahCaption.IsMine(null, fileName))
                                {
                                    cheetahCaption.LoadSubtitle(sub, null, fileName);
                                    format = cheetahCaption;
                                }
                            }
                            if (format == null)
                            {
                                var chk = new Chk();
                                if (chk.IsMine(null, fileName))
                                {
                                    chk.LoadSubtitle(sub, null, fileName);
                                    format = chk;
                                }
                            }
                            if (format == null)
                            {
                                var ayato = new Ayato();
                                if (ayato.IsMine(null, fileName))
                                {
                                    ayato.LoadSubtitle(sub, null, fileName);
                                    format = ayato;
                                }
                            }
                            if (format == null)
                            {
                                var capMakerPlus = new CapMakerPlus();
                                if (capMakerPlus.IsMine(null, fileName))
                                {
                                    capMakerPlus.LoadSubtitle(sub, null, fileName);
                                    format = capMakerPlus;
                                }
                            }
                            if (format == null)
                            {
                                var captionate = new Captionate();
                                if (captionate.IsMine(null, fileName))
                                {
                                    captionate.LoadSubtitle(sub, null, fileName);
                                    format = captionate;
                                }
                            }
                            if (format == null)
                            {
                                var ultech130 = new Ultech130();
                                if (ultech130.IsMine(null, fileName))
                                {
                                    ultech130.LoadSubtitle(sub, null, fileName);
                                    format = ultech130;
                                }
                            }
                            if (format == null)
                            {
                                var nciCaption = new NciCaption();
                                if (nciCaption.IsMine(null, fileName))
                                {
                                    nciCaption.LoadSubtitle(sub, null, fileName);
                                    format = nciCaption;
                                }
                            }
                            if (format == null)
                            {
                                var tsb4 = new TSB4();
                                if (tsb4.IsMine(null, fileName))
                                {
                                    tsb4.LoadSubtitle(sub, null, fileName);
                                    format = tsb4;
                                }
                            }
                            if (format == null)
                            {
                                var avidStl = new AvidStl();
                                if (avidStl.IsMine(null, fileName))
                                {
                                    avidStl.LoadSubtitle(sub, null, fileName);
                                    format = avidStl;
                                }
                            }
                            if (format == null)
                            {
                                var elr = new ELRStudioClosedCaption();
                                if (elr.IsMine(null, fileName))
                                {
                                    elr.LoadSubtitle(sub, null, fileName);
                                    format = elr;
                                }
                            }
                        }

                        if (format == null)
                        {
                            if (fi.Length < 1024 * 1024) // max 1 mb
                            {
                                Console.WriteLine("{0}: {1} - input file format unknown!", fileName, toFormat);
                            }
                            else
                            {
                                Console.WriteLine("{0}: {1} - input file too large!", fileName, toFormat);
                            }
                        }
                        else if (!done)
                        {
                            BatchConvertSave(toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, fileName, sub, format, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing);
                        }
                    }
                    else
                    {
                        Console.WriteLine("{0}: {1} - file not found!", count, fileName);
                        errors++;
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine();
                Console.WriteLine("Ups - an error occured: " + exception.Message);
                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine("{0} file(s) converted", converted);
            Console.WriteLine();
            Console.Write(currentDir + ">");

            if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux())
            {
                NativeMethods.FreeConsole();
            }

            if (count == converted && errors == 0)
            {
                Environment.Exit(0);
            }
            else
            {
                Environment.Exit(1);
            }
        }
示例#21
0
        // 从本地获得两个配置文件的内容
        // return:
        //      -1  出错
        //      0   正常返回
        //      1   配置文件没有找到,但 host 已经初始化
        int GetCodeFromLocal(
            string strAutogenDataCfgFilename,
            out string strCode,
            out string strRef,
            out string strError)
        {
            strError = "";
            strCode  = "";
            strRef   = "";

            if (File.Exists(strAutogenDataCfgFilename) == false)
            {
                IDetailHost host = null;

                if (this.DetailHostType != null)
                {
                    host = (IDetailHost)DetailHostType.InvokeMember(null,
                                                                    BindingFlags.DeclaredOnly |
                                                                    BindingFlags.Public | BindingFlags.NonPublic |
                                                                    BindingFlags.Instance | BindingFlags.CreateInstance, null, null,
                                                                    null);
                }
                else
                {
                    host = new DetailHost();
                }

                host.Assembly        = null;
                host.Form            = this._myForm;
                host.DetailWindow    = this._myForm as IBiblioItemsWindow;
                this.m_detailHostObj = host;

                m_strAutogenDataCfgFilename = strAutogenDataCfgFilename;

                this.m_autogenDataAssembly = Assembly.GetAssembly(this.GetType());  // 充数
                return(1);
            }

            // 能自动识别文件内容的编码方式的读入文本文件内容模块
            // parameters:
            //      lMaxLength  装入的最大长度。如果超过,则超过的部分不装入。如果为-1,表示不限制装入长度
            // return:
            //      -1  出错 strError中有返回值
            //      0   文件不存在 strError中有返回值
            //      1   文件存在
            //      2   读入的内容不是全部
            int nRet = FileUtil.ReadTextFileContent(strAutogenDataCfgFilename,
                                                    -1,
                                                    out strCode,
                                                    out Encoding encoding,
                                                    out strError);

            if (nRet != 1)
            {
                return(-1);
            }

            string strCfgFilePath = strAutogenDataCfgFilename + ".ref"; // strBiblioDbName + "/cfgs/" + this.ScriptFileName + ".ref";

            if (File.Exists(strCfgFilePath) == true)
            {
                nRet = FileUtil.ReadTextFileContent(strCfgFilePath,
                                                    -1,
                                                    out strRef,
                                                    out encoding,
                                                    out strError);
                if (nRet != 1)
                {
                    return(-1);
                }
            }

            return(0);
        }
//----------------------------------------------------------------------------------------------------------------------

        internal static void Import(ImageFileImporterParam param)
        {
            string destFolder = null;

            if (!param.CopyToStreamingAssets)
            {
                destFolder = param.strSrcFolder.Replace("\\", "/");
            }
            else
            {
                destFolder = param.strDstFolder.Replace("\\", "/");
                if (destFolder.StartsWith(Application.dataPath) && !destFolder.StartsWith(Path.Combine(Application.dataPath, "StreamingAssets").Replace("\\", "/")))
                {
                    Debug.LogError("Files must be located under StreamingAssets folder.");
                    return;
                }

                foreach (WatchedFileInfo fileInfo in param.ImageFiles)
                {
                    string fileName          = fileInfo.GetName();
                    string strAbsFilePathDst = Path.Combine(destFolder, fileName).Replace("\\", "/");
                    if (File.Exists(strAbsFilePathDst))
                    {
                        File.Delete(strAbsFilePathDst);
                    }
                    string strAbsFilePathSrc = Path.Combine(param.strSrcFolder, fileName).Replace("\\", "/");
                    Directory.CreateDirectory(Path.GetDirectoryName(strAbsFilePathDst));//make sure dir exists
                    FileUtil.CopyFileOrDirectory(strAbsFilePathSrc, strAbsFilePathDst);
                }
            }

            //if possible, convert folder names to relative path.
            string strUnityProjectFolder = null;
            Regex  regAssetFolder        = new Regex("/Assets$");

            strUnityProjectFolder = Application.dataPath;
            strUnityProjectFolder = regAssetFolder.Replace(strUnityProjectFolder, "");

            if (destFolder.StartsWith(strUnityProjectFolder))
            {
                int start = strUnityProjectFolder.Length + 1;
                int end   = destFolder.Length - start;
                destFolder = destFolder.Substring(start, end);
            }

            //StreamingAsset
            StreamingImageSequencePlayableAsset playableAsset = param.TargetAsset;

            if (null == playableAsset)
            {
                string assetName = EstimateAssetName(param.ImageFiles[0].GetName());
                playableAsset = CreateUniqueSISAsset(
                    Path.Combine("Assets", assetName + "_StreamingImageSequence.playable").Replace("\\", "/")

                    );
            }

            playableAsset.InitFolderInEditor(destFolder, param.ImageFiles);
            if (param.CopyToStreamingAssets)
            {
                AssetDatabase.Refresh();
            }
        }
示例#23
0
        private void ButtonOpenSubtitle1Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = string.Empty;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (FileUtil.IsVobSub(openFileDialog1.FileName) || FileUtil.IsBluRaySup(openFileDialog1.FileName))
                {
                    MessageBox.Show(Configuration.Settings.Language.CompareSubtitles.CannotCompareWithImageBasedSubtitles);
                    return;
                }
                _subtitle1 = new Subtitle();
                Encoding encoding;
                var      format = _subtitle1.LoadSubtitle(openFileDialog1.FileName, out encoding, null);
                if (format == null)
                {
                    var pac = new Pac();
                    if (pac.IsMine(null, openFileDialog1.FileName))
                    {
                        pac.BatchMode = true;
                        pac.LoadSubtitle(_subtitle1, null, openFileDialog1.FileName);
                        format = pac;
                    }
                }
                if (format == null)
                {
                    var cavena890 = new Cavena890();
                    if (cavena890.IsMine(null, openFileDialog1.FileName))
                    {
                        cavena890.LoadSubtitle(_subtitle1, null, openFileDialog1.FileName);
                    }
                }
                if (format == null)
                {
                    var spt = new Spt();
                    if (spt.IsMine(null, openFileDialog1.FileName))
                    {
                        spt.LoadSubtitle(_subtitle1, null, openFileDialog1.FileName);
                    }
                }
                if (format == null)
                {
                    var cheetahCaption = new CheetahCaption();
                    if (cheetahCaption.IsMine(null, openFileDialog1.FileName))
                    {
                        cheetahCaption.LoadSubtitle(_subtitle1, null, openFileDialog1.FileName);
                    }
                }
                if (format == null)
                {
                    var chk = new Chk();
                    if (chk.IsMine(null, openFileDialog1.FileName))
                    {
                        chk.LoadSubtitle(_subtitle1, null, openFileDialog1.FileName);
                    }
                }
                if (format == null)
                {
                    var asc = new TimeLineAscii();
                    if (asc.IsMine(null, openFileDialog1.FileName))
                    {
                        asc.LoadSubtitle(_subtitle1, null, openFileDialog1.FileName);
                    }
                }
                if (format == null)
                {
                    var asc = new TimeLineFootageAscii();
                    if (asc.IsMine(null, openFileDialog1.FileName))
                    {
                        asc.LoadSubtitle(_subtitle1, null, openFileDialog1.FileName);
                    }
                }
                subtitleListView1.Fill(_subtitle1);
                subtitleListView1.SelectIndexAndEnsureVisible(0);
                subtitleListView2.SelectIndexAndEnsureVisible(0);
                labelSubtitle1.Text = openFileDialog1.FileName;
                _language1          = LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitle1);
                if (_subtitle1.Paragraphs.Count > 0)
                {
                    CompareSubtitles();
                }
            }
        }
 static void CleanResourcesDirectory()
 {
     FileUtil.DeleteFileOrDirectory(StreamingResourcesDirectory);
 }
示例#25
0
文件: Nsf.cs 项目: qyf0310/vgmtoolbox
 public void UpdateSongName(string pNewValue)
 {
     FileUtil.UpdateTextField(this.filePath, pNewValue, NAME_OFFSET,
                              NAME_LENGTH);
 }
示例#26
0
        public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName)
        {
            subtitle.Paragraphs.Clear();
            subtitle.Header = null;
            byte[] buffer = FileUtil.ReadAllBytesShared(fileName);

            int       i    = 256;
            Paragraph last = null;

            while (i < buffer.Length - 20)
            {
                var p = new Paragraph();

                while (buffer[i] != 0xfe && i < buffer.Length - 20)
                {
                    i++;
                }
                if (buffer[i] == 0xfe)
                {
                    i += 4;
                    string startTime = Encoding.ASCII.GetString(buffer, i, 8);
                    i += 8;
                    if (Utilities.IsInteger(startTime))
                    {
                        p.StartTime = DecodeTimestamp(startTime);
                    }
                }

                bool startFound = false;
                bool textEnd    = false;
                while (!startFound && !textEnd && i < buffer.Length - 20)
                {
                    bool skip = false;
                    if (buffer[i] == 0x0d)
                    {
                        i++;
                    }
                    else if (buffer[i] == 0x0a)
                    {
                        skip = true;
                    }
                    else if (buffer[i] == 0x14 && buffer[i + 1] == 0x2c) // text end
                    {
                        textEnd = true;
                    }
                    else if (buffer[i] <= 0x20) // text start
                    {
                        i++;
                    }
                    else
                    {
                        startFound = true;
                    }

                    if (!skip)
                    {
                        i++;
                    }
                }
                i++;

                if (!textEnd)
                {
                    i -= 2;
                    int start = i;
                    var sb    = new StringBuilder();
                    while (!textEnd && i < buffer.Length - 20)
                    {
                        if (buffer[i] == 0x14 && buffer[i + 1] == 0x2c) // text end
                        {
                            textEnd = true;
                        }
                        else if (buffer[i] == 0xd && buffer[i + 1] == 0xa) // text end
                        {
                            textEnd = true;
                        }
                        else if (buffer[i] <= 0x17)
                        {
                            if (!sb.ToString().EndsWith(Environment.NewLine))
                            {
                                sb.Append(Environment.NewLine);
                            }
                            i++;
                        }
                        else
                        {
                            sb.Append(Encoding.GetEncoding(1252).GetString(buffer, i, 1));
                        }
                        i++;
                    }
                    i++;
                    if (sb.Length > 0)
                    {
                        string text = sb.ToString().Trim();
                        p.Text = text;
                        subtitle.Paragraphs.Add(p);
                        last = p;
                    }
                }

                if (buffer[i] == 0xFE)
                {
                    string endTime = Encoding.ASCII.GetString(buffer, i + 4, 8);
                    if (Utilities.IsInteger(endTime))
                    {
                        p.EndTime = DecodeTimestamp(endTime);
                    }
                    while (i < buffer.Length && buffer[i] != 0xa)
                    {
                        i++;
                    }
                    i++;
                }
                else
                {
                    while (i < buffer.Length && buffer[i] != 0xa)
                    {
                        i++;
                    }
                    i++;

                    if (buffer[i] == 0xfe)
                    {
                        string endTime = Encoding.ASCII.GetString(buffer, i + 4, 8);
                        if (Utilities.IsInteger(endTime))
                        {
                            p.EndTime = DecodeTimestamp(endTime);
                        }
                    }
                }
            }
            if (last != null && last.Duration.TotalMilliseconds > Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds)
            {
                last.EndTime.TotalMilliseconds = last.StartTime.TotalMilliseconds + Utilities.GetOptimalDisplayMilliseconds(last.Text);
            }

            subtitle.Renumber(1);
        }
示例#27
0
文件: Nsf.cs 项目: qyf0310/vgmtoolbox
 public void UpdateCopyright(string pNewValue)
 {
     FileUtil.UpdateTextField(this.filePath, pNewValue, COPYRIGHT_OFFSET,
                              COPYRIGHT_LENGTH);
 }
示例#28
0
        private void ConvertPlayerDlltoCpp(ICollection <string> userAssemblies, string outputDirectory, string workingDirectory)
        {
            FileUtil.CreateOrCleanDirectory(outputDirectory);
            if (userAssemblies.Count == 0)
            {
                return;
            }
            string[] array = (from s in Directory.GetFiles("Assets", "il2cpp_extra_types.txt", SearchOption.AllDirectories)
                              select Path.Combine(Directory.GetCurrentDirectory(), s)).ToArray <string>();
            string        il2CppExe = this.GetIl2CppExe();
            List <string> list      = new List <string>();

            list.Add("--convert-to-cpp");
            list.Add("--copy-level=None");
            if (this.m_PlatformProvider.emitNullChecks)
            {
                list.Add("--emit-null-checks");
            }
            if (this.m_PlatformProvider.enableStackTraces)
            {
                list.Add("--enable-stacktrace");
            }
            if (this.m_PlatformProvider.enableArrayBoundsCheck)
            {
                list.Add("--enable-array-bounds-check");
            }
            if (this.m_PlatformProvider.compactMode)
            {
                list.Add("--output-format=Compact");
            }
            if (this.m_PlatformProvider.loadSymbols)
            {
                list.Add("--enable-symbol-loading");
            }
            if (this.m_PlatformProvider.developmentMode)
            {
                list.Add("--development-mode");
            }
            if (array.Length > 0)
            {
                string[] array2 = array;
                for (int i = 0; i < array2.Length; i++)
                {
                    string arg2 = array2[i];
                    list.Add(string.Format("--extra-types.file=\"{0}\"", arg2));
                }
            }
            string text = Path.Combine(this.m_PlatformProvider.il2CppFolder, "il2cpp_default_extra_types.txt");

            if (File.Exists(text))
            {
                list.Add(string.Format("--extra-types.file=\"{0}\"", text));
            }
            string text2 = string.Empty;

            if (PlayerSettings.GetPropertyOptionalString("additionalIl2CppArgs", ref text2))
            {
                list.Add(text2);
            }
            text2 = Environment.GetEnvironmentVariable("IL2CPP_ADDITIONAL_ARGS");
            if (!string.IsNullOrEmpty(text2))
            {
                list.Add(text2);
            }
            List <string> source = new List <string>(userAssemblies);

            list.AddRange(from arg in source
                          select "--assembly=\"" + Path.GetFullPath(arg) + "\"");
            list.Add(string.Format("--generatedcppdir=\"{0}\"", Path.GetFullPath(outputDirectory)));
            string text3 = list.Aggregate(string.Empty, (string current, string arg) => current + arg + " ");

            Console.WriteLine("Invoking il2cpp with arguments: " + text3);
            if (EditorUtility.DisplayCancelableProgressBar("Building Player", "Converting managed assemblies to C++", 0.3f))
            {
                throw new OperationCanceledException();
            }
            Runner.RunManagedProgram(il2CppExe, text3, workingDirectory, new Il2CppOutputParser());
        }
示例#29
0
        private void SaveAssets()
        {
            if (string.IsNullOrEmpty(saveFolder))
            {
                saveFolder = "Assets/";
            }
            string folder = EditorUtility.OpenFolderPanel("Select Folder", saveFolder, "");

            if (string.IsNullOrEmpty(folder))
            {
                return;
            }
            try
            {
                saveFolder = folder;
                GAnalytics.Record(GAnalytics.BILLBOARD_SAVE);
                EditorUtility.DisplayProgressBar("Saving", "Saving assets...", 1f);
                GBillboardCreatorArgs args      = ConstructArgs();
                BillboardAsset        billboard = GBillboardCreator.CreateBillboardAsset(args);
                Texture2D             atlas     = GBillboardCreator.RenderAtlas(args);
                Texture2D             normal    = GBillboardCreator.RenderNormal(args);

                string         billboardPath  = Path.Combine(FileUtil.GetProjectRelativePath(saveFolder), billboard.name + ".asset");
                BillboardAsset billboardAsset = AssetDatabase.LoadAssetAtPath <BillboardAsset>(billboardPath);
                if (billboardAsset == null)
                {
                    AssetDatabase.CreateAsset(billboard, billboardPath);
                    billboardAsset = billboard;
                }
                else
                {
                    billboardAsset.SetVertices(billboard.GetVertices());
                    billboardAsset.SetIndices(billboard.GetIndices());
                    billboardAsset.SetImageTexCoords(billboard.GetImageTexCoords());
                    billboardAsset.width  = billboard.width;
                    billboardAsset.height = billboard.height;
                    billboardAsset.bottom = billboard.bottom;
                    billboardAsset.name   = billboard.name;
                }

                string atlasPath = Path.Combine(FileUtil.GetProjectRelativePath(saveFolder), atlas.name + ".png");
                byte[] atlasData = atlas.EncodeToPNG();
                File.WriteAllBytes(atlasPath, atlasData);
                GUtilities.DestroyObject(atlas);

                string normalPath = Path.Combine(FileUtil.GetProjectRelativePath(saveFolder), normal.name + ".png");
                byte[] normalData = normal.EncodeToPNG();
                File.WriteAllBytes(normalPath, normalData);
                GUtilities.DestroyObject(normal);

                AssetDatabase.Refresh();

                TextureImporter atlasImporter = AssetImporter.GetAtPath(atlasPath) as TextureImporter;
                atlasImporter.wrapMode            = TextureWrapMode.Clamp;
                atlasImporter.alphaIsTransparency = true;
                atlasImporter.SaveAndReimport();
                atlas = AssetDatabase.LoadAssetAtPath <Texture2D>(atlasPath);

                TextureImporter normalImporter = AssetImporter.GetAtPath(normalPath) as TextureImporter;
                normalImporter.textureType = TextureImporterType.NormalMap;
                normalImporter.wrapMode    = TextureWrapMode.Clamp;
                normalImporter.SaveAndReimport();
                normal = AssetDatabase.LoadAssetAtPath <Texture2D>(normalPath);


                Material mat = null;
                if (GCommon.CurrentRenderPipeline == GRenderPipelineType.Universal)
                {
                    mat = Object.Instantiate(GRuntimeSettings.Instance.foliageRendering.urpTreeBillboardMaterial);
                }
                else
                {
                    mat = Object.Instantiate(GRuntimeSettings.Instance.foliageRendering.treeBillboardMaterial);
                }
                if (mat != null)
                {
                    if (mat.HasProperty("_MainTex"))
                    {
                        mat.SetTexture("_MainTex", atlas);
                    }
                    if (mat.HasProperty("_BumpMap"))
                    {
                        mat.SetTexture("_BumpMap", normal);
                    }
                    mat.name = args.Target.name + "_BillboardMaterial";
                    string matPath = Path.Combine(FileUtil.GetProjectRelativePath(saveFolder), mat.name + ".mat");
                    AssetDatabase.CreateAsset(mat, matPath);
                    billboardAsset.material = mat;
                }
                AssetDatabase.Refresh();
            }
            catch (System.Exception e)
            {
                Debug.LogError(e.ToString());
            }

            EditorUtility.ClearProgressBar();
        }
示例#30
0
 /// <summary>
 /// A simple constructor that initializes the object with the given values.
 /// </summary>
 /// <param name="p_modOldMod">The mod from which to upgrade.</param>
 /// <param name="p_modNewMod">The mod to which to upgrade.</param>
 /// <param name="p_gmdGameMode">The current game mode.</param>
 /// <param name="p_eifEnvironmentInfo">The application's envrionment info.</param>
 /// <param name="p_futFileUtility">The file utility class.</param>
 /// <param name="p_scxUIContext">The <see cref="SynchronizationContext"/> to use to marshall UI interactions to the UI thread.</param>
 /// <param name="p_ilgModInstallLog">The install log that tracks mod install info
 /// for the current game mode</param>
 /// <param name="p_pmgPluginManager">The plugin manager.</param>
 /// <param name="p_dlgOverwriteConfirmationDelegate">The method to call in order to confirm an overwrite.</param>
 public ModUpgrader(IMod p_modOldMod, IMod p_modNewMod, IGameMode p_gmdGameMode, IEnvironmentInfo p_eifEnvironmentInfo, FileUtil p_futFileUtility, SynchronizationContext p_scxUIContext, IInstallLog p_ilgModInstallLog, IPluginManager p_pmgPluginManager, ConfirmItemOverwriteDelegate p_dlgOverwriteConfirmationDelegate)
     : base(p_modNewMod, p_gmdGameMode, p_eifEnvironmentInfo, p_futFileUtility, p_scxUIContext, p_ilgModInstallLog, p_pmgPluginManager, p_dlgOverwriteConfirmationDelegate, null, null)
 {
     OldMod = p_modOldMod;
 }
示例#31
0
 /// <summary>
 /// Method to Get Diff Report of 2 files
 /// Requires that a Runner.exe.config or RunnerW.exe.config exist in the Runner directory. 
 /// </summary>
 /// <returns></returns>
 public static string GetDiffReport(string expectedfile, string actualfile, string testname)
 {
     FileUtil fu = new FileUtil();
     string result = fu.CreateDifferenceReport(expectedfile, actualfile, testname);
     return fu.CreateAHrefTag(result, "Report");
 }
示例#32
0
        protected override void Initialize()
        {
            myUtil = new FileUtil();

            base.Initialize();
        }