public virtual void testSetDiffSizeTrigger()
        {
            ImageDiff diff = IMAGE_DIFFER.makeDiff(IMAGE_A_SMALL, IMAGE_B_SMALL);

            Assert.IsFalse(diff.withDiffSizeTrigger(624).hasDiff());
            Assert.IsTrue(diff.withDiffSizeTrigger(623).hasDiff());
        }
        public virtual void testSameSizeDiff()
        {
            ImageDiff        diff    = IMAGE_DIFFER.makeDiff(IMAGE_A_SMALL, IMAGE_B_SMALL);
            Matcher <Bitmap> matcher = ImageTool.equalImage(loadImage("img/expected/same_size_diff.png"));

            Assert.IsTrue(matcher.Matches(diff.getMarkedImage()));
        }
        public virtual void testSetDiffColor()
        {
            ImageDiff diff = IMAGE_DIFFER.makeDiff(IMAGE_A_SMALL, IMAGE_B_SMALL);

            Matcher <Bitmap> matcher = ImageTool.equalImage(loadImage("img/expected/green_diff.png"));

            Assert.IsTrue(matcher.Matches(diff.withDiffColor(Color.Green).getMarkedImage()));
        }
        public virtual void testIgnoredCoordsSame()
        {
            Screenshot       a       = this.createScreenshotWithSameIgnoredAreas(IMAGE_A_SMALL);
            Screenshot       b       = this.createScreenshotWithSameIgnoredAreas(IMAGE_B_SMALL);
            ImageDiff        diff    = IMAGE_DIFFER.makeDiff(a, b);
            Matcher <Bitmap> matcher = ImageTool.equalImage(loadImage("img/expected/ignore_coords_same.png"));

            Assert.IsTrue(matcher.Matches(diff.getMarkedImage()));
        }
        public virtual void testCoordsToCompareAndIgnoredCombine()
        {
            Screenshot a = this.createScreenshotWithIgnoredAreas(IMAGE_A_SMALL, new HashSet <Coords> {
                new Coords(0, 0, 60, 60)
            });

            a.setCoordsToCompare(new HashSet <Coords> {
                new Coords(50, 50, 100, 100)
            });
            Screenshot b = this.createScreenshotWithIgnoredAreas(IMAGE_B_SMALL, new HashSet <Coords> {
                new Coords(0, 0, 80, 80)
            });

            b.setCoordsToCompare(new HashSet <Coords> {
                new Coords(50, 50, 100, 100)
            });
            ImageDiff        diff    = IMAGE_DIFFER.makeDiff(a, b);
            Matcher <Bitmap> matcher = ImageTool.equalImage(loadImage("img/expected/combined_diff.png"));

            Assert.IsTrue(matcher.Matches(diff.getMarkedImage()));
        }
        private static IList <double> DiffFusionImages(FusionTestDataContainer data, string testName)
        {
            var outputPath = new DirectoryInfo(Path.Combine(typeof(FusionLayerCoregistrationTests).FullName, testName));

            if (outputPath.Exists)
            {
                outputPath.Delete(true);
            }
            outputPath.Create();

            using (var log = File.CreateText(Path.Combine(outputPath.FullName, "data.csv")))
            {
                // if the overlay image is not rendered at all, this coregistration test would pass, but then the color compositing test would fail
                using (var referenceDisplaySet = data.CreateBaseDisplaySet())
                {
                    using (var testDisplaySet = data.CreateFusionDisplaySet())
                    {
                        var list  = new List <double>();
                        int index = 0;
                        foreach (var testImage in testDisplaySet.PresentationImages)
                        {
                            var referenceImage = referenceDisplaySet.PresentationImages[index];
                            NormalizePresentationImageDisplay(testImage);
                            NormalizePresentationImageDisplay(referenceImage);

                            Bitmap diff;
                            double result = ImageDiff.Compare(ImageDiffAlgorithm.Euclidian, referenceImage, testImage, out diff);
                            diff.Save(Path.Combine(outputPath.FullName, string.Format("diff{0:000}.png", index)));
                            diff.Dispose();
                            log.WriteLine("{0}, {1:f6}", index, result);
                            list.Add(result);

                            ++index;
                        }

                        return(list);
                    }
                }
            }
        }
        public void AssertFusionResults()
        {
            try
            {
                using (var outputStream = File.CreateText(string.Format("{0}.AssertFusionResults.csv", this.GetType().FullName)))
                {
                    using (var referenceDisplaySet = TestDisplaySetGenerator.CreateBaseDisplaySet())
                    {
                        using (var testDisplaySet = TestDisplaySetGenerator.CreateFusionDisplaySet())
                        {
                            int index = 0;
                            foreach (var testImage in testDisplaySet.PresentationImages)
                            {
                                var colorMapProvider = (IColorMapProvider)testImage;
                                colorMapProvider.ColorMapManager.InstallColorMap("Grayscale");

                                var layerOpacityProvider = (ILayerOpacityProvider)testImage;
                                layerOpacityProvider.LayerOpacityManager.Thresholding = false;
                                layerOpacityProvider.LayerOpacityManager.Opacity      = 0.5f;

                                Bitmap diff;
                                var    referenceImage = referenceDisplaySet.PresentationImages[index];
                                var    result         = ImageDiff.Compare(ImageDiffAlgorithm.Euclidian, referenceImage, testImage, out diff);
                                outputStream.WriteLine("{0}, {1:f4}", index, result);
                                diff.Save(index + ".png");
                                diff.Dispose();

                                ++index;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.Report(ex, "Fusion test assertion fail.", this.Context.DesktopWindow);
            }
        }
        private static IList <double> DiffFusionOperatorResults(IColorMap colorMap, bool thresholding, string testName)
        {
            var outputPath = new DirectoryInfo(Path.Combine(typeof(FusionColorCompositingTest).FullName, testName));

            if (outputPath.Exists)
            {
                outputPath.Delete(true);
            }
            outputPath.Create();

            // this kind of test requires that the base and overlay slices be unsigned and precisely coincident
            using (var data = new FusionTestDataContainer(
                       () => TestDataFunction.GradientX.CreateSops(false, Modality.CT, new Vector3D(1.0f, 1.0f, 15.0f), Vector3D.xUnit, Vector3D.yUnit, Vector3D.zUnit),
                       () => TestDataFunction.GradientY.CreateSops(false, Modality.PT, new Vector3D(1.0f, 1.0f, 15.0f), Vector3D.xUnit, Vector3D.yUnit, Vector3D.zUnit)))
            {
                using (var log = File.CreateText(Path.Combine(outputPath.FullName, "data.csv")))
                {
                    log.WriteLine("{0}, {1}, {2}, {3}", "n", "opacity", "alpha", "diff");
                    using (var baseDisplaySet = data.CreateBaseDisplaySet())
                    {
                        using (var overlayDisplaySet = data.CreateOverlayDisplaySet())
                        {
                            using (var fusionDisplaySet = data.CreateFusionDisplaySet())
                            {
                                var list = new List <double>();

                                var imageIndex  = fusionDisplaySet.PresentationImages.Count / 2;
                                var fusionImage = fusionDisplaySet.PresentationImages[imageIndex];

                                for (int n = 0; n <= 10; n++)
                                {
                                    var opacity = n / 10f;

                                    SetFusionDisplayParameters(fusionImage, colorMap, opacity, thresholding);
                                    using (IPresentationImage referenceImage =
                                               Fuse(baseDisplaySet.PresentationImages[imageIndex], overlayDisplaySet.PresentationImages[imageIndex], colorMap, opacity, thresholding))
                                    {
                                        using (var referenceBmp = DrawToBitmap(referenceImage))
                                        {
                                            referenceBmp.Save(Path.Combine(outputPath.FullName, string.Format("reference{0}.png", n)));
                                        }

                                        using (var fusionBmp = DrawToBitmap(fusionImage))
                                        {
                                            fusionBmp.Save(Path.Combine(outputPath.FullName, string.Format("test{0}.png", n)));
                                        }

                                        // because the fusion display set is generated from real base images and *reformatted* overlay images,
                                        // there will necessarily be higher differences at the edges of the useful image area

                                        Bitmap diff;
                                        double result = ImageDiff.Compare(ImageDiffAlgorithm.Euclidian, referenceImage, fusionImage, new Rectangle(18, 18, 98, 98), out diff);
                                        diff.Save(Path.Combine(outputPath.FullName, string.Format("diff{0}.png", n)));
                                        diff.Dispose();
                                        log.WriteLine("{0}, {1:f2}, {2}, {3:f6}", n, opacity, (int)(255 * opacity), result);
                                        list.Add(result);
                                    }
                                }

                                return(list);
                            }
                        }
                    }
                }
            }
        }
    static void Main(string[] args)
    {
        string URL       = null;
        string file      = null;
        int    minWidth  = 800;
        int    minHeight = 600;
        int    delay     = 1;
        string mode      = "edge";
        bool   diff      = false;
        string reference = null;
        string tmpPath   = System.IO.Path.GetTempPath() + @"IECapt\";

        Directory.CreateDirectory(tmpPath);
        bool   debug     = false;
        bool   silent    = false;
        string IEversion = "";

        string debugMessage = "";

        if (args.Length == 0)
        {
            PrintUsage();
            return;
        }

        // Parse command line parameters
        foreach (string arg in args)
        {
            string[] tmp = arg.Split(new char[] { '=' }, 2);

            if (tmp.Length < 2)
            {
                PrintUsage();
                return;
            }
            else if (tmp[0].Equals("-u") || tmp[0].Equals("--url"))
            {
                URL = tmp[1];
            }
            else if (tmp[0].Equals("-o") || tmp[0].Equals("--out"))
            {
                file = tmp[1];;
            }
            else if (tmp[0].Equals("-rf") || tmp[0].Equals("--reference"))
            {
                reference = tmp[1];;
            }
            else if (tmp[0].Equals("-mw") || tmp[0].Equals("--min-width"))
            {
                minWidth = int.Parse(tmp[1]);
            }
            else if (tmp[0].Equals("-mh") || tmp[0].Equals("--min-height"))
            {
                minHeight = int.Parse(tmp[1]);
            }
            else if (tmp[0].Equals("-dy") || tmp[0].Equals("--delay"))
            {
                delay = int.Parse(tmp[1]);
            }
            else if (tmp[0].Equals("-df") || tmp[0].Equals("--diff"))
            {
                diff = (tmp[1].ToString() == "yes");
            }
            else if (tmp[0].Equals("-ie") || tmp[0].Equals("--internet-explorer"))
            {
                Dictionary <string, int> dic = new Dictionary <string, int>();
                dic.Add("quirks", 0x1388);
                dic.Add("7", 0x1b58);
                dic.Add("8", 0x1f40);
                dic.Add("8+", 0x22b8);
                dic.Add("9", 0x2328);
                dic.Add("9+", 0x270f);
                dic.Add("10", 0x3e8);

                object o = "edge";
                IEversion = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Version Vector", "IE", o).ToString();

                Int32 value = 0;
                mode = tmp[1];

                if (mode == "edge")
                {
                    value = dic[IEversion.Split('.')[0]];
                }
                else if (dic.ContainsKey(mode))
                {
                    value     = dic[mode];
                    IEversion = value.ToString();
                }

                try
                {
                    Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION", Path.GetFileName(System.Windows.Forms.Application.ExecutablePath), value, RegistryValueKind.DWord);
                }
                catch (System.UnauthorizedAccessException e)
                {
                    Console.Error.WriteLine(e.Message.ToString());
                    return;
                }
            }
            else if (tmp[0].Equals("-dg") || tmp[0].Equals("--debug"))
            {
                debug = (tmp[1].ToString() == "yes");
            }
            else if (tmp[0].Equals("-s") || tmp[0].Equals("--silent"))
            {
                silent = (tmp[1].ToString() == "yes");
            }
            else
            {
                Console.WriteLine("Warning: unknown parameter {0}", tmp[0]);
            }
        }

        if (delay < 1 || URL == null)
        {
            PrintUsage();
            return;
        }

        if (String.IsNullOrEmpty(file))
        {
            file = tmpPath + URL.ToLower().Replace("http://", "").Replace("/", "-") + "-" + mode + ".png";
        }

        Debug dbg = new Debug(debug);

        debugMessage += "URL: " + URL + "\n";
        debugMessage += "Output: " + file + "{" + (File.Exists(reference)) + "}\n";
        debugMessage += "Reference: " + reference + "{" + (File.Exists(reference)) + "}\n";
        debugMessage += "Min-width: " + minWidth + "px\n";
        debugMessage += "Min-height: " + minHeight + "px\n";
        debugMessage += "Delay: " + delay + "ms\n";
        debugMessage += "Diff: " + diff + "\n";
        debugMessage += "IE Mode: " + IEversion + "\n";
        debugMessage += "IE Silent Mode: " + silent + "\n";
        dbg.log(debugMessage);

        ImageDiff imageDiff = null;

        if (reference != null)
        {
            imageDiff = new ImageDiff(reference, file);
        }
        AxWebBrowser wb = new AxWebBrowser();

        System.Windows.Forms.Form main = new IECaptForm(URL, file, minWidth, delay, wb, imageDiff);

        wb.BeginInit();
        wb.Parent = main;
        wb.EndInit();

        // Set the initial dimensions of the browser's client area.
        wb.SetBounds(0, 0, minWidth, minHeight);

        object oBlank = "about:blank";
        object oURL   = URL;
        object oNull  = String.Empty;

        // Internet Explorer should show no dialog boxes; this does not dis-
        // able script debugging however, I am not aware of a method to dis-
        // able that, other than manual configuration in he Internet Settings
        // or perhaps the registry.
        wb.Silent = silent;

        // The custom UI handler can only be registered on a document, so we
        // navigate to about:blank as a first step, then register the handler.
        wb.Navigate2(ref oBlank, ref oNull, ref oNull, ref oNull, ref oNull);

        ICustomDoc cdoc = wb.Document as ICustomDoc;

        cdoc.SetUIHandler(new IECaptUIHandler());

        // Register a document complete handler. It will be called whenever a
        // document completes loading, including embedded documents and the
        // initial about:blank document.
        wb.DocumentComplete +=
            new DWebBrowserEvents2_DocumentCompleteEventHandler(IE_DocumentComplete);

        // Register an error handler. If the main document cannot be loaded,
        // the document complete event will not fire, so we have to listen to
        // this and shut the application down in case of a fatal error.
        wb.NavigateError +=
            new DWebBrowserEvents2_NavigateErrorEventHandler(IE_NavigateError);

        // Now navigate to the final destination.
        wb.Navigate2(ref oURL, ref oNull, ref oNull, ref oNull, ref oNull);

        System.Windows.Forms.Application.Run();
    }
Exemple #10
0
        //TODO: Errors handling and refactoring
        private bool Cmp(Session session, Driver[] items, string relative, int idx, Results results)
        {
            var settings = session.Settings;
            var isScript = StringUtils.RemovePrefix(ref relative, "EXEC ");

            var pages = items.AsParallel().AsOrdered().Select(item =>
            {
                var(baseUri, driver) = item;

                if (isScript)
                {
                    driver.ExecuteScript(relative);
                }
                else
                {
                    driver.Navigate().GoToUrl(new Uri(baseUri, relative));
                }

                if (settings.Script.OnLoad != null)
                {
                    driver.ExecuteScript(settings.Script.OnLoad);
                }

                driver.Wait(settings.WaitUntil);

                return(Http: driver.GetHttpResponse(), Bmp: driver.GetVertScrollScreenshot(settings));
            }).ToArray();

            (HttpResponse Http, Bitmap Bmp)pageLeft = pages[0], pageRight = pages[1];
            Bitmap imgLeft = pageLeft.Bmp, imgRight = pageRight.Bmp, diff;

            int pixels;
            var result  = ImageDiff.CompareImages(settings, imgLeft, imgRight, out diff);
            var areSame = (pixels = result.Unmatched) <= settings.Compare.PixelsThreshold || result.Map == null || result.Map.Count == 0;

            var match = 1.0 - (double)pixels / diff.Width / diff.Height;

            WriteResult(areSame, areSame ? "Same: " : "Diff: ", relative);
            log.LogInformation($"      Match {match:P1} ({pixels} / {diff.Width * diff.Height} pixels)");

            string leftName = null, rightName = null, diffName = null;

            var name = $"{idx:0000}-" + relative.Trim('/').ToSafeFilename();

            if (!areSame)
            {
                leftName = name + "-left.png";
                imgLeft.Save(Path.Combine(ResultsImgPath, leftName), ImageFormat.Png);

                rightName = name + "-right.png";
                imgRight.Save(Path.Combine(ResultsImgPath, rightName), ImageFormat.Png);

                diffName = name + "-diff.png";
                diff.Save(Path.Combine(ResultsImgPath, diffName), ImageFormat.Png);
            }

            results.TotalCount++;
            if (areSame)
            {
                results.SameCount++;
            }
            else
            {
                results.DiffCount++;
            }

            results.Diffs.Add(new Diff
            {
                Relative        = relative,
                AreSame         = areSame,
                UnmatchedPixels = result.Unmatched,
                TotalPixels     = diff.Width * diff.Height,
                Match           = match,
                Left            = new Page
                {
                    Url      = isScript ? null : new Uri(session.SvcLeft, relative),
                    Response = pageLeft.Http,
                    Img      = new Img
                    {
                        Filename = leftName,
                        Src      = leftName == null ? null : Path.Combine(ImgRelativePath, WebUtility.UrlEncode(leftName)),
                        Size     = pageLeft.Bmp.Size
                    }
                },
                Right = new Page
                {
                    Url      = isScript ? null : new Uri(session.SvcRight, relative),
                    Response = pageRight.Http,
                    Img      = new Img
                    {
                        Filename = rightName,
                        Src      = rightName == null ? null : Path.Combine(ImgRelativePath, WebUtility.UrlEncode(rightName)),
                        Size     = pageRight.Bmp.Size
                    }
                },
                DiffImg = new Img
                {
                    Filename = diffName,
                    Src      = diffName == null ? null : Path.Combine(ImgRelativePath, WebUtility.UrlEncode(diffName)),
                    Size     = diff.Size
                },
                DiffMap = result.Map
            });

            return(areSame);
        }
        public virtual void testEqualImagesDiff()
        {
            ImageDiff diff = IMAGE_DIFFER.makeDiff(IMAGE_A_SMALL, IMAGE_A_SMALL);

            Assert.IsFalse(diff.hasDiff());
        }