Combine() public static méthode

public static Combine ( ) : string
Résultat string
            public LocalMarketDataStorageDrive(LocalMarketDataDrive parent, SecurityId securityId, string fileName, StorageFormats format, IMarketDataDrive drive)
            {
                if (parent == null)
                {
                    throw new ArgumentNullException("parent");
                }

                if (securityId.IsDefault())
                {
                    throw new ArgumentNullException("securityId");
                }

                if (drive == null)
                {
                    throw new ArgumentNullException("drive");
                }

                if (fileName.IsEmpty())
                {
                    throw new ArgumentNullException("fileName");
                }

                _parent                = parent;
                _securityId            = securityId;
                _fileName              = fileName;
                _format                = format;
                _drive                 = drive;
                _fileNameWithExtension = _fileName + GetExtension(_format);

                _datesDict = new Lazy <CachedSynchronizedOrderedDictionary <DateTime, DateTime> >(() =>
                {
                    var retVal = new CachedSynchronizedOrderedDictionary <DateTime, DateTime>();

                    var datesPath = GetDatesCachePath();

                    if (File.Exists(datesPath))
                    {
                        foreach (var date in LoadDates())
                        {
                            retVal.Add(date, date);
                        }
                    }
                    else
                    {
                        var rootDir = Path;

                        var dates = InteropHelper
                                    .GetDirectories(rootDir)
                                    .Where(dir => File.Exists(IOPath.Combine(dir, _fileNameWithExtension)))
                                    .Select(dir => IOPath.GetFileName(dir).ToDateTime(_dateFormat));

                        foreach (var date in dates)
                        {
                            retVal.Add(date, date);
                        }

                        SaveDates(retVal.CachedValues);
                    }

                    return(retVal);
                }).Track();
            }
Exemple #2
0
 public TempDirectory()
 {
     Path = IOPath.Combine(IOPath.GetTempPath(), IOPath.GetRandomFileName());
     Directory.CreateDirectory(Path);
 }
        private void RenderPreviews()
        {
            //render the segment previews for the visualization
            Directory.CreateDirectory(Path.Combine(outdir, "\\previews\\"));

            //read in the patterns and save out their layers
            List <PatternItem> patterns = PatternIO.GetPatterns(imagedir);

            int hpadding = 30;

            foreach (PatternItem p in patterns)
            {
                Bitmap image    = new Bitmap(p.FullPath);
                String basename = p.Name;

                if (!palettes.ContainsKey(basename))
                {
                    continue;
                }

                PaletteData palette = palettes[basename];

                ColorTemplate template = new ColorTemplate(image, palette);
                SegmentMesh   mesh     = new SegmentMesh(template);

                //create a pattern directory (Not using PatternIO here, since each pattern has its own directory anyways)
                String patternDir = Path.Combine(outdir, "previews", Util.ConvertFileName(basename, "", ""));
                Directory.CreateDirectory(patternDir);

                //for each segment, pair of adjacent segments, and group, output a preview image
                List <Segment>      segs   = mesh.getSegments();
                List <SegmentGroup> groups = mesh.getGroups();

                Bitmap original = (renderFinal)? image : template.DebugQuantization();

                Bitmap previewBase = new Bitmap(original.Width * 2 + hpadding, original.Height);
                //draw the original image on the right
                Graphics g = Graphics.FromImage(previewBase);
                g.DrawImage(original, original.Width + hpadding, 0);

                //draw a grayscaled image on the left
                for (int i = 0; i < original.Width; i++)
                {
                    for (int j = 0; j < original.Height; j++)
                    {
                        int gray = (int)Math.Round(255 * original.GetPixel(i, j).GetBrightness());
                        previewBase.SetPixel(i, j, Color.FromArgb(gray, gray, gray));
                    }
                }

                //color in orange and blue

                for (int i = 0; i < segs.Count(); i++)
                {
                    Bitmap unary = new Bitmap(previewBase);
                    foreach (var point in segs[i].points)
                    {
                        unary.SetPixel(point.X, point.Y, Color.Orange);
                    }
                    unary.Save(Path.Combine(patternDir, "s" + i + ".png"));

                    foreach (int j in segs[i].adjacencies)
                    {
                        if (j > i)
                        {
                            Bitmap binary = new Bitmap(unary);

                            Segment neighbor = segs[j];
                            foreach (var point in neighbor.points)
                            {
                                binary.SetPixel(point.X, point.Y, Color.ForestGreen);
                            }

                            binary.Save(Path.Combine(patternDir, "s" + i + "-s" + j + ".png"));
                            binary.Dispose();
                        }
                    }
                    unary.Dispose();
                }

                for (int i = 0; i < groups.Count(); i++)
                {
                    Bitmap group = new Bitmap(previewBase);
                    foreach (int j in groups[i].members)
                    {
                        Segment member = segs[j];

                        //color in the points
                        foreach (var point in member.points)
                        {
                            group.SetPixel(point.X, point.Y, Color.Orange);
                        }
                    }
                    group.Save(Path.Combine(patternDir, "g" + i + ".png"));
                    group.Dispose();
                }


                original.Dispose();
                previewBase.Dispose();
            }
        }
 private string GetDatesCachePath()
 {
     return(IOPath.Combine(Path, GetDatesCacheFileName()));
 }
Exemple #5
0
        private void _ExportBeginImpl(string[] features, bool isDebug, string path, int flags)
        {
            if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
            {
                return;
            }

            string platform = DeterminePlatformFromFeatures(features);

            if (platform == null)
            {
                throw new NotSupportedException("Target platform not supported");
            }

            string outputDir = new FileInfo(path).Directory?.FullName ??
                               throw new FileNotFoundException("Base directory not found");

            string buildConfig = isDebug ? "Debug" : "Release";

            string scriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, $"scripts_metadata.{(isDebug ? "debug" : "release")}");

            CsProjOperations.GenerateScriptsMetadata(GodotSharpDirs.ProjectCsProjPath, scriptsMetadataPath);

            AddFile(scriptsMetadataPath, scriptsMetadataPath);

            // Turn export features into defines
            var godotDefines = features;

            if (!BuildManager.BuildProjectBlocking(buildConfig, godotDefines))
            {
                throw new Exception("Failed to build project");
            }

            // Add dependency assemblies

            var dependencies = new Godot.Collections.Dictionary <string, string>();

            var projectDllName = (string)ProjectSettings.GetSetting("application/config/name");

            if (projectDllName.Empty())
            {
                projectDllName = "UnnamedProject";
            }

            string projectDllSrcDir  = Path.Combine(GodotSharpDirs.ResTempAssembliesBaseDir, buildConfig);
            string projectDllSrcPath = Path.Combine(projectDllSrcDir, $"{projectDllName}.dll");

            dependencies[projectDllName] = projectDllSrcPath;

            {
                string platformBclDir = DeterminePlatformBclDir(platform);

                internal_GetExportedAssemblyDependencies(projectDllName, projectDllSrcPath, buildConfig, platformBclDir, dependencies);
            }

            string apiConfig        = isDebug ? "Debug" : "Release";
            string resAssembliesDir = Path.Combine(GodotSharpDirs.ResAssembliesBaseDir, apiConfig);

            foreach (var dependency in dependencies)
            {
                string dependSrcPath = dependency.Value;
                string dependDstPath = Path.Combine(resAssembliesDir, dependSrcPath.GetFile());
                AddFile(dependSrcPath, dependDstPath);
            }

            // Mono specific export template extras (data dir)
            string outputDataDir = null;

            if (PlatformHasTemplateDir(platform))
            {
                outputDataDir = ExportDataDirectory(features, platform, isDebug, outputDir);
            }

            // AOT

            if ((bool)ProjectSettings.GetSetting("mono/export/aot/enabled"))
            {
                AotCompileDependencies(features, platform, isDebug, outputDir, outputDataDir, dependencies);
            }
        }
        private void Vis(bool figureQuality = false)
        {
            Directory.CreateDirectory(outdir + "\\viscolor\\");

            Directory.CreateDirectory(outdir + "\\vis\\");

            //read in the patterns and save out their layers
            List <PatternItem> patterns = PatternIO.GetPatterns(imagedir);

            foreach (PatternItem p in patterns)
            {
                String basename = p.Name;

                //Read the vis permutation description if available
                String specs = Path.Combine(outdir, "vis", p.Directory, Util.ConvertFileName(basename, "", ".txt"));
                if (!File.Exists(specs))
                {
                    continue;
                }

                Bitmap image = new Bitmap(p.FullPath);

                if (!palettes.ContainsKey(basename))
                {
                    continue;
                }

                PaletteData palette = palettes[basename];

                ColorTemplate template = new ColorTemplate(image, palette);


                int[] slotToColor = new int[template.NumSlots()];
                for (int i = 0; i < slotToColor.Count(); i++)
                {
                    slotToColor[i] = i;
                }

                Dictionary <int, int> groupToSlot = new Dictionary <int, int>();
                PaletteData           data        = new PaletteData();

                int ngroups = 0;
                for (int i = 0; i < slotToColor.Count(); i++)
                {
                    slotToColor[i] = i;
                    data.colors.Add(new Color());
                    data.lab.Add(new CIELAB());

                    if (template.PixelsInSlot(i) > 0)
                    {
                        groupToSlot.Add(ngroups++, i);
                    }
                }

                Bitmap   vis = null;
                Graphics g   = null;

                String[] lines = File.ReadAllLines(specs);


                //read the score and if it's the original or not
                double score = 0;
                bool   orig  = false;

                int  nresult  = 0;
                int  y        = 0;
                int  x        = 0;
                int  ncol     = 8;
                int  iwidth   = 200;
                int  iheight  = 200;
                int  padding  = (figureQuality) ? 8 : 15;
                Font font     = new Font("Arial", 8);
                int  colorIdx = 0;

                foreach (String line in lines)
                {
                    if (line.StartsWith("Count"))
                    {
                        int count = Int32.Parse(line.Split(' ').Last());

                        //initialize the result image
                        int nrow = count / ncol + 1;
                        vis = new Bitmap(ncol * iwidth, nrow * iheight);
                        g   = Graphics.FromImage(vis);
                    }
                    else if (line.StartsWith("Score"))
                    {
                        //add the result to the visualization
                        x = (nresult % ncol) * iwidth;
                        y = (nresult / ncol) * iheight;

                        if (colorIdx > 0)
                        {
                            Bitmap result = (renderFinal) ? GetFinalRendering(Util.ConvertFileName(basename, "", ""), data): template.SolidColor(data, slotToColor);
                            //sometimes we can't get the nice image, so render the quantized image in this case
                            if (result == null)
                            {
                                result = template.SolidColor(data, slotToColor);
                            }
                            g.DrawImage(result, x, y, iwidth - padding, iheight - padding);

                            String label = String.Format("{0:0.00}", score);
                            Color  color = Color.Black;
                            if (orig)
                            {
                                label += ", ***";
                                color  = Color.Red;
                            }
                            if (!figureQuality)
                            {
                                g.DrawString(label, font, new SolidBrush(color), x, y + iheight - padding);
                            }

                            result.Dispose();

                            colorIdx = 0;
                            //data.colors.Clear();
                            //data.lab.Clear();

                            nresult++;
                        }
                        score = Double.Parse(line.Split(' ')[1]);
                        orig  = Boolean.Parse(line.Split(' ')[2]);
                    }
                    else
                    {
                        //rgb floats
                        int[] fields = line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select <String, int>(s => ((int)(Math.Round(double.Parse(s) * 255)))).ToArray <int>();
                        Color color  = Color.FromArgb(fields[0], fields[1], fields[2]);
                        data.colors[groupToSlot[colorIdx]] = color;
                        data.lab[groupToSlot[colorIdx]]    = Util.RGBtoLAB(color);
                        colorIdx++;
                    }
                }

                //save the last image
                if (data.colors.Count() > 0)
                {
                    x = (nresult % ncol) * iwidth;
                    y = (nresult / ncol) * iheight;

                    Bitmap result = (renderFinal)? GetFinalRendering(Util.ConvertFileName(basename, "", ""), data): template.SolidColor(data, slotToColor);
                    //sometimes we can't get the nice image, so render the quantized image in this case
                    if (result == null)
                    {
                        result = template.SolidColor(data, slotToColor);
                    }
                    g.DrawImage(result, x, y, iwidth - padding, iheight - padding);
                    Color color = Color.Black;

                    String label = String.Format("{0:0.00}", score);
                    if (orig)
                    {
                        label += ", ***";
                        color  = Color.Red;
                    }

                    if (!figureQuality)
                    {
                        g.DrawString(label, font, new SolidBrush(color), x, y + iheight - padding);
                    }

                    result.Dispose();

                    //data.colors.Clear();
                    //data.lab.Clear();
                    colorIdx = 0;

                    nresult++;
                }

                PatternIO.SavePattern(vis, p, Path.Combine(outdir, "viscolor"));
                vis.Dispose();
            }
        }
    public static void Go()
    {
        Texture fntTex = (Texture)Selection.activeObject;

        var fontName = fntTex.name;
        var path     = AssetDatabase.GetAssetPath(fntTex);

        Sprite[] spts = AssetDatabase.LoadAllAssetsAtPath(path).OfType <Sprite>().ToArray();

        var dirPath = Path.GetDirectoryName(path);

        var matPath = Path.Combine(dirPath, fontName + ".mat");
        var fntMat  = AssetDatabase.LoadAssetAtPath <Material>(matPath);

        if (fntMat == null)
        {
            fntMat             = new Material(Shader.Find("UI/Default"));
            fntMat.mainTexture = fntTex;
            AssetDatabase.CreateAsset(fntMat, matPath);
        }


        var fontPath = Path.Combine(dirPath, fntTex.name + ".fontsettings");
        var font     = AssetDatabase.LoadAssetAtPath <Font>(fontPath);

        if (font == null)
        {
            font = new Font(fntTex.name);
            AssetDatabase.CreateAsset(font, fontPath);
        }
        CharacterInfo[] infos = new CharacterInfo[spts.Length];
        for (var i = 0; i < spts.Length; i++)
        {
            var spt = spts[i];
            if (i == 0)
            {
                Debug.Log("rect:" + spt.rect);
                Debug.Log("textureRect:" + spt.textureRect);
                Debug.Log("textureRectOffset:" + spt.textureRectOffset);
            }
            var uvRect = spt.rect;
            uvRect.x      = (float)uvRect.x / fntTex.width;
            uvRect.y      = (float)uvRect.y / fntTex.height;
            uvRect.width  = (float)uvRect.width / fntTex.width;
            uvRect.height = ((float)uvRect.height / fntTex.height);
//            uvRect.y -= uvRect.height;

            var info = new CharacterInfo();
            info.index = spt.name[0];

            Debug.Log(spt.name[0]);
            info.glyphWidth  = (int)spt.rect.width;
            info.glyphHeight = (int)spt.rect.height;
            info.advance     = (int)(spt.textureRect.width + 1);
            Debug.Log(info.glyphWidth);
            Debug.Log(info.glyphHeight);
            info.uvBottomLeft = uvRect.min;
            info.uvTopRight   = uvRect.max;
//            info.uvTopLeft = new Vector2(uvRect.xMin, uvRect.yMin);
//            info.uvBottomRight = new Vector2(uvRect.xMax, uvRect.yMin);
//            info.uvTopLeft = new Vector2(uvRect.xMin, uvRect.yMax);
//            info.uvBottomRight = uvRect.max; // new Vector2(uvRect.xMax, uvRect.yMax);
            infos[i] = info;
        }
        font.characterInfo = infos;

        EditorUtility.SetDirty(font);
        AssetDatabase.SaveAssets();

        //EditorUtility.DisplayDialog("提示", string.Format("功能未实现\nNot Implemented\n実装されていない\nKeine umsetzung"), "确定");
        EditorUtility.DisplayDialog("提示", string.Format("字体创建完成:{0}。\n注意:需要手动修改一下字体配置,否则退出后不会保存!", fontPath), "确定");
    }
Exemple #8
0
        private void AotCompileDependencies(string[] features, string platform, bool isDebug, string outputDir, string outputDataDir, IDictionary <string, string> dependencies)
        {
            // TODO: WASM

            string bclDir = DeterminePlatformBclDir(platform) ?? typeof(object).Assembly.Location.GetBaseDir();

            string aotTempDir = Path.Combine(Path.GetTempPath(), $"godot-aot-{Process.GetCurrentProcess().Id}");

            if (!Directory.Exists(aotTempDir))
            {
                Directory.CreateDirectory(aotTempDir);
            }

            var assemblies = new Dictionary <string, string>();

            foreach (var dependency in dependencies)
            {
                string assemblyName = dependency.Key;
                string assemblyPath = dependency.Value;

                string assemblyPathInBcl = Path.Combine(bclDir, assemblyName + ".dll");

                if (File.Exists(assemblyPathInBcl))
                {
                    // Don't create teporaries for assemblies from the BCL
                    assemblies.Add(assemblyName, assemblyPathInBcl);
                }
                else
                {
                    string tempAssemblyPath = Path.Combine(aotTempDir, assemblyName + ".dll");
                    File.Copy(assemblyPath, tempAssemblyPath);
                    assemblies.Add(assemblyName, tempAssemblyPath);
                }
            }

            foreach (var assembly in assemblies)
            {
                string assemblyName = assembly.Key;
                string assemblyPath = assembly.Value;

                string sharedLibExtension = platform == OS.Platforms.Windows ? ".dll" :
                                            platform == OS.Platforms.OSX ? ".dylib" :
                                            platform == OS.Platforms.HTML5 ? ".wasm" :
                                            ".so";

                string outputFileName = assemblyName + ".dll" + sharedLibExtension;

                if (platform == OS.Platforms.Android)
                {
                    // Not sure if the 'lib' prefix is an Android thing or just Godot being picky,
                    // but we use '-aot-' as well just in case to avoid conflicts with other libs.
                    outputFileName = "lib-aot-" + outputFileName;
                }

                string outputFilePath = null;
                string tempOutputFilePath;

                switch (platform)
                {
                case OS.Platforms.OSX:
                    tempOutputFilePath = Path.Combine(aotTempDir, outputFileName);
                    break;

                case OS.Platforms.Android:
                    tempOutputFilePath = Path.Combine(aotTempDir, "%%ANDROID_ABI%%", outputFileName);
                    break;

                case OS.Platforms.HTML5:
                    tempOutputFilePath = Path.Combine(aotTempDir, outputFileName);
                    outputFilePath     = Path.Combine(outputDir, outputFileName);
                    break;

                default:
                    tempOutputFilePath = Path.Combine(aotTempDir, outputFileName);
                    outputFilePath     = Path.Combine(outputDataDir, "Mono", platform == OS.Platforms.Windows ? "bin" : "lib", outputFileName);
                    break;
                }

                var data = new Dictionary <string, string>();
                var enabledAndroidAbis = platform == OS.Platforms.Android ? GetEnabledAndroidAbis(features).ToArray() : null;

                if (platform == OS.Platforms.Android)
                {
                    Debug.Assert(enabledAndroidAbis != null);

                    foreach (var abi in enabledAndroidAbis)
                    {
                        data["abi"] = abi;
                        var outputFilePathForThisAbi = tempOutputFilePath.Replace("%%ANDROID_ABI%%", abi);

                        AotCompileAssembly(platform, isDebug, data, assemblyPath, outputFilePathForThisAbi);

                        AddSharedObject(outputFilePathForThisAbi, tags: new[] { abi });
                    }
                }
                else
                {
                    string bits = features.Contains("64") ? "64" : features.Contains("64") ? "32" : null;

                    if (bits != null)
                    {
                        data["bits"] = bits;
                    }

                    AotCompileAssembly(platform, isDebug, data, assemblyPath, tempOutputFilePath);

                    if (platform == OS.Platforms.OSX)
                    {
                        AddSharedObject(tempOutputFilePath, tags: null);
                    }
                    else
                    {
                        Debug.Assert(outputFilePath != null);
                        File.Copy(tempOutputFilePath, outputFilePath);
                    }
                }
            }
        }
Exemple #9
0
        private void _ExportBeginImpl(string[] features, bool isDebug, string path, int flags)
        {
            if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
            {
                return;
            }

            string platform = DeterminePlatformFromFeatures(features);

            if (platform == null)
            {
                throw new NotSupportedException("Target platform not supported");
            }

            string outputDir = new FileInfo(path).Directory?.FullName ??
                               throw new FileNotFoundException("Base directory not found");

            string buildConfig = isDebug ? "Debug" : "Release";

            string scriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, $"scripts_metadata.{(isDebug ? "debug" : "release")}");

            CsProjOperations.GenerateScriptsMetadata(GodotSharpDirs.ProjectCsProjPath, scriptsMetadataPath);

            AddFile(scriptsMetadataPath, scriptsMetadataPath);

            // Turn export features into defines
            var godotDefines = features;

            if (!BuildManager.BuildProjectBlocking(buildConfig, godotDefines))
            {
                throw new Exception("Failed to build project");
            }

            // Add dependency assemblies

            var dependencies = new Godot.Collections.Dictionary <string, string>();

            var projectDllName = (string)ProjectSettings.GetSetting("application/config/name");

            if (projectDllName.Empty())
            {
                projectDllName = "UnnamedProject";
            }

            string projectDllSrcDir  = Path.Combine(GodotSharpDirs.ResTempAssembliesBaseDir, buildConfig);
            string projectDllSrcPath = Path.Combine(projectDllSrcDir, $"{projectDllName}.dll");

            dependencies[projectDllName] = projectDllSrcPath;

            if (platform == OS.Platforms.Android)
            {
                string godotAndroidExtProfileDir = GetBclProfileDir("godot_android_ext");
                string monoAndroidAssemblyPath   = Path.Combine(godotAndroidExtProfileDir, "Mono.Android.dll");

                if (!File.Exists(monoAndroidAssemblyPath))
                {
                    throw new FileNotFoundException("Assembly not found: 'Mono.Android'", monoAndroidAssemblyPath);
                }

                dependencies["Mono.Android"] = monoAndroidAssemblyPath;
            }

            var initialDependencies = dependencies.Duplicate();

            internal_GetExportedAssemblyDependencies(initialDependencies, buildConfig, DeterminePlatformBclDir(platform), dependencies);

            AddI18NAssemblies(dependencies, platform);

            string outputDataDir = null;

            if (PlatformHasTemplateDir(platform))
            {
                outputDataDir = ExportDataDirectory(features, platform, isDebug, outputDir);
            }

            string apiConfig        = isDebug ? "Debug" : "Release";
            string resAssembliesDir = Path.Combine(GodotSharpDirs.ResAssembliesBaseDir, apiConfig);

            bool assembliesInsidePck = (bool)ProjectSettings.GetSetting("mono/export/export_assemblies_inside_pck") || outputDataDir == null;

            if (!assembliesInsidePck)
            {
                string outputDataGameAssembliesDir = Path.Combine(outputDataDir, "Assemblies");
                if (!Directory.Exists(outputDataGameAssembliesDir))
                {
                    Directory.CreateDirectory(outputDataGameAssembliesDir);
                }
            }

            foreach (var dependency in dependencies)
            {
                string dependSrcPath = dependency.Value;

                if (assembliesInsidePck)
                {
                    string dependDstPath = Path.Combine(resAssembliesDir, dependSrcPath.GetFile());
                    AddFile(dependSrcPath, dependDstPath);
                }
                else
                {
                    string dependDstPath = Path.Combine(outputDataDir, "Assemblies", dependSrcPath.GetFile());
                    File.Copy(dependSrcPath, dependDstPath);
                }
            }

            // AOT

            if ((bool)ProjectSettings.GetSetting("mono/export/aot/enabled"))
            {
                AotCompileDependencies(features, platform, isDebug, outputDir, outputDataDir, dependencies);
            }
        }
Exemple #10
0
        private static string GetBclProfileDir(string profile)
        {
            string templatesDir = Internal.FullTemplatesDir;

            return(Path.Combine(templatesDir, "bcl", profile));
        }
Exemple #11
0
        public Task Run(string[] args)
        {
            if (!ParseArgs(args))
            {
                PrintUsage();
                Environment.Exit(1);
            }

            var cts = new CancellationTokenSource();
            var ct  = cts.Token;

            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                cts.Cancel();
            };

            return(Task.Run(async() =>
            {
                var res = await Toolkit.Exec("btrfs", new[] { "sub", "list", SourcePath }, ct, development);

                var nfos = new BtrfsNfos();

                var sourcePaths = new List <string>();
                foreach (var x in res.output.Lines())
                {
                    var q = x.IndexOf("path ");
                    if (q != -1)
                    {
                        var relpath = x.Substring(q + "path ".Length);
                        var subvolFullpath = Path.Combine(SourcePath, relpath);

                        var subvolInfo = await GetSubVolumeInfo(subvolFullpath, ct);

                        nfos.Add(SourcePath, relpath, subvolInfo.uuid, subvolInfo.parentUUID, subvolInfo.generation, subvolInfo.genAtCreation);
                    }
                }

                #region log helper
                var indent = 0;
                Action <BtrfsNfo> logNfo = null;
                logNfo = (entry) =>
                {
                    var indentSpaces = " ".Repeat(2 * indent);

                    System.Console.WriteLine($@"
{indentSpaces}path:[{entry.Fullpath}]
{indentSpaces}uuid:[{entry.UUID}]
{indentSpaces}parentUUID:[{entry.ParentUUID}]=[{entry.Parent?.Fullpath}]
{indentSpaces}generation:[{entry.Generation}]
{indentSpaces}genAtCreation:[{entry.GenAtCreation}]
{indentSpaces}children:[{entry.Children.Count()}]");

                    ++indent;
                    foreach (var c in entry.Children.OrderBy(w => w.GenAtCreation))
                    {
                        logNfo(c);
                    }
                    --indent;
                };

                Action header1 = () => { System.Console.WriteLine("=".Repeat(78)); };
                Action header2 = () => { System.Console.WriteLine("-".Repeat(78)); };
                #endregion

                // log
                foreach (var entry in nfos.Entries.Where(r => r.Parent == null))
                {
                    logNfo(entry);
                }

                // plan work
                var workPlan = new List <BtrfsResynActionNfo>();

                Action <BtrfsNfo> planWorkAct = null;

                planWorkAct = (entry) =>
                {
                    var entryCounterPart = entry.CounterPart(TargetPath);

                    if (entry.Parent == null && !Directory.Exists(entryCounterPart))
                    {
                        var dstPath = Path.GetDirectoryName(entryCounterPart);
                        if (!Directory.Exists(dstPath))
                        {
                            workPlan.Add(new BtrfsResynActionNfo(BtrfsRsyncActionMode.ensurePath,
                                                                 Path.GetDirectoryName(entry.Fullpath),
                                                                 dstPath));
                        }
                        workPlan.Add(new BtrfsResynActionNfo(BtrfsRsyncActionMode.createSubvol, entry.Fullpath, entryCounterPart));
                    }

                    if (entry.Children.Any())
                    {
                        foreach (var(child, idx, isLast) in entry.Children.OrderBy(w => w.GenAtCreation).WithIndexIsLast())
                        {
                            var childCounterPart = child.CounterPart(TargetPath);
                            var childCounterPartExists = Directory.Exists(childCounterPart);

                            if (childCounterPartExists)
                            {
                                if (!SkipSubVolResync)
                                {
                                    workPlan.Add(new BtrfsResynActionNfo(BtrfsRsyncActionMode.rsync, child.Fullpath, childCounterPart));
                                }
                            }
                            else if (entry.Parent == null)
                            {
                                workPlan.Add(new BtrfsResynActionNfo(BtrfsRsyncActionMode.rsync, child.Fullpath, entryCounterPart));
                                workPlan.Add(new BtrfsResynActionNfo(BtrfsRsyncActionMode.snap, entryCounterPart, childCounterPart));
                            }

                            if (child.Children.Any())
                            {
                                planWorkAct(child);
                            }

                            if (isLast)
                            {
                                workPlan.Add(new BtrfsResynActionNfo(BtrfsRsyncActionMode.rsync, entry.Fullpath, entryCounterPart,
                                                                     entry.Children.Select(w => w.CounterPart(TargetPath))));
                            }
                        }
                    }
                    else
                    {
                        workPlan.Add(new BtrfsResynActionNfo(BtrfsRsyncActionMode.rsync, entry.Fullpath, entryCounterPart));
                    }
                };

                foreach (var entry in nfos.Entries.Where(r => r.Parent == null))
                {
                    planWorkAct(entry);
                }

                #region log workplane
                {
                    System.Console.WriteLine();
                    header1();
                    System.Console.WriteLine($"WORKPLAN");
                    header1();
                    foreach (var wp in workPlan)
                    {
                        System.Console.WriteLine(wp.ToString());
                    }
                }
                #endregion

                #region dryrun log helper
                Action <string, IEnumerable <string> > dryRunProg = (p, a) =>
                {
                    System.Console.WriteLine($"{p} {string.Join(" ", a)}");
                };
                #endregion

                System.Console.WriteLine();
                header1();
                System.Console.WriteLine($"RUNNING");
                header1();

                foreach (var wp in workPlan)
                {
                    switch (wp.Mode)
                    {
                    case BtrfsRsyncActionMode.ensurePath:
                        {
                            // TODO: acl and permission set
                            var cmdprog = "mkdir";
                            var cmdargs = new List <string>()
                            {
                                "-p", wp.DestPath
                            };
                            if (RunMode == RunMode.dryRun)
                            {
                                dryRunProg(cmdprog, cmdargs);
                            }
                            else
                            {
                                var cmdres = await Toolkit.ExecNoRedirect(cmdprog, cmdargs, ct, development);
                            }
                        }
                        break;

                    case BtrfsRsyncActionMode.createSubvol:
                        {
                            var cmdprog = "btrfs";
                            var cmdargs = new List <string>()
                            {
                                "sub", "create", wp.DestPath
                            };
                            if (RunMode == RunMode.dryRun)
                            {
                                dryRunProg(cmdprog, cmdargs);
                            }
                            else
                            {
                                var cmdres = await Toolkit.ExecNoRedirect(cmdprog, cmdargs, ct, development);
                            }
                        }
                        break;

                    case BtrfsRsyncActionMode.rsync:
                        {
                            var cmdprog = "rsync";
                            var cmdargs = new List <string>();
                            cmdargs.Add("-Aav");
                            cmdargs.Add("--delete");
                            foreach (var excl in wp.rsyncExclusions)
                            {
                                cmdargs.Add($"--exclude={excl}");
                            }
                            cmdargs.Add(wp.SourcePath + "/");
                            cmdargs.Add(wp.DestPath + "/");
                            if (RunMode == RunMode.dryRun)
                            {
                                dryRunProg(cmdprog, cmdargs);
                            }
                            else
                            {
                                var cmdres = await Toolkit.ExecNoRedirect(cmdprog, cmdargs, ct, development);
                            }
                        }
                        break;

                    case BtrfsRsyncActionMode.snap:
                        {
                            var cmdprog = "btrfs";
                            var cmdargs = new List <string>()
                            {
                                "sub", "snap", wp.SourcePath, wp.DestPath
                            };
                            if (RunMode == RunMode.dryRun)
                            {
                                dryRunProg(cmdprog, cmdargs);
                            }
                            else
                            {
                                var cmdres = await Toolkit.ExecNoRedirect(cmdprog, cmdargs, ct, development);
                            }
                        }
                        break;
                    }
                }
            }));
        }
Exemple #12
0
        public void SetEvisaArabicFieldValue(string fieldName, string fieldValue)
        {
            try
            {
                _reader       = new PdfReader(fileName);
                pdfFormFields = _reader.AcroFields;
                var field = pdfFormFields.GetFieldItem(fieldName).GetValue(0);
                Console.WriteLine(field.ToString());
                var outfileName = fileName.Replace(".pdf", DateTime.Now.Ticks + ".pdf");
                _pdfStamper = new PdfStamper(_reader, new FileStream(outfileName, FileMode.Create));

                var ARIALUNI_TFF =
                    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "trado.TTF");
                var bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                var f  = new iTextSharp.text.Font(bf);

                var overContent   = _pdfStamper.GetOverContent(1); //1 means page 1
                var fieldPosition = pdfFormFields.GetFieldPositions(fieldName)[0].position;

                var ct = new ColumnText(overContent)
                {
                    RunDirection = PdfWriter.RUN_DIRECTION_RTL, YLine = 5
                };
                if (rdCenter.Checked)
                {
                    ct.SetSimpleColumn(fieldPosition.Left, fieldPosition.Bottom - fieldPosition.Height / 2,
                                       fieldPosition.Right, fieldPosition.Top - fieldPosition.Height / 2, 0, Element.ALIGN_CENTER);
                }
                else if (rdRight.Checked)
                {
                    ct.SetSimpleColumn(fieldPosition.Left, fieldPosition.Bottom - fieldPosition.Height / 2,
                                       fieldPosition.Right, fieldPosition.Top - fieldPosition.Height / 2, 0, Element.ALIGN_RIGHT);
                }
                if (rdLeft.Checked)
                {
                    ct.SetSimpleColumn(fieldPosition.Left, fieldPosition.Bottom - fieldPosition.Height / 2,
                                       fieldPosition.Right, fieldPosition.Top - fieldPosition.Height / 2, 0, Element.ALIGN_LEFT);
                }
                if (rdUseFieldAlignment.Checked)
                {
                    ct.SetSimpleColumn(fieldPosition.Left, fieldPosition.Bottom - fieldPosition.Height / 2,
                                       fieldPosition.Right, fieldPosition.Top - fieldPosition.Height / 2, 0, Element.ALIGN_LEFT);
                }

                ct.SetText(new Phrase(fieldValue, f));
                ct.Go();

                //uncomment to draw rectangle
                //var rect = new iTextSharp.text.Rectangle(fieldPosition.Left, fieldPosition.Bottom - fieldPosition.Height / 2, fieldPosition.Right, fieldPosition.Top - fieldPosition.Height / 2);
                //rect.Border = iTextSharp.text.Rectangle.LEFT_BORDER | iTextSharp.text.Rectangle.RIGHT_BORDER;
                //rect.BorderWidth = 5;
                //rect.BorderColor = new BaseColor(0, 0, 0);

                //overContent.Rectangle(rect);
                _pdfStamper.Close();
                Process.Start(outfileName);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
Exemple #13
0
        //科大讯飞
        private void btnKeda_Click(object sender, RoutedEventArgs e)
        {
            string url    = "http://api.xfyun.cn/v1/service/v1/tts";
            string appId  = "5b3c9b38";
            string apiKey = "6d3122d48c1b5309eb60eda4fb7f354b";

            Parameter parameter = new Parameter();
            //parameter.speed = ((int)sldSpeed.Value * 10) + "";
            //parameter.volume = ((int)sldVol.Value * 10) + "";

            var json_str   = JsonConvert.SerializeObject(parameter);
            var base64_str = Convert.ToBase64String(Encoding.UTF8.GetBytes(json_str));

            HttpWebRequest  httpwebrequest  = null;
            HttpWebResponse httpwebresponse = null;

            httpwebrequest        = (HttpWebRequest)WebRequest.Create(url);
            httpwebrequest.Method = "POST";

            String t_s_1970 = TimestampSince1970;
            String checksum = Helpers.GetMD5(apiKey + t_s_1970 + base64_str);//准备好一个checksum备用

            httpwebrequest.Headers.Clear();
            httpwebrequest.Headers.Add("X-Param", base64_str);
            httpwebrequest.Headers.Add("X-CurTime", t_s_1970);
            httpwebrequest.Headers.Add("X-Appid", appId);
            httpwebrequest.Headers.Add("X-CheckSum", checksum);
            httpwebrequest.Headers.Add("X-Real-Ip", "127.0.0.1");
            httpwebrequest.ContentType = "application/x-www-form-urlencoded";
            httpwebrequest.Headers.Add("charset", "utf-8");

            using (Stream stream = httpwebrequest.GetRequestStream())
            {
                byte[] data = Encoding.UTF8.GetBytes($"text={txtMsg.Text}");//更改生成内容时,text= 要保留
                stream.Write(data, 0, data.Length);
            }
            httpwebresponse = (HttpWebResponse)httpwebrequest.GetResponse();
            Stream res_strem = httpwebresponse.GetResponseStream();

            if (httpwebresponse.ContentType == "text/plain")//ContentType等于"text/plain"即表示生成失败,等于"audio/mpeg"即生成成功
            {
                using (StreamReader s_reader = new StreamReader(res_strem, Encoding.UTF8))
                {
                    String a = s_reader.ReadToEnd();
                    MessageBox.Show($"生成失败:{a}");
                }
            }
            else
            {
                var outputDic = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Output");
                if (!Directory.Exists(outputDic))
                {
                    Directory.CreateDirectory(outputDic);
                }
                var path = System.IO.Path.Combine(outputDic, $"{txtMsg.Text}科大讯飞{DateTime.Now:yyyyMMddHHmmssffff}.mp3");
                using (StreamWriter sw = new StreamWriter(path))
                {
                    res_strem.CopyTo(sw.BaseStream);
                    sw.Flush();
                    sw.Close();
                    res_strem.Dispose();
                }
                if (chkOpenDir.IsChecked == true)
                {
                    OpenDir();
                }
                else
                {
                    MessageBox.Show("生成成功");
                }
            }
        }
 private string GetDataPath(DateTime date)
 {
     return(IOPath.Combine(_path, GetDirName(date)));
 }
Exemple #15
0
    public void IsSymlink_WithMissingFile_ReturnsFalse()
    {
        var path = new PosixPath(Path.Combine(_fixture.TempFolder, "does-not-exist"));

        Assert.False(path.IsSymlink());
    }
        private async Task LoadFile(string fileName)
        {
            string fileExt = IoPath.GetExtension(fileName);

            if (string.IsNullOrWhiteSpace(fileExt))
            {
                return;
            }

            bool generateXaml = _optionSettings.ShowOutputFile;

            if (string.Equals(fileExt, SvgConverter.SvgExt, StringComparison.OrdinalIgnoreCase) ||
                string.Equals(fileExt, SvgConverter.CompressedSvgExt, StringComparison.OrdinalIgnoreCase))
            {
                _svgFilePath = fileName;

                if (_svgPage != null && _optionSettings.ShowInputFile)
                {
                    _svgPage.LoadDocument(fileName);
                }

                if (_drawingPage == null)
                {
                    return;
                }
                _drawingPage.SaveXaml = generateXaml;

                try
                {
                    if (await _drawingPage.LoadDocumentAsync(fileName))
                    {
                        this.Title = AppTitle + " - " + IoPath.GetFileName(fileName);

                        if (_xamlPage != null && !string.IsNullOrWhiteSpace(_drawingDir))
                        {
                            string xamlFilePath = IoPath.Combine(_drawingDir,
                                                                 IoPath.GetFileNameWithoutExtension(fileName) + SvgConverter.XamlExt);

                            _xamlFilePath  = xamlFilePath;
                            _canDeleteXaml = true;

                            if (File.Exists(xamlFilePath) && _optionSettings.ShowOutputFile)
                            {
                                _xamlPage.LoadDocument(xamlFilePath);
                            }
                        }

                        _fileWatcher.Path = IoPath.GetDirectoryName(fileName);
                        // Only watch current file
                        _fileWatcher.Filter = IoPath.GetFileName(fileName);
                        // Begin watching.
                        _fileWatcher.EnableRaisingEvents = true;
                    }
                }
                catch
                {
                    // Try loading the XAML, if generated but the rendering failed...
                    if (_xamlPage != null && !string.IsNullOrWhiteSpace(_drawingDir))
                    {
                        string xamlFilePath = IoPath.Combine(_drawingDir,
                                                             IoPath.GetFileNameWithoutExtension(fileName) + SvgConverter.XamlExt);

                        _xamlFilePath  = xamlFilePath;
                        _canDeleteXaml = true;

                        if (File.Exists(xamlFilePath) && _optionSettings.ShowOutputFile)
                        {
                            _xamlPage.LoadDocument(xamlFilePath);
                        }
                    }
                    throw;
                }
            }
        }
Exemple #17
0
        public static List <Equip> LoadEquipData(string chosenPath, string category)
        {
            List <Equip> equips        = new List <Equip>();
            WzFile       characterFile = new WzFile(PathIO.Combine(chosenPath, "Character.wz"), WzMapleVersion.CLASSIC);
            WzFile       stringFile    = new WzFile(PathIO.Combine(chosenPath, "String.wz"), WzMapleVersion.CLASSIC);
            CharacterWz  character     = new CharacterWz(characterFile, category);
            StringWz     stringM       = new StringWz(stringFile, false);
            int          loopNumber    = character.GetEquipQuantity();

            for (int i = 0; i < loopNumber; i++)
            {
                int    equipID             = character.GetEquipID(i);
                string equipName           = stringM.GetEquipName(equipID, category);
                string equipClassification = character.GetEquipClassification();
                Bitmap equipImage          = character.GetEquipImage(characterFile);
                int    hasEquipImage       = 1;
                if (equipImage.Height <= 1)
                {
                    hasEquipImage = 0;
                }
                if (equipClassification == "Cash")
                {
                    equips.Add(new Equip()
                    {
                        /* Missing Int Properties don't make the program crash, like Level.
                         * But I'll put it anyway for organization sake.
                         */
                        EquipID             = equipID,
                        EquipName           = equipName,
                        EquipImage          = equipImage,
                        HasEquipImage       = hasEquipImage,
                        EquipLevel          = 0,
                        EquipClassification = equipClassification,
                        EquipType           = "",
                        RequiredStats       = "",
                        RequiredJob         = "",
                        TotalUpgradeCount   = 0,
                        EquipStats          = "",
                    });
                    continue;
                }

                equips.Add(new Equip()
                {
                    EquipID             = equipID,
                    EquipName           = equipName,
                    EquipImage          = equipImage,
                    HasEquipImage       = hasEquipImage,
                    EquipLevel          = character.GetEquipLevel(),
                    EquipClassification = equipClassification,
                    EquipType           = character.GetEquipType(equipID),
                    RequiredStats       = character.GetRequiredStats(),
                    RequiredJob         = character.GetRequiredJob(equipID),
                    TotalUpgradeCount   = character.GetTotalUpgradeCount(),
                    EquipStats          = character.GetEquipStats(),
                });
            }
            characterFile.Dispose();
            stringFile.Dispose();

            return(equips);
        }
Exemple #18
0
        private static void AotCompileAssembly(string platform, bool isDebug, Dictionary <string, string> data, string assemblyPath, string outputFilePath)
        {
            // Make sure the output directory exists
            Directory.CreateDirectory(outputFilePath.GetBaseDir());

            string exeExt = OS.IsWindows ? ".exe" : string.Empty;

            string monoCrossDirName = DetermineMonoCrossDirName(platform, data);
            string monoCrossRoot    = Path.Combine(GodotSharpDirs.DataEditorToolsDir, "aot-compilers", monoCrossDirName);
            string monoCrossBin     = Path.Combine(monoCrossRoot, "bin");

            string toolPrefix  = DetermineToolPrefix(monoCrossBin);
            string monoExeName = System.IO.File.Exists(Path.Combine(monoCrossBin, $"{toolPrefix}mono{exeExt}")) ? "mono" : "mono-sgen";

            string compilerCommand = Path.Combine(monoCrossBin, $"{toolPrefix}{monoExeName}{exeExt}");

            bool fullAot = (bool)ProjectSettings.GetSetting("mono/export/aot/full_aot");

            string EscapeOption(string option) => option.Contains(',') ? $"\"{option}\"" : option;
            string OptionsToString(IEnumerable <string> options) => string.Join(",", options.Select(EscapeOption));

            var aotOptions       = new List <string>();
            var optimizerOptions = new List <string>();

            if (fullAot)
            {
                aotOptions.Add("full");
            }

            aotOptions.Add(isDebug ? "soft-debug" : "nodebug");

            if (platform == OS.Platforms.Android)
            {
                string abi = data["abi"];

                string androidToolchain = (string)ProjectSettings.GetSetting("mono/export/aot/android_toolchain_path");

                if (string.IsNullOrEmpty(androidToolchain))
                {
                    androidToolchain = Path.Combine(GodotSharpDirs.DataEditorToolsDir, "android-toolchains", $"{abi}"); // TODO: $"{abi}-{apiLevel}{(clang?"clang":"")}"

                    if (!Directory.Exists(androidToolchain))
                    {
                        throw new FileNotFoundException("Missing android toolchain. Specify one in the AOT export settings.");
                    }
                }
                else if (!Directory.Exists(androidToolchain))
                {
                    throw new FileNotFoundException("Android toolchain not found: " + androidToolchain);
                }

                var androidToolPrefixes = new Dictionary <string, string>
                {
                    ["armeabi-v7a"] = "arm-linux-androideabi-",
                    ["arm64-v8a"]   = "aarch64-linux-android-",
                    ["x86"]         = "i686-linux-android-",
                    ["x86_64"]      = "x86_64-linux-android-"
                };

                aotOptions.Add("tool-prefix=" + Path.Combine(androidToolchain, "bin", androidToolPrefixes[abi]));

                string triple = GetAndroidTriple(abi);
                aotOptions.Add($"mtriple={triple}");
            }

            aotOptions.Add($"outfile={outputFilePath}");

            var extraAotOptions       = (string[])ProjectSettings.GetSetting("mono/export/aot/extra_aot_options");
            var extraOptimizerOptions = (string[])ProjectSettings.GetSetting("mono/export/aot/extra_optimizer_options");

            if (extraAotOptions.Length > 0)
            {
                aotOptions.AddRange(extraAotOptions);
            }

            if (extraOptimizerOptions.Length > 0)
            {
                optimizerOptions.AddRange(extraOptimizerOptions);
            }

            var compilerArgs = new List <string>();

            if (isDebug)
            {
                compilerArgs.Add("--debug"); // Required for --aot=soft-debug
            }
            compilerArgs.Add(aotOptions.Count > 0 ? $"--aot={OptionsToString(aotOptions)}" : "--aot");

            if (optimizerOptions.Count > 0)
            {
                compilerArgs.Add($"-O={OptionsToString(optimizerOptions)}");
            }

            compilerArgs.Add(ProjectSettings.GlobalizePath(assemblyPath));

            // TODO: Once we move to .NET Standard 2.1 we can use ProcessStartInfo.ArgumentList instead
            string CmdLineArgsToString(IEnumerable <string> args)
            {
                // Not perfect, but as long as we are careful...
                return(string.Join(" ", args.Select(arg => arg.Contains(" ") ? $@"""{arg}""" : arg)));
            }

            using (var process = new Process())
            {
                process.StartInfo = new ProcessStartInfo(compilerCommand, CmdLineArgsToString(compilerArgs))
                {
                    UseShellExecute = false
                };

                string platformBclDir = DeterminePlatformBclDir(platform);
                process.StartInfo.EnvironmentVariables.Add("MONO_PATH", string.IsNullOrEmpty(platformBclDir) ?
                                                           typeof(object).Assembly.Location.GetBaseDir() :
                                                           platformBclDir);

                Console.WriteLine($"Running: \"{process.StartInfo.FileName}\" {process.StartInfo.Arguments}");

                if (!process.Start())
                {
                    throw new Exception("Failed to start process for Mono AOT compiler");
                }

                process.WaitForExit();

                if (process.ExitCode != 0)
                {
                    throw new Exception($"Mono AOT compiler exited with error code: {process.ExitCode}");
                }

                if (!System.IO.File.Exists(outputFilePath))
                {
                    throw new Exception("Mono AOT compiler finished successfully but the output file is missing");
                }
            }
        }
Exemple #19
0
        /// <summary>
        /// Gets all the info to be shown by DataGrid
        /// </summary>
        /// <param name="chosenPath"></param>
        /// <returns></returns>
        public static List <Familiar> LoadCollectionData(string chosenPath)
        {
            List <Familiar> familiars     = new List <Familiar>();
            WzFile          characterFile = new WzFile(PathIO.Combine(chosenPath, "Character.wz"), WzMapleVersion.CLASSIC);
            WzFile          etcFile       = new WzFile(PathIO.Combine(chosenPath, "Etc.wz"), WzMapleVersion.CLASSIC);
            WzFile          stringFile    = new WzFile(PathIO.Combine(chosenPath, "String.wz"), WzMapleVersion.CLASSIC);
            WzFile          uiFile        = new WzFile(PathIO.Combine(chosenPath, "UI.wz"), WzMapleVersion.CLASSIC);
            WzFile          mobFile       = new WzFile(PathIO.Combine(chosenPath, "Mob.wz"), WzMapleVersion.CLASSIC);
            WzFile          mob2File      = new WzFile(PathIO.Combine(chosenPath, "Mob2.wz"), WzMapleVersion.CLASSIC);
            WzFile          skill001File  = new WzFile(PathIO.Combine(chosenPath, "Skill001.wz"), WzMapleVersion.CLASSIC);
            WzFile          itemFile      = new WzFile(PathIO.Combine(chosenPath, "Item.wz"), WzMapleVersion.CLASSIC);
            CharacterWz     character     = new CharacterWz(characterFile);
            EtcWz           etc           = new EtcWz(etcFile);
            StringWz        stringM       = new StringWz(stringFile, true);
            UIWz            ui            = new UIWz(uiFile);
            MobWz           mob           = new MobWz(mobFile);
            MobWz           mob2          = new MobWz(mob2File);
            Skill001Wz      skill001      = new Skill001Wz(skill001File);
            ItemWz          item          = new ItemWz(itemFile);
            int             loopNumber    = character.GetFamiliarQuantity();

            for (int i = 0; i < loopNumber; i++)
            {
                int familiarID = character.GetFamiliarID(i);
                character.SetFamiliarImage(familiarID);
                int mobID = etc.GetMobID(familiarID);
                if (mobID == -1)
                {
                    mobID = character.GetMobID();
                }
                mob.SetMobImage(mobID, mobFile);
                mob2.SetMobImage(mobID, mob2File);
                MobWz realMob;
                if (mob.MobImage != null)
                {
                    realMob = mob;
                }
                else
                {
                    realMob = mob2;
                }
                int skillID         = character.GetSkillID();
                int passiveEffectID = etc.GetPassiveEffectID(familiarID);
                int cardID          = etc.GetCardID(familiarID);
                if (cardID == -1)
                {
                    cardID = character.GetCardID();
                }
                int level = character.GetLevel(); // DON'T CHANGE THE ORDER, OR IT'LL BE MESSED UP
                if (level == 0)
                {
                    level = realMob.GetLevel();
                }
                int att = character.GetATT(); // SAME AS LEVEL, DON'T CHANGE ORDER
                if (att == 0)
                {
                    att = realMob.GetATT();
                }
                Bitmap mobImage = realMob.GetMobImage();
                //BitmapSource finalCardImage = CreateBitmapSourceFromGdiBitmap(item.GetCardImage(cardID));
                //BitmapSource finalMobImage = CreateBitmapSourceFromGdiBitmap(mobImage);
                Bitmap finalCardImage = item.GetCardImage(cardID);
                Bitmap finalMobImage  = mobImage;
                int    hasCardImage   = 1;
                int    hasMobImage    = 1;
                if (finalCardImage == null || finalCardImage.Height <= 1)
                {
                    hasCardImage = 0;
                }
                if (finalMobImage == null)
                {
                    hasMobImage = 0;
                }

                familiars.Add(new Familiar()
                {
                    FamiliarID       = familiarID,
                    MobID            = mobID,
                    MobName          = stringM.GetMobName(mobID),
                    SkillID          = skillID,
                    SkillName        = stringM.GetSkillName(skillID),
                    SkillDescription = stringM.GetSkillDesc(skillID),
                    PassiveEffectID  = passiveEffectID,
                    PassiveEffect    = stringM.GetPassiveEffect(passiveEffectID),
                    Range            = character.GetRange(),
                    Rarity           = item.GetRarity(cardID),
                    CardID           = cardID,
                    CardName         = stringM.GetCardName(cardID),
                    SkillCategory    = skill001.GetSkillCategory(skillID),
                    Level            = level,
                    ATT = att,
                    PassiveEffectTarget = item.GetPassiveEffectTarget(passiveEffectID),
                    PassiveEffectBonus  = item.GetPassiveEffectBonus(passiveEffectID),
                    CardImage           = finalCardImage,
                    MobImage            = finalMobImage,
                    HasCardImage        = hasCardImage,
                    HasMobImage         = hasMobImage,
                });
            }
            characterFile.Dispose();
            etcFile.Dispose();
            stringFile.Dispose();
            uiFile.Dispose();
            mobFile.Dispose();
            mob2File.Dispose();
            skill001File.Dispose();
            itemFile.Dispose();

            return(familiars);
        }
        private void Recolor()
        {
            String suboutdir = Path.Combine(outdir, "recolored");

            Directory.CreateDirectory(suboutdir);

            //read in the patterns and save out their layers
            List <PatternItem> patterns = PatternIO.GetPatterns(imagedir);

            foreach (PatternItem p in patterns)
            {
                String basename = p.Name;

                if (!palettes.ContainsKey(basename))
                {
                    continue;
                }

                PaletteData palette = palettes[basename];


                //Read the recoloring description if available
                String specs = Path.Combine(outdir, "specs", p.Directory, Util.ConvertFileName(basename, "", ".txt"));

                if (!File.Exists(specs))
                {
                    continue;
                }



                Bitmap image = new Bitmap(p.FullPath);


                //TODO: save and reload color templates functionality
                ColorTemplate template = new ColorTemplate(image, palette);

                PaletteData data = new PaletteData();

                String[] lines       = File.ReadAllLines(specs);
                int[]    slotToColor = new int[template.NumSlots()];
                Dictionary <int, int> groupToSlot = new Dictionary <int, int>();

                int ngroups = 0;
                for (int i = 0; i < slotToColor.Count(); i++)
                {
                    slotToColor[i] = i;
                    if (template.PixelsInSlot(i) > 0)
                    {
                        groupToSlot.Add(ngroups++, i);
                    }
                }


                //TODO: handle recoloring when # groups is less than number of original slots, because of quantization issues.
                //Right now, this is rather ugly..

                data.colors = new List <Color>();
                data.lab    = new List <CIELAB>();
                for (int i = 0; i < slotToColor.Count(); i++)
                {
                    data.colors.Add(new Color());
                    data.lab.Add(new CIELAB());
                }

                int groupid = 0;
                foreach (String line in lines)
                {
                    //rgb floats
                    int[] fields = line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select <String, int>(s => ((int)(Math.Round(double.Parse(s) * 255)))).ToArray <int>();
                    Color color  = Color.FromArgb(fields[0], fields[1], fields[2]);
                    data.colors[groupToSlot[groupid]] = color;
                    data.lab[groupToSlot[groupid]]    = Util.RGBtoLAB(color);
                    groupid++;
                }

                Bitmap orig = (renderFinal)? image : template.DebugQuantization();
                PatternIO.SavePattern(orig, p, suboutdir, "_original");
                orig.Dispose();

                Bitmap result = (renderFinal)? GetFinalRendering(Util.ConvertFileName(basename, "", ""), data): template.SolidColor(data, slotToColor);
                //sometimes we can't get the nice image, so render the quantized image in this case. TODO: or maybe skip rendering this visualization at all
                if (result == null)
                {
                    result = template.SolidColor(data, slotToColor);
                }
                PatternIO.SavePattern(result, p, suboutdir, "_recolored");
                result.Dispose();
            }
        }
 /// <summary>
 /// Gets the full qualified path to the file.
 /// </summary>
 /// <param name="file">The file path.</param>
 /// <returns>
 /// The <see cref="string"/>.
 /// </returns>
 public static string GetPath(string file) => IOPath.Combine(FontsDirectory, file);
        //render an image of the original pattern, plus columns of patterns generated by different models (trained on diff styles)
        private void VisAllStyles()
        {
            Directory.CreateDirectory(outdir + "\\stylecolor\\");

            Directory.CreateDirectory(outdir + "\\styles\\");

            //read in the patterns and save out their layers
            List <PatternItem> patterns = PatternIO.GetPatterns(Path.Combine(imagedir, "../styles"));

            foreach (PatternItem p in patterns)
            {
                String basename = p.Name;

                //Read the style description if available
                String specs = Path.Combine(outdir, "styles", p.Directory, Util.ConvertFileName(basename, "", ".txt"));
                if (!File.Exists(specs))
                {
                    continue;
                }

                Bitmap image = new Bitmap(p.FullPath);

                if (!palettes.ContainsKey(basename))
                {
                    continue;
                }

                PaletteData palette = palettes[basename];

                ColorTemplate template = new ColorTemplate(image, palette);

                int[] slotToColor = new int[template.NumSlots()];
                for (int i = 0; i < slotToColor.Count(); i++)
                {
                    slotToColor[i] = i;
                }

                List <List <String> > lines = File.ReadAllLines(specs).Select(line => line.Split(',').ToList <String>()).ToList <List <String> >();
                if (lines.Count() == 0)
                {
                    continue;
                }

                Dictionary <String, int> styleToRowIdx = new Dictionary <String, int>();
                String origStyle = "";

                foreach (List <String> line in lines)
                {
                    origStyle = line[0];
                    if (!styleToRowIdx.ContainsKey(line[1]))
                    {
                        styleToRowIdx.Add(line[1], 0);
                    }
                }


                //read the score and if it's the original or not
                double score       = 0;
                int    iwidth      = 100;
                int    iheight     = 100;
                int    padding     = 15;
                int    headerSpace = 30;
                int    width       = (styleToRowIdx.Keys.Count() + 1) * iwidth;
                int    height      = (lines.Count() / styleToRowIdx.Keys.Count()) * iheight + headerSpace;

                Font font = new Font("Arial", 10);

                Bitmap   vis = new Bitmap(width, height);
                Graphics g   = Graphics.FromImage(vis);

                //write out the headings, highlight the original style heading
                var   headers     = styleToRowIdx.Keys.ToList <String>();
                int   ncol        = headers.Count() + 1;
                Color headerColor = Color.Black;
                g.DrawString("original", font, new SolidBrush(headerColor), 0, 0);
                for (int i = 0; i < headers.Count(); i++)
                {
                    if (headers[i] == origStyle)
                    {
                        g.DrawString(headers[i], font, new SolidBrush(headerColor), (i + 1) * iwidth, 0);
                    }
                    else
                    {
                        g.DrawString(headers[i], font, new SolidBrush(headerColor), (i + 1) * iwidth, 0);
                    }
                }

                //draw the original
                Bitmap original = (renderFinal)? image: template.DebugQuantization();
                g.DrawImage(original, 0, headerSpace, iwidth - padding, iheight - padding);
                original.Dispose();

                PaletteData           data        = new PaletteData();
                Dictionary <int, int> groupToSlot = new Dictionary <int, int>();
                int ngroups = 0;
                for (int i = 0; i < slotToColor.Count(); i++)
                {
                    slotToColor[i] = i;
                    data.colors.Add(new Color());
                    data.lab.Add(new CIELAB());

                    if (template.PixelsInSlot(i) > 0)
                    {
                        groupToSlot.Add(ngroups++, i);
                    }
                }


                foreach (List <String> line in lines)
                {
                    //draw the colorized thumbnail in the right location
                    String style = line[1];

                    String[] colors = line[2].Split('^');

                    int colorIdx = 0;
                    foreach (String color in colors)
                    {
                        //rgb floats
                        int[] fields = color.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select <String, int>(s => ((int)(Math.Round(double.Parse(s) * 255)))).ToArray <int>();
                        Color c      = Color.FromArgb(fields[0], fields[1], fields[2]);
                        data.colors[groupToSlot[colorIdx]] = c;
                        data.lab[groupToSlot[colorIdx]]    = Util.RGBtoLAB(c);
                        colorIdx++;
                    }

                    int x = (headers.IndexOf(style) + 1) * iwidth;
                    int y = styleToRowIdx[style] * iheight + headerSpace;
                    styleToRowIdx[style]++;

                    Bitmap result = (renderFinal)?GetFinalRendering(Util.ConvertFileName(basename, "", ""), data):template.SolidColor(data, slotToColor);
                    //sometimes we can't get the nice image, so render the quantized image in this case
                    if (result == null)
                    {
                        result = template.SolidColor(data, slotToColor);
                    }
                    g.DrawImage(result, x, y, iwidth - padding, iheight - padding);
                    result.Dispose();
                }


                PatternIO.SavePattern(vis, p, Path.Combine(outdir, "stylecolor"));
                vis.Dispose();
            }
        }
Exemple #23
0
        /// <summary>
        /// Photoes the captured.
        /// </summary>
        /// <param name="o">The o.</param>
        private void PhotoCaptured(object o)
        {
            PhotoCapturedEventArgs eventArgs = o as PhotoCapturedEventArgs;

            if (eventArgs == null)
            {
                return;
            }
            try
            {
                Log.Debug("Photo transfer begin.");
                eventArgs.CameraDevice.IsBusy = true;
                CameraProperty property = eventArgs.CameraDevice.LoadProperties();
                PhotoSession   session  = (PhotoSession)eventArgs.CameraDevice.AttachedPhotoSession ??
                                          ServiceProvider.Settings.DefaultSession;
                StaticHelper.Instance.SystemMessage = "";

                var extension = Path.GetExtension(eventArgs.FileName);

                if (!eventArgs.CameraDevice.CaptureInSdRam || (extension != null && extension.ToLower() == ".mov"))
                {
                    if (property.NoDownload)
                    {
                        eventArgs.CameraDevice.IsBusy = false;
                        return;
                    }
                    if (extension != null && (session.DownloadOnlyJpg && extension.ToLower() != ".jpg"))
                    {
                        eventArgs.CameraDevice.IsBusy = false;
                        return;
                    }
                }

                StaticHelper.Instance.SystemMessage = TranslationStrings.MsgPhotoTransferBegin;

                string tempFile = Path.GetTempFileName();

                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }

                if (!eventArgs.CameraDevice.CaptureInSdRam && session.DownloadThumbOnly)
                {
                    eventArgs.CameraDevice.TransferFileThumb(eventArgs.Handle, tempFile);
                }
                else
                {
                    eventArgs.CameraDevice.TransferFile(eventArgs.Handle, tempFile);
                }

                string fileName = "";
                if (!session.UseOriginalFilename || eventArgs.CameraDevice.CaptureInSdRam)
                {
                    fileName =
                        session.GetNextFileName(eventArgs.FileName, eventArgs.CameraDevice);
                }
                else
                {
                    fileName = Path.Combine(session.Folder, eventArgs.FileName);
                    if (File.Exists(fileName) && !session.AllowOverWrite)
                    {
                        fileName =
                            StaticHelper.GetUniqueFilename(
                                Path.GetDirectoryName(fileName) + "\\" + Path.GetFileNameWithoutExtension(fileName) +
                                "_", 0,
                                Path.GetExtension(fileName));
                    }
                }

                if (session.AllowOverWrite && File.Exists(fileName))
                {
                    PhotoUtils.WaitForFile(fileName);
                    File.Delete(fileName);
                }

                // make lower case extension
                if (session.LowerCaseExtension && !string.IsNullOrEmpty(Path.GetExtension(fileName)))
                {
                    fileName = Path.Combine(Path.GetDirectoryName(fileName),
                                            Path.GetFileNameWithoutExtension(fileName) + Path.GetExtension(fileName).ToLower());
                }


                if (session.AskSavePath)
                {
                    SaveFileDialog dialog = new SaveFileDialog();
                    dialog.Filter           = "All files|*.*";
                    dialog.Title            = "Save captured photo";
                    dialog.FileName         = fileName;
                    dialog.InitialDirectory = Path.GetDirectoryName(fileName);
                    if (dialog.ShowDialog() == true)
                    {
                        fileName = dialog.FileName;
                    }
                    else
                    {
                        eventArgs.CameraDevice.IsBusy = false;
                        if (File.Exists(tempFile))
                        {
                            File.Delete(tempFile);
                        }
                        return;
                    }
                }

                if (!Directory.Exists(Path.GetDirectoryName(fileName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                }

                File.Copy(tempFile, fileName);

                string backupfile = null;
                if (session.BackUp)
                {
                    backupfile = session.CopyBackUp(tempFile, fileName);
                    if (string.IsNullOrEmpty(backupfile))
                    {
                        StaticHelper.Instance.SystemMessage = "Unable to save the backup";
                    }
                }

                if (!eventArgs.CameraDevice.CaptureInSdRam && session.DeleteFileAfterTransfer)
                {
                    eventArgs.CameraDevice.DeleteObject(new DeviceObject()
                    {
                        Handle = eventArgs.Handle
                    });
                }


                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }

                if (session.WriteComment)
                {
                    if (!string.IsNullOrEmpty(session.Comment))
                    {
                        Exiv2Helper.SaveComment(fileName, session.Comment);
                    }
                    if (session.SelectedTag1 != null && !string.IsNullOrEmpty(session.SelectedTag1.Value))
                    {
                        Exiv2Helper.AddKeyword(fileName, session.SelectedTag1.Value);
                    }
                    if (session.SelectedTag2 != null && !string.IsNullOrEmpty(session.SelectedTag2.Value))
                    {
                        Exiv2Helper.AddKeyword(fileName, session.SelectedTag2.Value);
                    }
                    if (session.SelectedTag3 != null && !string.IsNullOrEmpty(session.SelectedTag3.Value))
                    {
                        Exiv2Helper.AddKeyword(fileName, session.SelectedTag3.Value);
                    }
                    if (session.SelectedTag4 != null && !string.IsNullOrEmpty(session.SelectedTag4.Value))
                    {
                        Exiv2Helper.AddKeyword(fileName, session.SelectedTag4.Value);
                    }
                }

                if (session.ExternalData != null)
                {
                    session.ExternalData.FileName = fileName;
                }

                // prevent crash og GUI when item count updated
                Dispatcher.Invoke(new Action(delegate
                {
                    try
                    {
                        _selectedItem = session.GetNewFileItem(fileName);
                        _selectedItem.BackupFileName = backupfile;
                        _selectedItem.Series         = session.Series;
                        _selectedItem.AddTemplates(eventArgs.CameraDevice, session);
                        ServiceProvider.Database.Add(new DbFile(_selectedItem, eventArgs.CameraDevice.DisplayName,
                                                                eventArgs.CameraDevice.SerialNumber, session.Name));
                    }
                    catch (Exception ex)
                    {
                    }
                }));

                foreach (AutoExportPluginConfig plugin in ServiceProvider.Settings.DefaultSession.AutoExportPluginConfigs)
                {
                    if (!plugin.IsEnabled)
                    {
                        continue;
                    }
                    var pl = ServiceProvider.PluginManager.GetAutoExportPlugin(plugin.Type);
                    try
                    {
                        pl.Execute(_selectedItem, plugin);
                        ServiceProvider.Analytics.PluginExecute(plugin.Type);
                        Log.Debug("AutoexportPlugin executed " + plugin.Type);
                    }
                    catch (Exception ex)
                    {
                        plugin.IsError = true;
                        plugin.Error   = ex.Message;
                        plugin.IsRedy  = true;
                        Log.Error("Error to apply plugin", ex);
                    }
                }

                Dispatcher.Invoke(() =>
                {
                    _selectedItem.RemoveThumbs();
                    session.Add(_selectedItem);
                    ServiceProvider.OnFileTransfered(_selectedItem);
                });

                if (ServiceProvider.Settings.MinimizeToTrayIcon && !IsVisible && !ServiceProvider.Settings.HideTrayNotifications)
                {
                    MyNotifyIcon.HideBalloonTip();
                    MyNotifyIcon.ShowBalloonTip("Photo transfered", fileName, BalloonIcon.Info);
                }

                ServiceProvider.DeviceManager.LastCapturedImage[eventArgs.CameraDevice] = fileName;

                //select the new file only when the multiple camera support isn't used to prevent high CPU usage on raw files
                if (ServiceProvider.Settings.AutoPreview &&
                    !ServiceProvider.WindowsManager.Get(typeof(MultipleCameraWnd)).IsVisible&&
                    !ServiceProvider.Settings.UseExternalViewer)
                {
                    if ((Path.GetExtension(fileName).ToLower() == ".jpg" && ServiceProvider.Settings.AutoPreviewJpgOnly) ||
                        !ServiceProvider.Settings.AutoPreviewJpgOnly)
                    {
                        if ((DateTime.Now - _lastLoadTime).TotalSeconds < 4)
                        {
                            _selectiontimer.Stop();
                            _selectiontimer.Start();
                        }
                        else
                        {
                            ServiceProvider.WindowsManager.ExecuteCommand(WindowsCmdConsts.Select_Image, _selectedItem);
                        }
                    }
                }
                _lastLoadTime = DateTime.Now;
                //ServiceProvider.Settings.Save(session);
                StaticHelper.Instance.SystemMessage = TranslationStrings.MsgPhotoTransferDone;
                eventArgs.CameraDevice.IsBusy       = false;
                //show fullscreen only when the multiple camera support isn't used
                if (ServiceProvider.Settings.Preview &&
                    !ServiceProvider.WindowsManager.Get(typeof(MultipleCameraWnd)).IsVisible&&
                    !ServiceProvider.Settings.UseExternalViewer)
                {
                    ServiceProvider.WindowsManager.ExecuteCommand(WindowsCmdConsts.FullScreenWnd_ShowTimed);
                }
                if (ServiceProvider.Settings.UseExternalViewer &&
                    File.Exists(ServiceProvider.Settings.ExternalViewerPath))
                {
                    string arg = ServiceProvider.Settings.ExternalViewerArgs;
                    arg = arg.Contains("%1") ? arg.Replace("%1", fileName) : arg + " " + fileName;
                    PhotoUtils.Run(ServiceProvider.Settings.ExternalViewerPath, arg, ProcessWindowStyle.Normal);
                }
                if (ServiceProvider.Settings.PlaySound)
                {
                    PhotoUtils.PlayCaptureSound();
                }
                Log.Debug("Photo transfer done.");
            }
            catch (Exception ex)
            {
                eventArgs.CameraDevice.IsBusy       = false;
                StaticHelper.Instance.SystemMessage = TranslationStrings.MsgPhotoTransferError + " " + ex.Message;
                Log.Error("Transfer error !", ex);
            }
            // not indicated to be used
            GC.Collect();
            //GC.WaitForPendingFinalizers();
        }
Exemple #24
0
        private void DeployCdw800()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            if (!string.IsNullOrEmpty(ProductAppDataPath))
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();

                string markerFile   = Path.Combine(ProductAppDataPath, "ChemDoodle-Web-800.txt");
                string otherVersion = Path.Combine(ProductAppDataPath, "ChemDoodle-Web-702.txt");
                string refreshFile  = Path.Combine(ProductAppDataPath, "ChemDoodle-Web-Refresh.txt");

                if (File.Exists(otherVersion))
                {
                    Telemetry.Write(module, "Information", "Deleting CDW 702 resources from disk");

                    File.Delete(otherVersion);

                    DelTree(Path.Combine(ProductAppDataPath, "ChemDoodleWeb"));
                }

                if (File.Exists(refreshFile))
                {
                    Telemetry.Write(module, "Information", "Refreshing CDW 800 resources");

                    File.Delete(refreshFile);
                    if (File.Exists(markerFile))
                    {
                        File.Delete(markerFile);
                    }

                    DelTree(Path.Combine(ProductAppDataPath, "ChemDoodleWeb"));
                }

                if (!File.Exists(markerFile))
                {
                    Telemetry.Write(module, "Information", "Writing CDW 800 resources to disk");

                    File.WriteAllText(markerFile, "Delete this file to refresh ChemDoodle Web");

                    Stream stream = ResourceHelper.GetBinaryResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.ChemDoodleWeb_800.zip");

                    // NB: Top level of zip file must be the folder ChemDoodleWeb
                    using (ZipFile zip = ZipFile.Read(stream))
                    {
                        zip.ExtractAll(ProductAppDataPath, ExtractExistingFileAction.OverwriteSilently);
                    }

                    string cssfile = ResourceHelper.GetStringResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.Chem4Word.css");
                    File.WriteAllText(Path.Combine(ProductAppDataPath, "Chem4Word.css"), cssfile);

                    string jsfile = ResourceHelper.GetStringResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.Chem4Word.js");
                    File.WriteAllText(Path.Combine(ProductAppDataPath, "Chem4Word.js"), jsfile);
                }

                sw.Stop();

                Telemetry.Write(module, "Timing", $"Writing resources to disk took {SafeDouble.Duration(sw.ElapsedMilliseconds)}ms");
            }
        }
Exemple #25
0
        private void generator_Click(object sender, RoutedEventArgs e)
        {
            var tExePath = bmfontPathTextBox.Text;

            if (!File.Exists(tExePath))
            {
                MessageBox.Show("填写bmfont.com文件的所在绝对路径", "提示");
                return;
            }

            var tInfoPath = fontInfoTextBox.Text;

            if (!Directory.Exists(tInfoPath))
            {
                MessageBox.Show("字体信息生成路径不是一个文件夹", "提示");
                return;
            }

            if (string.IsNullOrEmpty(imageFolderNameTextBox.Text.Trim()))
            {
                MessageBox.Show($"Image文件夹名字不能为空", "提示");
                return;
            }
            var tImageAbsoluteUri = new Uri(Path.Combine(generateAbsoluteUri.AbsolutePath, imageFolderNameTextBox.Text.Trim()), UriKind.Absolute);

            if (!Directory.Exists(tImageAbsoluteUri.AbsolutePath))
            {
                MessageBox.Show($"Image文件夹名字错误,不存在该路径“{tImageAbsoluteUri.AbsolutePath}“", "提示");
                return;
            }

            var tInfos = new List <BMFontInfo>();

            foreach (var item in dataGrid.Items)
            {
                var tRowView = item as DataRowView;
                if (tRowView == null)
                {
                    continue;
                }
                var tInfo = new BMFontInfo(tRowView[cPictureAbsolutePath].ToString());
                if (!File.Exists(tInfo.pictureAbsoluteUri.AbsolutePath))
                {
                    MessageBox.Show($"含有不存在的路径 {tInfo.pictureAbsoluteUri.AbsolutePath}", "提示");
                    return;
                }

                tInfo.SetCharSymbol(tRowView[cCharSymbol].ToString());
                if (tInfo.charSymbol == ' ' || string.IsNullOrEmpty(tInfo.charSymbol.ToString()))
                {
                    MessageBox.Show($"有未填写的字符符号", "提示");
                    return;
                }

                tInfo.SetOffsetX(tRowView[cCharOffsetX].ToString());
                tInfo.SetOffsetY(tRowView[cCharOffsetY].ToString());
                tInfo.SetAdvance(tRowView[cCharAdvance].ToString());
                tInfos.Add(tInfo);
            }

            var tTempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MyBMFont");

            if (!Directory.Exists(tTempPath))
            {
                Directory.CreateDirectory(tTempPath);
            }

            var tTempConfigPath_Cmd    = Path.Combine(tTempPath, "tempCmd.bmfc");
            var tTempConfigPath_Source = Path.Combine(tTempPath, "tempSource.bmfc");

            if (File.Exists(tTempConfigPath_Cmd))
            {
                File.Delete(tTempConfigPath_Cmd);
            }
            if (File.Exists(tTempConfigPath_Source))
            {
                File.Delete(tTempConfigPath_Source);
            }

            List <string> tTempLines = null;

            if (mBMFontType == BMFontType.Config && File.Exists(MyPrefs.sConfigPath))
            {
                tTempLines = File.ReadAllLines(MyPrefs.sConfigPath).ToList();
            }
            else if (mBMFontType == BMFontType.ImageFolder)
            {
                var tBackupConfigUri = new Uri(@"pack://application:,,,/Resources/backup.txt");
                var tStream          = Application.GetResourceStream(tBackupConfigUri);
                var tReader          = new StreamReader(tStream.Stream);
                tTempLines = new List <string>();
                while (!tReader.EndOfStream)
                {
                    tTempLines.Add(tReader.ReadLine());
                }
            }

            for (int i = 0; i < tTempLines.Count;)
            {
                if (tTempLines[i].StartsWith("icon=\""))
                {
                    tTempLines.RemoveAt(i);
                    continue;
                }
                i++;
            }

            var tAllLines_Cmd    = new List <string>(tTempLines);
            var tAllLines_Source = new List <string>(tTempLines);

            foreach (var tInfo in tInfos)
            {
                var tUri            = tImageAbsoluteUri.MakeRelativeUri(tInfo.pictureAbsoluteUri);
                var tRelativePath   = tUri.OriginalString;
                var tContent_Source = string.Format($"icon=\"{tRelativePath}\",{tInfo.charID},{tInfo.xOffset},{tInfo.yOffset},{tInfo.advance}");
                tAllLines_Source.Add(tContent_Source);

                var tContent_Cmd = string.Format($"icon=\"{tInfo.pictureAbsoluteUri.AbsolutePath}\",{tInfo.charID},{tInfo.xOffset},{tInfo.yOffset},{tInfo.advance}");
                tAllLines_Cmd.Add(tContent_Cmd);
            }

            File.WriteAllLines(tTempConfigPath_Cmd, tAllLines_Cmd);
            File.WriteAllLines(tTempConfigPath_Source, tAllLines_Source);

            CMD.ProcessCommand(tExePath, string.Format($"-c {tTempConfigPath_Cmd} -o {Path.Combine(generateAbsoluteUri.AbsolutePath.Replace("/", "\\"), mGenerateName + ".fnt")}"));

            var tNewPath = Path.Combine(generateAbsoluteUri.AbsolutePath, mGenerateName + ".bmfc");

            File.Copy(tTempConfigPath_Source, tNewPath, true);

            MyPrefs.SetString(nameof(bmfontPathTextBox), tExePath);
            MyPrefs.SetString(nameof(imageFolderNameTextBox), imageFolderNameTextBox.Text.Trim());
        }
 private string GetDataPath(DateTime date)
 {
     return(IOPath.Combine(Path, date.ToString(_dateFormat)));
 }
        private FilterStore LoadFilters(string path)
        {
            var filterFile = Path.Combine(path, "_filter.xml");

            if (_fileAccessor.Exists(filterFile))
            {
                var       filterStore = new FilterStore();
                XDocument filterDoc   = XDocument.Parse(_fileAccessor.ReadAllText(filterFile));
                var       attrFilter  = filterDoc.Root.Element("attributeFilter");
                if (attrFilter != null && attrFilter.Attribute("apply").Value == "true")
                {
                    var attrFilterElements = attrFilter.Elements("namespaceFilter");
                    if (attrFilterElements != null)
                    {
                        filterStore.AttributeFilters = new List <AttributeFilter>();
                        foreach (var fElement in attrFilterElements)
                        {
                            AttributeFilter filter = new AttributeFilter()
                            {
                                Namespace    = fElement.Attribute("name").Value,
                                TypeFilters  = new Dictionary <string, bool>(),
                                DefaultValue = true
                            };
                            foreach (var tFiler in fElement.Elements("typeFilter"))
                            {
                                bool.TryParse(tFiler.Attribute("expose").Value, out bool expose);
                                string name = tFiler.Attribute("name").Value;
                                if (name == "*")
                                {
                                    filter.DefaultValue = expose;
                                }
                                else
                                {
                                    filter.TypeFilters[name] = expose;
                                }
                            }
                            filterStore.AttributeFilters.Add(filter);
                        }
                    }
                }
                var apiFilter = filterDoc.Root.Element("apiFilter");
                if (apiFilter != null && apiFilter.Attribute("apply").Value == "true")
                {
                    var apiFilterElements = apiFilter.Elements("namespaceFilter");
                    if (apiFilterElements != null)
                    {
                        filterStore.TypeFilters   = new List <TypeFilter>();
                        filterStore.MemberFilters = new List <MemberFilter>();
                        foreach (var fElement in apiFilterElements)
                        {
                            var nsName = fElement.Attribute("name").Value?.Trim();
                            foreach (var tElement in fElement.Elements("typeFilter"))
                            {
                                var tFilter = new TypeFilter(tElement)
                                {
                                    Namespace = nsName
                                };
                                filterStore.TypeFilters.Add(tFilter);

                                var memberFilterElements = tElement.Elements("memberFilter");
                                if (memberFilterElements != null)
                                {
                                    foreach (var mElement in memberFilterElements)
                                    {
                                        filterStore.MemberFilters.Add(new MemberFilter(mElement)
                                        {
                                            Parent = tFilter
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
                return(filterStore);
            }

            return(null);
        }
Exemple #28
0
        private void convertButton_Click(object sender, RoutedEventArgs e)
        {
            var uwpSolutionFileLocation = uwpSolutionLocationTextBox.Text;

            if (string.IsNullOrWhiteSpace(uwpSolutionFileLocation) && !Path.IsPathRooted(uwpSolutionFileLocation))
            {
                MessageBox.Show("A valid Unity UWP Solution file must be provided.\nIt is the .sln file created by Unity when building for the Universal Windows Platform.", "Solution missing", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var uwpSolutionDirectory = Path.GetDirectoryName(uwpSolutionFileLocation);

            var projectName      = GetProjectName(uwpSolutionFileLocation);
            var namespaceName    = GetNamespaceName(projectName);
            var projectDirectory = Path.Combine(uwpSolutionDirectory, projectName);

            var displayName        = gameDisplayNameTextBox.Text;
            var displayDescription = descriptionTextBox.Text;

            int startWidth;
            int startHeight;
            int minWidth;
            int minHeight;

            try
            {
                startWidth  = int.Parse(widthTextBox.Text);
                startHeight = int.Parse(heightTextBox.Text);
                minWidth    = int.Parse(minWidthTextBox.Text);
                minHeight   = int.Parse(minHeightTextBox.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("Invalid input for one of the size fields. Whole numbers only.", "Invalid input", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            bool resizable = resizableCheckBox.IsChecked ?? false;

            try
            {
                AddGameBarPackage(uwpSolutionDirectory, projectName);
            }
            catch (Exception)
            {
                MessageBox.Show("An error occured when adding the Game Bar package.", "Failed", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            try
            {
                ModifyAppManifest(uwpSolutionDirectory, projectName, true, displayName, displayDescription, startWidth, startHeight, minWidth, minHeight, resizable);
            }
            catch (Exception)
            {
                MessageBox.Show("An error occured when modifying the project's appxmanifest.", "Failed", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            try
            {
                ModifyAppH(projectDirectory);
            }
            catch (Exception)
            {
                MessageBox.Show("An error occured when modifying the project's App.xaml.h file.", "Failed", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            try
            {
                ModifyAppCpp(projectDirectory);
            }
            catch (Exception)
            {
                MessageBox.Show("An error occured when modifying the project's App.xaml.cpp file.", "Failed", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            MessageBox.Show("Game Bar widget successfully attached to the Unity project.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
        }
Exemple #29
0
        public Error OpenInExternalEditor(Script script, int line, int col)
        {
            var editorId = (ExternalEditorId)editorSettings.GetSetting("mono/editor/external_editor");

            switch (editorId)
            {
            case ExternalEditorId.None:
                // Not an error. Tells the caller to fallback to the global external editor settings or the built-in editor.
                return(Error.Unavailable);

            case ExternalEditorId.VisualStudio:
            {
                string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath);

                var args = new List <string>
                {
                    GodotSharpDirs.ProjectSlnPath,
                    line >= 0 ? $"{scriptPath};{line + 1};{col + 1}" : scriptPath
                };

                string command = Path.Combine(GodotSharpDirs.DataEditorToolsDir, "GodotTools.OpenVisualStudio.exe");

                try
                {
                    if (Godot.OS.IsStdoutVerbose())
                    {
                        Console.WriteLine($"Running: \"{command}\" {string.Join(" ", args.Select(a => $"\"{a}\""))}");
                    }

                    OS.RunProcess(command, args);
                }
                catch (Exception e)
                {
                    GD.PushError($"Error when trying to run code editor: VisualStudio. Exception message: '{e.Message}'");
                }

                break;
            }

            case ExternalEditorId.VisualStudioForMac:
                goto case ExternalEditorId.MonoDevelop;

            case ExternalEditorId.Rider:
            {
                string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath);
                RiderPathManager.OpenFile(GodotSharpDirs.ProjectSlnPath, scriptPath, line);
                return(Error.Ok);
            }

            case ExternalEditorId.MonoDevelop:
            {
                string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath);

                GodotIdeManager.LaunchIdeAsync().ContinueWith(launchTask =>
                    {
                        var editorPick = launchTask.Result;
                        if (line >= 0)
                        {
                            editorPick?.SendOpenFile(scriptPath, line + 1, col);
                        }
                        else
                        {
                            editorPick?.SendOpenFile(scriptPath);
                        }
                    });

                break;
            }

            case ExternalEditorId.VsCode:
            {
                if (string.IsNullOrEmpty(_vsCodePath) || !File.Exists(_vsCodePath))
                {
                    // Try to search it again if it wasn't found last time or if it was removed from its location
                    _vsCodePath = VsCodeNames.SelectFirstNotNull(OS.PathWhich, orElse: string.Empty);
                }

                var args = new List <string>();

                bool osxAppBundleInstalled = false;

                if (OS.IsOSX)
                {
                    // The package path is '/Applications/Visual Studio Code.app'
                    const string vscodeBundleId = "com.microsoft.VSCode";

                    osxAppBundleInstalled = Internal.IsOsxAppBundleInstalled(vscodeBundleId);

                    if (osxAppBundleInstalled)
                    {
                        args.Add("-b");
                        args.Add(vscodeBundleId);

                        // The reusing of existing windows made by the 'open' command might not choose a wubdiw that is
                        // editing our folder. It's better to ask for a new window and let VSCode do the window management.
                        args.Add("-n");

                        // The open process must wait until the application finishes (which is instant in VSCode's case)
                        args.Add("--wait-apps");

                        args.Add("--args");
                    }
                }

                var resourcePath = ProjectSettings.GlobalizePath("res://");
                args.Add(resourcePath);

                string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath);

                if (line >= 0)
                {
                    args.Add("-g");
                    args.Add($"{scriptPath}:{line}:{col}");
                }
                else
                {
                    args.Add(scriptPath);
                }

                string command;

                if (OS.IsOSX)
                {
                    if (!osxAppBundleInstalled && string.IsNullOrEmpty(_vsCodePath))
                    {
                        GD.PushError("Cannot find code editor: VSCode");
                        return(Error.FileNotFound);
                    }

                    command = osxAppBundleInstalled ? "/usr/bin/open" : _vsCodePath;
                }
                else
                {
                    if (string.IsNullOrEmpty(_vsCodePath))
                    {
                        GD.PushError("Cannot find code editor: VSCode");
                        return(Error.FileNotFound);
                    }

                    command = _vsCodePath;
                }

                try
                {
                    OS.RunProcess(command, args);
                }
                catch (Exception e)
                {
                    GD.PushError($"Error when trying to run code editor: VSCode. Exception message: '{e.Message}'");
                }

                break;
            }

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(Error.Ok);
        }
    public QTMConnectLiveLink(ReadOnlyTargetRules Target) : base(Target)
    {
        PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;

        string rtClientSDKPath          = Path.GetFullPath(Path.Combine(PluginDirectory, "Source/ThirdParty/RTClientSDK"));
        string rtClientSDKIncludePath   = System.IO.Path.Combine(rtClientSDKPath, "Include");
        string targetPlatformPathName   = GetTargetPlatformPathName(Target);
        string rtClientSDKLibPath       = Path.Combine(rtClientSDKPath, "Lib", targetPlatformPathName);
        string pluginPublicIncludePath  = Path.Combine(ModuleDirectory, "Public");
        string pluginPrivateIncludePath = Path.Combine(ModuleDirectory, "Private");

        PublicIncludePaths.AddRange(
            new string[] {
            pluginPublicIncludePath
        }
            );


        PrivateIncludePaths.AddRange(
            new string[] {
            pluginPrivateIncludePath,
            rtClientSDKIncludePath,
        }
            );


        PublicDependencyModuleNames.AddRange(
            new string[]
        {
            "Core",
            "Networking",
            "Sockets",
            "LiveLinkInterface",
            "LiveLink",
#if UE_5_0_OR_LATER
            "LiveLinkAnimationCore",
#endif
        }
            );


        PrivateDependencyModuleNames.AddRange(
            new string[]
        {
            "CoreUObject",
            "Engine",
            "Slate",
            "SlateCore",
            "LiveLink",
            "LiveLinkInterface",
            "TimeManagement",
#if UE_5_0_OR_LATER
            "LiveLinkAnimationCore",
#endif
        }
            );


        PublicSystemIncludePaths.Add(rtClientSDKIncludePath);

        if (IsWindowsPlatform(Target))
        {
            PublicAdditionalLibraries.Add(Path.Combine(rtClientSDKLibPath, "RTClientSDK.lib"));
        }
    }
 private ContainerCmdletProvider GetContainerProviderByPath(string path, string name, out Path normalizedPath)
 {
     PSDriveInfo drive;
     var provider = _cmdlet.State.SessionStateGlobal.GetProviderByPath(path, out drive) as ContainerCmdletProvider;
     if (provider == null)
     {
         throw new PSInvalidOperationException(String.Format("The provider for path '{0}' is not a ContainerProvider", path));
     }
     normalizedPath = new Path(path);
     if (!String.IsNullOrEmpty(name))
     {
         normalizedPath = normalizedPath.Combine(name);
     }
     normalizedPath = normalizedPath.NormalizeSlashes();
     return provider;
 }