private static void _PreAction(ScriptEngine engine, IScriptAction command) { var loadCommand = command as LoadFileCommand; if (loadCommand != null) { Console.WriteLine("Loading from file " + loadCommand.FileName); return; } var saveCommand = command as SaveFileCommand; if (saveCommand != null) { Console.WriteLine("Saving to file " + saveCommand.FileName); } var resizeCommand = command as ResizeCommand; if (resizeCommand != null) { Console.WriteLine("Applying filter : {0}", SupportedManipulators.MANIPULATORS.First(k => k.Value == resizeCommand.Manipulator).Key); Console.WriteLine(" Target percentage : {0}", (resizeCommand.Percentage == 0 ? "auto" : resizeCommand.Percentage + "%")); Console.WriteLine(" Target width : {0}", (resizeCommand.Width == 0 ? "auto" : resizeCommand.Width + "pixels")); Console.WriteLine(" Target height : {0}", (resizeCommand.Height == 0 ? "auto" : resizeCommand.Height + "pixels")); Console.WriteLine(" Hori. BPH : {0}", resizeCommand.HorizontalBph); Console.WriteLine(" Vert. BPH : {0}", resizeCommand.VerticalBph); Console.WriteLine(" Use Thresholds : {0}", resizeCommand.UseThresholds); Console.WriteLine(" Centered Grid : {0}", resizeCommand.UseCenteredGrid); Console.WriteLine(" Radius : {0}", resizeCommand.Radius); Console.WriteLine(" Repeat : {0} times", resizeCommand.Count); } }
/// <summary> /// Parses the command line arguments. /// </summary> /// <param name="arguments">The arguments.</param> public static CLIExitCode ParseCommandLineArguments(string[] arguments) { if (arguments == null || arguments.Length < 1) return (CLIExitCode.OK); var engine = new ScriptEngine(); var line = string.Join(" ", arguments.Select(a => string.Format(@"""{0}""", a))); Console.WriteLine("Executing the following script:"); Console.WriteLine(line); Console.WriteLine(); // load script from command line parameters try { ScriptSerializer.LoadFromString(engine, line); } catch (ScriptSerializerException e) { _ShowHelp(); return (e.ErrorType); } // execute script try { engine.RepeatActions(_PreAction, _PostAction); } catch (Exception e) { Console.WriteLine(e.Message); return (CLIExitCode.RuntimeError); } return (CLIExitCode.OK); }
/// <summary> /// Loads from file. /// </summary> /// <param name="engine">The engine.</param> /// <param name="filename">The filename.</param> public static void LoadFromFile(ScriptEngine engine, string filename) { Contract.Requires(engine != null); Contract.Requires(filename != null); var content = File.ReadAllLines(filename); for (var lineNumber = 0; lineNumber < content.Length; lineNumber++) { var line = content[lineNumber]; var cliExitCode = _ParseScriptLine(line, engine); if (cliExitCode != CLIExitCode.OK) throw new ScriptSerializerException(filename, lineNumber, cliExitCode); } }
/// <summary> /// Saves the script engine's tasks to a file. /// </summary> /// <param name="engine">The engine.</param> /// <param name="filename">The filename.</param> public static void SaveToFile(ScriptEngine engine, string filename) { Contract.Requires(engine != null); Contract.Requires(filename != null); File.WriteAllText(filename, SerializeState(engine)); }
/// <summary> /// Serializes the state of the script engine. /// </summary> /// <param name="engine">The engine.</param> /// <returns>A makro to repeat the script engine actions.</returns> public static string SerializeState(ScriptEngine engine) { Contract.Requires(engine != null); var tasks = engine.Actions; return (string.Join(Environment.NewLine, tasks.Select(_GetCommandTextForAction).Where(l => !string.IsNullOrWhiteSpace(l)))); }
/// <summary> /// Parses the resize command. /// </summary> /// <param name="engine">The engine.</param> /// <param name="dimensions">The dimensions.</param> /// <param name="filterName">Name of the filter(and parameters if any).</param> /// <returns></returns> private static CLIExitCode _ParseResizeCommand(ScriptEngine engine, string dimensions, string filterName) { Contract.Requires(engine != null); Contract.Requires(dimensions != null); Contract.Requires(filterName != null); var match = _DIMENSIONS_REGEX.Match(dimensions); if (!match.Success) return (CLIExitCode.InvalidTargetDimensions); var width = match.Groups["width"].Value; var height = match.Groups["height"].Value; var percent = match.Groups["percent"].Value; word targetWidth = 0; word targetHeight = 0; word targetPercent = 0; if (!(string.IsNullOrWhiteSpace(width) || word.TryParse(width, out targetWidth))) return (CLIExitCode.CouldNotParseDimensionsAsWord); if (!(string.IsNullOrWhiteSpace(height) || word.TryParse(height, out targetHeight))) return (CLIExitCode.CouldNotParseDimensionsAsWord); if (!(string.IsNullOrWhiteSpace(percent) || word.TryParse(percent, out targetPercent))) return (CLIExitCode.CouldNotParseDimensionsAsWord); var useAspect = targetWidth == 0 || targetHeight == 0; var filterMatch = _FILTER_REGEX.Match(filterName); if (!filterMatch.Success) return (CLIExitCode.InvalidFilterDescription); var filterParams = filterMatch.Groups["params"].Value; filterName = filterMatch.Groups["filter"].Value; var useThresholds = true; var useCenteredGrid = true; var repeat = (byte)1; var radius = 1f; var vbounds = OutOfBoundsMode.ConstantExtension; var hbounds = OutOfBoundsMode.ConstantExtension; if (!string.IsNullOrWhiteSpace(filterParams) && !byte.TryParse(filterParams, out repeat)) { repeat = 1; // parse parameterlist, splitted with "," and assigned using "=" var parameters = ( from p in filterParams.Split(',') let idx = p.IndexOf('=') where idx > 0 let name = p.Substring(0, idx).Trim().ToLower() let value = p.Substring(idx + 1).Trim() select new KeyValuePair<string, string>(name, value) ); #region supported parameter handling foreach (var pair in parameters) { switch (pair.Key) { case VBOUNDS_PARAMETER_NAME: { var value = pair.Value.ToLower(); if (value == CONST_BOUNDS_VALUE) vbounds = OutOfBoundsMode.ConstantExtension; else if (value == HALF_BOUNDS_VALUE) vbounds = OutOfBoundsMode.HalfSampleSymmetric; else if (value == WHOLE_BOUNDS_VALUE) vbounds = OutOfBoundsMode.WholeSampleSymmetric; else if (value == WRAP_BOUNDS_VALUE) vbounds = OutOfBoundsMode.WrapAround; else return (CLIExitCode.InvalidOutOfBoundsMode); break; } case HBOUNDS_PARAMETER_NAME: { var value = pair.Value.ToLower(); if (value == CONST_BOUNDS_VALUE) hbounds = OutOfBoundsMode.ConstantExtension; else if (value == HALF_BOUNDS_VALUE) hbounds = OutOfBoundsMode.HalfSampleSymmetric; else if (value == WHOLE_BOUNDS_VALUE) hbounds = OutOfBoundsMode.WholeSampleSymmetric; else if (value == WRAP_BOUNDS_VALUE) hbounds = OutOfBoundsMode.WrapAround; else return (CLIExitCode.InvalidOutOfBoundsMode); break; } case RADIUS_PARAMETER_NAME: { if (!float.TryParse(pair.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out radius)) return (CLIExitCode.CouldNotParseParameterAsFloat); break; } case REPEAT_PARAMETER_NAME: { if (!byte.TryParse(pair.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out repeat)) return (CLIExitCode.CouldNotParseParameterAsByte); break; } case CENTERED_GRID_PARAMETER_NAME: { useCenteredGrid = pair.Value == "1"; break; } case THRESHOLDS_PARAMETER_NAME: { useThresholds = pair.Value == "1"; break; } default: { return (CLIExitCode.UnknownParameter); } } } #endregion } // find the given manipulator var manipulator = SupportedManipulators.MANIPULATORS .Where(resizer => string.Compare(resizer.Key, filterName, true) == 0) .Select(kvp => kvp.Value) .FirstOrDefault() ; if (manipulator == null) return (CLIExitCode.UnknownFilter); engine.AddWithoutExecution(new ResizeCommand(true, manipulator, targetWidth, targetHeight, targetPercent, useAspect, hbounds, vbounds, repeat, useThresholds, useCenteredGrid, radius)); return (CLIExitCode.OK); }
/// <summary> /// Parses a script line and adds the action from it to the engine's list. /// </summary> /// <param name="line">The line.</param> /// <param name="engine">The engine.</param> private static CLIExitCode _ParseScriptLine(string line, ScriptEngine engine) { Contract.Requires(engine != null); if (string.IsNullOrWhiteSpace(line)) return (CLIExitCode.OK); var arguments = line.SplitWithQuotes(' ').ToArray(); var length = arguments.Length; if (length < 1) return (CLIExitCode.OK); var i = 0; while (i < length) { var command = arguments[i++].ToLowerInvariant(); // skip empty stuff if (command.IsNullOrWhiteSpace()) continue; switch (command) { #region /STDIN case STDIN_COMMAND_NAME: { engine.AddWithoutExecution(new LoadStdInCommand()); engine.AddWithoutExecution(new NullTransformCommand()); break; } #endregion #region /STDOUT case STDOUT_COMMAND_NAME: { engine.AddWithoutExecution(new SaveStdOutCommand()); break; } #endregion #region /LOAD case LOAD_COMMAND_NAME: { if (length - i < 1) { return (CLIExitCode.TooLessArguments); } var filename = arguments[i++]; if (filename == null) { return (CLIExitCode.FilenameMustNotBeNull); } engine.AddWithoutExecution(new LoadFileCommand(filename)); engine.AddWithoutExecution(new NullTransformCommand()); break; } #endregion #region /RESIZE case RESIZE_COMMAND_NAME: { if (length - i < 2) { return (CLIExitCode.TooLessArguments); } var dimensions = arguments[i++].Trim(); var filterName = arguments[i++].Trim(); var result = _ParseResizeCommand(engine, dimensions, filterName); if (result != CLIExitCode.OK) return (result); break; } #endregion #region /SAVE case SAVE_COMMAND_NAME: { if (length - i < 1) { return (CLIExitCode.TooLessArguments); } var filename = arguments[i++]; if (filename == null) { return (CLIExitCode.FilenameMustNotBeNull); } engine.AddWithoutExecution(new SaveFileCommand(filename)); break; } #endregion #region /SCRIPT case SCRIPT_COMMAND_NAME: { if (length - i < 1) { return (CLIExitCode.TooLessArguments); } var filename = arguments[i++]; if (filename == null) { return (CLIExitCode.FilenameMustNotBeNull); } LoadFromFile(engine, filename); break; } #endregion default: { return (CLIExitCode.UnknownParameter); } } } return (CLIExitCode.OK); }
/// <summary> /// Loads from string. /// </summary> /// <param name="engine">The engine.</param> /// <param name="line">The line.</param> public static void LoadFromString(ScriptEngine engine, string line) { Contract.Requires(engine != null); var cliExitCode = _ParseScriptLine(line, engine); if (cliExitCode != CLIExitCode.OK) throw new ScriptSerializerException(null, 1, cliExitCode); }
private static void _PostAction(ScriptEngine engine, IScriptAction command) { var loadCommand = command as LoadFileCommand; if (loadCommand != null) { Console.WriteLine(" File : {0} Bytes", new FileInfo(loadCommand.FileName).Length); Console.WriteLine(" Width : {0} Pixel", engine.SourceImage.Width); Console.WriteLine(" Height : {0} Pixel", engine.SourceImage.Height); Console.WriteLine(" Size : {0:0.00} MegaPixel", (engine.SourceImage.Width * engine.SourceImage.Height / 1000000.0)); Console.WriteLine(" Type : {0}", ImageCodecInfo.GetImageDecoders().First(d => d.FormatID == engine.GdiSource.RawFormat.Guid).FormatDescription); Console.WriteLine(" Format : {0}", engine.GdiSource.PixelFormat); return; } var saveCommand = command as SaveFileCommand; if (saveCommand != null) { var reloadedImage = Image.FromFile(saveCommand.FileName); Console.WriteLine(" File : {0} Bytes", new FileInfo(saveCommand.FileName).Length); Console.WriteLine(" Width : {0} Pixel", reloadedImage.Width); Console.WriteLine(" Height : {0} Pixel", reloadedImage.Height); Console.WriteLine(" Size : {0:0.00} MegaPixel", (reloadedImage.Width * reloadedImage.Height / 1000000.0)); Console.WriteLine(" Type : {0}", ImageCodecInfo.GetImageDecoders().First(d => d.FormatID == reloadedImage.RawFormat.Guid).FormatDescription); Console.WriteLine(" Format : {0}", reloadedImage.PixelFormat); } }
/// <summary> /// Applies the given script file to the source image. /// </summary> /// <param name="fileName">Name of the file.</param> private void _ApplyScriptFile(string fileName) { var localEngine = new ScriptEngine(); localEngine.AddWithoutExecution(new NullTransformCommand()); ScriptSerializer.LoadFromFile(localEngine, fileName); this._ExecuteScriptActions(localEngine.Actions.ToArray()); }