Remove workaround for monospace font resources.
[chromium-blink-merge.git] / tools / imagediff / image_diff.cc
blob294e2e3dbd87f20de0812324ded6db34f7e90fe2
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // This file input format is based loosely on
6 // Tools/DumpRenderTree/ImageDiff.m
8 // The exact format of this tool's output to stdout is important, to match
9 // what the run-webkit-tests script expects.
11 #include <algorithm>
12 #include <vector>
13 #include <string>
14 #include <iostream>
16 #include "base/basictypes.h"
17 #include "base/command_line.h"
18 #include "base/file_path.h"
19 #include "base/file_util.h"
20 #include "base/logging.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/process_util.h"
23 #include "base/string_util.h"
24 #include "base/utf_string_conversions.h"
25 #include "ui/gfx/codec/png_codec.h"
26 #include "ui/gfx/size.h"
28 #if defined(OS_WIN)
29 #include "windows.h"
30 #endif
32 // Causes the app to remain open, waiting for pairs of filenames on stdin.
33 // The caller is then responsible for terminating this app.
34 static const char kOptionPollStdin[] = "use-stdin";
35 static const char kOptionGenerateDiff[] = "diff";
37 // Return codes used by this utility.
38 static const int kStatusSame = 0;
39 static const int kStatusDifferent = 1;
40 static const int kStatusError = 2;
42 // Color codes.
43 static const uint32 RGBA_RED = 0x000000ff;
44 static const uint32 RGBA_ALPHA = 0xff000000;
46 class Image {
47 public:
48 Image() : w_(0), h_(0) {
51 Image(const Image& image)
52 : w_(image.w_),
53 h_(image.h_),
54 data_(image.data_) {
57 bool has_image() const {
58 return w_ > 0 && h_ > 0;
61 int w() const {
62 return w_;
65 int h() const {
66 return h_;
69 const unsigned char* data() const {
70 return &data_.front();
73 // Creates the image from stdin with the given data length. On success, it
74 // will return true. On failure, no other methods should be accessed.
75 bool CreateFromStdin(size_t byte_length) {
76 if (byte_length == 0)
77 return false;
79 scoped_array<unsigned char> source(new unsigned char[byte_length]);
80 if (fread(source.get(), 1, byte_length, stdin) != byte_length)
81 return false;
83 if (!gfx::PNGCodec::Decode(source.get(), byte_length,
84 gfx::PNGCodec::FORMAT_RGBA,
85 &data_, &w_, &h_)) {
86 Clear();
87 return false;
89 return true;
92 // Creates the image from the given filename on disk, and returns true on
93 // success.
94 bool CreateFromFilename(const FilePath& path) {
95 FILE* f = file_util::OpenFile(path, "rb");
96 if (!f)
97 return false;
99 std::vector<unsigned char> compressed;
100 const int buf_size = 1024;
101 unsigned char buf[buf_size];
102 size_t num_read = 0;
103 while ((num_read = fread(buf, 1, buf_size, f)) > 0) {
104 compressed.insert(compressed.end(), buf, buf + num_read);
107 file_util::CloseFile(f);
109 if (!gfx::PNGCodec::Decode(&compressed[0], compressed.size(),
110 gfx::PNGCodec::FORMAT_RGBA, &data_, &w_, &h_)) {
111 Clear();
112 return false;
114 return true;
117 void Clear() {
118 w_ = h_ = 0;
119 data_.clear();
122 // Returns the RGBA value of the pixel at the given location
123 uint32 pixel_at(int x, int y) const {
124 DCHECK(x >= 0 && x < w_);
125 DCHECK(y >= 0 && y < h_);
126 return *reinterpret_cast<const uint32*>(&(data_[(y * w_ + x) * 4]));
129 void set_pixel_at(int x, int y, uint32 color) const {
130 DCHECK(x >= 0 && x < w_);
131 DCHECK(y >= 0 && y < h_);
132 void* addr = &const_cast<unsigned char*>(&data_.front())[(y * w_ + x) * 4];
133 *reinterpret_cast<uint32*>(addr) = color;
136 private:
137 // pixel dimensions of the image
138 int w_, h_;
140 std::vector<unsigned char> data_;
143 float PercentageDifferent(const Image& baseline, const Image& actual) {
144 int w = std::min(baseline.w(), actual.w());
145 int h = std::min(baseline.h(), actual.h());
147 // compute pixels different in the overlap
148 int pixels_different = 0;
149 for (int y = 0; y < h; y++) {
150 for (int x = 0; x < w; x++) {
151 if (baseline.pixel_at(x, y) != actual.pixel_at(x, y))
152 pixels_different++;
156 // count pixels that are a difference in size as also being different
157 int max_w = std::max(baseline.w(), actual.w());
158 int max_h = std::max(baseline.h(), actual.h());
160 // ...pixels off the right side, but not including the lower right corner
161 pixels_different += (max_w - w) * h;
163 // ...pixels along the bottom, including the lower right corner
164 pixels_different += (max_h - h) * max_w;
166 // Like the WebKit ImageDiff tool, we define percentage different in terms
167 // of the size of the 'actual' bitmap.
168 float total_pixels = static_cast<float>(actual.w()) *
169 static_cast<float>(actual.h());
170 if (total_pixels == 0)
171 return 100.0f; // when the bitmap is empty, they are 100% different
172 return static_cast<float>(pixels_different) / total_pixels * 100;
175 void PrintHelp() {
176 fprintf(stderr,
177 "Usage:\n"
178 " image_diff <compare file> <reference file>\n"
179 " Compares two files on disk, returning 0 when they are the same\n"
180 " image_diff --use-stdin\n"
181 " Stays open reading pairs of filenames from stdin, comparing them,\n"
182 " and sending 0 to stdout when they are the same\n"
183 " image_diff --diff <compare file> <reference file> <output file>\n"
184 " Compares two files on disk, outputs an image that visualizes the"
185 " difference to <output file>\n");
186 /* For unfinished webkit-like-mode (see below)
187 "\n"
188 " image_diff -s\n"
189 " Reads stream input from stdin, should be EXACTLY of the format\n"
190 " \"Content-length: <byte length> <data>Content-length: ...\n"
191 " it will take as many file pairs as given, and will compare them as\n"
192 " (cmp_file, reference_file) pairs\n");
196 int CompareImages(const FilePath& file1, const FilePath& file2) {
197 Image actual_image;
198 Image baseline_image;
200 if (!actual_image.CreateFromFilename(file1)) {
201 fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n",
202 file1.value().c_str());
203 return kStatusError;
205 if (!baseline_image.CreateFromFilename(file2)) {
206 fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n",
207 file2.value().c_str());
208 return kStatusError;
211 float percent = PercentageDifferent(actual_image, baseline_image);
212 if (percent > 0.0) {
213 // failure: The WebKit version also writes the difference image to
214 // stdout, which seems excessive for our needs.
215 printf("diff: %01.2f%% failed\n", percent);
216 return kStatusDifferent;
219 // success
220 printf("diff: %01.2f%% passed\n", percent);
221 return kStatusSame;
223 /* Untested mode that acts like WebKit's image comparator. I wrote this but
224 decided it's too complicated. We may use it in the future if it looks useful
226 char buffer[2048];
227 while (fgets(buffer, sizeof(buffer), stdin)) {
229 if (strncmp("Content-length: ", buffer, 16) == 0) {
230 char* context;
231 strtok_s(buffer, " ", &context);
232 int image_size = strtol(strtok_s(NULL, " ", &context), NULL, 10);
234 bool success = false;
235 if (image_size > 0 && actual_image.has_image() == 0) {
236 if (!actual_image.CreateFromStdin(image_size)) {
237 fputs("Error, input image can't be decoded.\n", stderr);
238 return 1;
240 } else if (image_size > 0 && baseline_image.has_image() == 0) {
241 if (!baseline_image.CreateFromStdin(image_size)) {
242 fputs("Error, baseline image can't be decoded.\n", stderr);
243 return 1;
245 } else {
246 fputs("Error, image size must be specified.\n", stderr);
247 return 1;
251 if (actual_image.has_image() && baseline_image.has_image()) {
252 float percent = PercentageDifferent(actual_image, baseline_image);
253 if (percent > 0.0) {
254 // failure: The WebKit version also writes the difference image to
255 // stdout, which seems excessive for our needs.
256 printf("diff: %01.2f%% failed\n", percent);
257 } else {
258 // success
259 printf("diff: %01.2f%% passed\n", percent);
261 actual_image.Clear();
262 baseline_image.Clear();
265 fflush(stdout);
270 bool CreateImageDiff(const Image& image1, const Image& image2, Image* out) {
271 int w = std::min(image1.w(), image2.w());
272 int h = std::min(image1.h(), image2.h());
273 *out = Image(image1);
274 bool same = (image1.w() == image2.w()) && (image1.h() == image2.h());
276 // TODO(estade): do something with the extra pixels if the image sizes
277 // are different.
278 for (int y = 0; y < h; y++) {
279 for (int x = 0; x < w; x++) {
280 uint32 base_pixel = image1.pixel_at(x, y);
281 if (base_pixel != image2.pixel_at(x, y)) {
282 // Set differing pixels red.
283 out->set_pixel_at(x, y, RGBA_RED | RGBA_ALPHA);
284 same = false;
285 } else {
286 // Set same pixels as faded.
287 uint32 alpha = base_pixel & RGBA_ALPHA;
288 uint32 new_pixel = base_pixel - ((alpha / 2) & RGBA_ALPHA);
289 out->set_pixel_at(x, y, new_pixel);
294 return same;
297 int DiffImages(const FilePath& file1, const FilePath& file2,
298 const FilePath& out_file) {
299 Image actual_image;
300 Image baseline_image;
302 if (!actual_image.CreateFromFilename(file1)) {
303 fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n",
304 file1.value().c_str());
305 return kStatusError;
307 if (!baseline_image.CreateFromFilename(file2)) {
308 fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n",
309 file2.value().c_str());
310 return kStatusError;
313 Image diff_image;
314 bool same = CreateImageDiff(baseline_image, actual_image, &diff_image);
315 if (same)
316 return kStatusSame;
318 std::vector<unsigned char> png_encoding;
319 gfx::PNGCodec::Encode(diff_image.data(), gfx::PNGCodec::FORMAT_RGBA,
320 gfx::Size(diff_image.w(), diff_image.h()),
321 diff_image.w() * 4, false,
322 std::vector<gfx::PNGCodec::Comment>(), &png_encoding);
323 if (file_util::WriteFile(out_file,
324 reinterpret_cast<char*>(&png_encoding.front()), png_encoding.size()) < 0)
325 return kStatusError;
327 return kStatusDifferent;
330 // It isn't strictly correct to only support ASCII paths, but this
331 // program reads paths on stdin and the program that spawns it outputs
332 // paths as non-wide strings anyway.
333 FilePath FilePathFromASCII(const std::string& str) {
334 #if defined(OS_WIN)
335 return FilePath(ASCIIToWide(str));
336 #else
337 return FilePath(str);
338 #endif
341 int main(int argc, const char* argv[]) {
342 base::EnableTerminationOnHeapCorruption();
343 CommandLine::Init(argc, argv);
344 const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
345 if (parsed_command_line.HasSwitch(kOptionPollStdin)) {
346 // Watch stdin for filenames.
347 std::string stdin_buffer;
348 FilePath filename1;
349 while (std::getline(std::cin, stdin_buffer)) {
350 if (stdin_buffer.empty())
351 continue;
353 if (!filename1.empty()) {
354 // CompareImages writes results to stdout unless an error occurred.
355 FilePath filename2 = FilePathFromASCII(stdin_buffer);
356 if (CompareImages(filename1, filename2) == kStatusError)
357 printf("error\n");
358 fflush(stdout);
359 filename1 = FilePath();
360 } else {
361 // Save the first filename in another buffer and wait for the second
362 // filename to arrive via stdin.
363 filename1 = FilePathFromASCII(stdin_buffer);
366 return 0;
369 const std::vector<CommandLine::StringType>& args = parsed_command_line.args();
370 if (parsed_command_line.HasSwitch(kOptionGenerateDiff)) {
371 if (args.size() == 3) {
372 return DiffImages(FilePath(args[0]),
373 FilePath(args[1]),
374 FilePath(args[2]));
376 } else if (args.size() == 2) {
377 return CompareImages(FilePath(args[0]), FilePath(args[1]));
380 PrintHelp();
381 return kStatusError;