Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / cc / layers / heads_up_display_layer_impl.cc
1 // Copyright 2012 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.
4
5 #include "cc/layers/heads_up_display_layer_impl.h"
6
7 #include <algorithm>
8 #include <vector>
9
10 #include "base/debug/trace_event.h"
11 #include "base/debug/trace_event_argument.h"
12 #include "base/strings/stringprintf.h"
13 #include "cc/debug/debug_colors.h"
14 #include "cc/debug/frame_rate_counter.h"
15 #include "cc/debug/paint_time_counter.h"
16 #include "cc/output/begin_frame_args.h"
17 #include "cc/output/renderer.h"
18 #include "cc/quads/texture_draw_quad.h"
19 #include "cc/resources/memory_history.h"
20 #include "cc/trees/layer_tree_impl.h"
21 #include "skia/ext/platform_canvas.h"
22 #include "third_party/khronos/GLES2/gl2.h"
23 #include "third_party/khronos/GLES2/gl2ext.h"
24 #include "third_party/skia/include/core/SkBitmap.h"
25 #include "third_party/skia/include/core/SkPaint.h"
26 #include "third_party/skia/include/core/SkTypeface.h"
27 #include "third_party/skia/include/effects/SkColorMatrixFilter.h"
28 #include "ui/gfx/geometry/point.h"
29 #include "ui/gfx/geometry/size.h"
30
31 namespace cc {
32
33 static inline SkPaint CreatePaint() {
34   SkPaint paint;
35 #if (SK_R32_SHIFT || SK_B32_SHIFT != 16)
36   // The SkCanvas is in RGBA but the shader is expecting BGRA, so we need to
37   // swizzle our colors when drawing to the SkCanvas.
38   SkColorMatrix swizzle_matrix;
39   for (int i = 0; i < 20; ++i)
40     swizzle_matrix.fMat[i] = 0;
41   swizzle_matrix.fMat[0 + 5 * 2] = 1;
42   swizzle_matrix.fMat[1 + 5 * 1] = 1;
43   swizzle_matrix.fMat[2 + 5 * 0] = 1;
44   swizzle_matrix.fMat[3 + 5 * 3] = 1;
45
46   skia::RefPtr<SkColorMatrixFilter> filter =
47       skia::AdoptRef(SkColorMatrixFilter::Create(swizzle_matrix));
48   paint.setColorFilter(filter.get());
49 #endif
50   return paint;
51 }
52
53 HeadsUpDisplayLayerImpl::Graph::Graph(double indicator_value,
54                                       double start_upper_bound)
55     : value(0.0),
56       min(0.0),
57       max(0.0),
58       current_upper_bound(start_upper_bound),
59       default_upper_bound(start_upper_bound),
60       indicator(indicator_value) {}
61
62 double HeadsUpDisplayLayerImpl::Graph::UpdateUpperBound() {
63   double target_upper_bound = std::max(max, default_upper_bound);
64   current_upper_bound += (target_upper_bound - current_upper_bound) * 0.5;
65   return current_upper_bound;
66 }
67
68 HeadsUpDisplayLayerImpl::HeadsUpDisplayLayerImpl(LayerTreeImpl* tree_impl,
69                                                  int id)
70     : LayerImpl(tree_impl, id),
71       typeface_(skia::AdoptRef(
72           SkTypeface::CreateFromName("monospace", SkTypeface::kBold))),
73       fps_graph_(60.0, 80.0),
74       paint_time_graph_(16.0, 48.0),
75       fade_step_(0) {}
76
77 HeadsUpDisplayLayerImpl::~HeadsUpDisplayLayerImpl() {}
78
79 scoped_ptr<LayerImpl> HeadsUpDisplayLayerImpl::CreateLayerImpl(
80     LayerTreeImpl* tree_impl) {
81   return HeadsUpDisplayLayerImpl::Create(tree_impl, id());
82 }
83
84 void HeadsUpDisplayLayerImpl::AcquireResource(
85     ResourceProvider* resource_provider) {
86   for (ScopedPtrVector<ScopedResource>::iterator it = resources_.begin();
87        it != resources_.end();
88        ++it) {
89     if (!resource_provider->InUseByConsumer((*it)->id())) {
90       resources_.swap(it, resources_.end() - 1);
91       return;
92     }
93   }
94
95   scoped_ptr<ScopedResource> resource =
96       ScopedResource::Create(resource_provider);
97   resource->Allocate(
98       content_bounds(), ResourceProvider::TextureHintImmutable, RGBA_8888);
99   resources_.push_back(resource.Pass());
100 }
101
102 class ResourceSizeIsEqualTo {
103  public:
104   explicit ResourceSizeIsEqualTo(const gfx::Size& size_)
105       : compare_size_(size_) {}
106
107   bool operator()(const ScopedResource* resource) {
108     return resource->size() == compare_size_;
109   }
110
111  private:
112   const gfx::Size compare_size_;
113 };
114
115 void HeadsUpDisplayLayerImpl::ReleaseUnmatchedSizeResources(
116     ResourceProvider* resource_provider) {
117   ScopedPtrVector<ScopedResource>::iterator it_erase =
118       resources_.partition(ResourceSizeIsEqualTo(content_bounds()));
119   resources_.erase(it_erase, resources_.end());
120 }
121
122 bool HeadsUpDisplayLayerImpl::WillDraw(DrawMode draw_mode,
123                                        ResourceProvider* resource_provider) {
124   if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE)
125     return false;
126
127   ReleaseUnmatchedSizeResources(resource_provider);
128   AcquireResource(resource_provider);
129   return LayerImpl::WillDraw(draw_mode, resource_provider);
130 }
131
132 void HeadsUpDisplayLayerImpl::AppendQuads(
133     RenderPass* render_pass,
134     const Occlusion& occlusion_in_content_space,
135     AppendQuadsData* append_quads_data) {
136   if (!resources_.back()->id())
137     return;
138
139   SharedQuadState* shared_quad_state =
140       render_pass->CreateAndAppendSharedQuadState();
141   PopulateSharedQuadState(shared_quad_state);
142
143   gfx::Rect quad_rect(content_bounds());
144   gfx::Rect opaque_rect(contents_opaque() ? quad_rect : gfx::Rect());
145   gfx::Rect visible_quad_rect(quad_rect);
146   bool premultiplied_alpha = true;
147   gfx::PointF uv_top_left(0.f, 0.f);
148   gfx::PointF uv_bottom_right(1.f, 1.f);
149   const float vertex_opacity[] = { 1.f, 1.f, 1.f, 1.f };
150   bool flipped = false;
151   TextureDrawQuad* quad =
152       render_pass->CreateAndAppendDrawQuad<TextureDrawQuad>();
153   quad->SetNew(shared_quad_state,
154                quad_rect,
155                opaque_rect,
156                visible_quad_rect,
157                resources_.back()->id(),
158                premultiplied_alpha,
159                uv_top_left,
160                uv_bottom_right,
161                SK_ColorTRANSPARENT,
162                vertex_opacity,
163                flipped);
164 }
165
166 void HeadsUpDisplayLayerImpl::UpdateHudTexture(
167     DrawMode draw_mode,
168     ResourceProvider* resource_provider) {
169   if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE || !resources_.back()->id())
170     return;
171
172   SkISize canvas_size;
173   if (hud_canvas_)
174     canvas_size = hud_canvas_->getDeviceSize();
175   else
176     canvas_size.set(0, 0);
177
178   if (canvas_size.width() != content_bounds().width() ||
179       canvas_size.height() != content_bounds().height() || !hud_canvas_) {
180     TRACE_EVENT0("cc", "ResizeHudCanvas");
181     bool opaque = false;
182     hud_canvas_ = make_scoped_ptr(skia::CreateBitmapCanvas(
183         content_bounds().width(), content_bounds().height(), opaque));
184   }
185
186   UpdateHudContents();
187
188   {
189     TRACE_EVENT0("cc", "DrawHudContents");
190     hud_canvas_->clear(SkColorSetARGB(0, 0, 0, 0));
191     hud_canvas_->save();
192     hud_canvas_->scale(contents_scale_x(), contents_scale_y());
193
194     DrawHudContents(hud_canvas_.get());
195
196     hud_canvas_->restore();
197   }
198
199   TRACE_EVENT0("cc", "UploadHudTexture");
200   SkImageInfo info;
201   size_t row_bytes = 0;
202   const void* pixels = hud_canvas_->peekPixels(&info, &row_bytes);
203   DCHECK(pixels);
204   gfx::Rect content_rect(content_bounds());
205   DCHECK(info.colorType() == kN32_SkColorType);
206   resource_provider->SetPixels(resources_.back()->id(),
207                                static_cast<const uint8_t*>(pixels),
208                                content_rect,
209                                content_rect,
210                                gfx::Vector2d());
211 }
212
213 void HeadsUpDisplayLayerImpl::ReleaseResources() {
214   resources_.clear();
215 }
216
217 void HeadsUpDisplayLayerImpl::UpdateHudContents() {
218   const LayerTreeDebugState& debug_state = layer_tree_impl()->debug_state();
219
220   // Don't update numbers every frame so text is readable.
221   base::TimeTicks now = layer_tree_impl()->CurrentBeginFrameArgs().frame_time;
222   if (base::TimeDelta(now - time_of_last_graph_update_).InSecondsF() > 0.25f) {
223     time_of_last_graph_update_ = now;
224
225     if (debug_state.show_fps_counter) {
226       FrameRateCounter* fps_counter = layer_tree_impl()->frame_rate_counter();
227       fps_graph_.value = fps_counter->GetAverageFPS();
228       fps_counter->GetMinAndMaxFPS(&fps_graph_.min, &fps_graph_.max);
229     }
230
231     if (debug_state.continuous_painting) {
232       PaintTimeCounter* paint_time_counter =
233           layer_tree_impl()->paint_time_counter();
234       base::TimeDelta latest, min, max;
235
236       if (paint_time_counter->End())
237         latest = **paint_time_counter->End();
238       paint_time_counter->GetMinAndMaxPaintTime(&min, &max);
239
240       paint_time_graph_.value = latest.InMillisecondsF();
241       paint_time_graph_.min = min.InMillisecondsF();
242       paint_time_graph_.max = max.InMillisecondsF();
243     }
244
245     if (debug_state.ShowMemoryStats()) {
246       MemoryHistory* memory_history = layer_tree_impl()->memory_history();
247       if (memory_history->End())
248         memory_entry_ = **memory_history->End();
249       else
250         memory_entry_ = MemoryHistory::Entry();
251     }
252   }
253
254   fps_graph_.UpdateUpperBound();
255   paint_time_graph_.UpdateUpperBound();
256 }
257
258 void HeadsUpDisplayLayerImpl::DrawHudContents(SkCanvas* canvas) {
259   const LayerTreeDebugState& debug_state = layer_tree_impl()->debug_state();
260
261   if (debug_state.ShowHudRects()) {
262     DrawDebugRects(canvas, layer_tree_impl()->debug_rect_history());
263     if (IsAnimatingHUDContents()) {
264       layer_tree_impl()->SetNeedsRedraw();
265     }
266   }
267
268   SkRect area = SkRect::MakeEmpty();
269   if (debug_state.continuous_painting) {
270     area = DrawPaintTimeDisplay(
271         canvas, layer_tree_impl()->paint_time_counter(), 0, 0);
272   } else if (debug_state.show_fps_counter) {
273     // Don't show the FPS display when continuous painting is enabled, because
274     // it would show misleading numbers.
275     area =
276         DrawFPSDisplay(canvas, layer_tree_impl()->frame_rate_counter(), 0, 0);
277   }
278
279   if (debug_state.ShowMemoryStats())
280     DrawMemoryDisplay(canvas, 0, area.bottom(), SkMaxScalar(area.width(), 150));
281 }
282
283 void HeadsUpDisplayLayerImpl::DrawText(SkCanvas* canvas,
284                                        SkPaint* paint,
285                                        const std::string& text,
286                                        SkPaint::Align align,
287                                        int size,
288                                        int x,
289                                        int y) const {
290   const bool anti_alias = paint->isAntiAlias();
291   paint->setAntiAlias(true);
292
293   paint->setTextSize(size);
294   paint->setTextAlign(align);
295   paint->setTypeface(typeface_.get());
296   canvas->drawText(text.c_str(), text.length(), x, y, *paint);
297
298   paint->setAntiAlias(anti_alias);
299 }
300
301 void HeadsUpDisplayLayerImpl::DrawText(SkCanvas* canvas,
302                                        SkPaint* paint,
303                                        const std::string& text,
304                                        SkPaint::Align align,
305                                        int size,
306                                        const SkPoint& pos) const {
307   DrawText(canvas, paint, text, align, size, pos.x(), pos.y());
308 }
309
310 void HeadsUpDisplayLayerImpl::DrawGraphBackground(SkCanvas* canvas,
311                                                   SkPaint* paint,
312                                                   const SkRect& bounds) const {
313   paint->setColor(DebugColors::HUDBackgroundColor());
314   canvas->drawRect(bounds, *paint);
315 }
316
317 void HeadsUpDisplayLayerImpl::DrawGraphLines(SkCanvas* canvas,
318                                              SkPaint* paint,
319                                              const SkRect& bounds,
320                                              const Graph& graph) const {
321   // Draw top and bottom line.
322   paint->setColor(DebugColors::HUDSeparatorLineColor());
323   canvas->drawLine(bounds.left(),
324                    bounds.top() - 1,
325                    bounds.right(),
326                    bounds.top() - 1,
327                    *paint);
328   canvas->drawLine(
329       bounds.left(), bounds.bottom(), bounds.right(), bounds.bottom(), *paint);
330
331   // Draw indicator line (additive blend mode to increase contrast when drawn on
332   // top of graph).
333   paint->setColor(DebugColors::HUDIndicatorLineColor());
334   paint->setXfermodeMode(SkXfermode::kPlus_Mode);
335   const double indicator_top =
336       bounds.height() * (1.0 - graph.indicator / graph.current_upper_bound) -
337       1.0;
338   canvas->drawLine(bounds.left(),
339                    bounds.top() + indicator_top,
340                    bounds.right(),
341                    bounds.top() + indicator_top,
342                    *paint);
343   paint->setXfermode(nullptr);
344 }
345
346 SkRect HeadsUpDisplayLayerImpl::DrawFPSDisplay(
347     SkCanvas* canvas,
348     const FrameRateCounter* fps_counter,
349     int right,
350     int top) const {
351   const int kPadding = 4;
352   const int kGap = 6;
353
354   const int kFontHeight = 15;
355
356   const int kGraphWidth = fps_counter->time_stamp_history_size() - 2;
357   const int kGraphHeight = 40;
358
359   const int kHistogramWidth = 37;
360
361   int width = kGraphWidth + kHistogramWidth + 4 * kPadding;
362   int height = kFontHeight + kGraphHeight + 4 * kPadding + 2;
363   int left = bounds().width() - width - right;
364   SkRect area = SkRect::MakeXYWH(left, top, width, height);
365
366   SkPaint paint = CreatePaint();
367   DrawGraphBackground(canvas, &paint, area);
368
369   SkRect text_bounds =
370       SkRect::MakeXYWH(left + kPadding,
371                        top + kPadding,
372                        kGraphWidth + kHistogramWidth + kGap + 2,
373                        kFontHeight);
374   SkRect graph_bounds = SkRect::MakeXYWH(left + kPadding,
375                                          text_bounds.bottom() + 2 * kPadding,
376                                          kGraphWidth,
377                                          kGraphHeight);
378   SkRect histogram_bounds = SkRect::MakeXYWH(graph_bounds.right() + kGap,
379                                              graph_bounds.top(),
380                                              kHistogramWidth,
381                                              kGraphHeight);
382
383   const std::string value_text =
384       base::StringPrintf("FPS:%5.1f", fps_graph_.value);
385   const std::string min_max_text =
386       base::StringPrintf("%.0f-%.0f", fps_graph_.min, fps_graph_.max);
387
388   VLOG(1) << value_text;
389
390   paint.setColor(DebugColors::FPSDisplayTextAndGraphColor());
391   DrawText(canvas,
392            &paint,
393            value_text,
394            SkPaint::kLeft_Align,
395            kFontHeight,
396            text_bounds.left(),
397            text_bounds.bottom());
398   DrawText(canvas,
399            &paint,
400            min_max_text,
401            SkPaint::kRight_Align,
402            kFontHeight,
403            text_bounds.right(),
404            text_bounds.bottom());
405
406   DrawGraphLines(canvas, &paint, graph_bounds, fps_graph_);
407
408   // Collect graph and histogram data.
409   SkPath path;
410
411   const int kHistogramSize = 20;
412   double histogram[kHistogramSize] = { 1.0 };
413   double max_bucket_value = 1.0;
414
415   for (FrameRateCounter::RingBufferType::Iterator it = --fps_counter->end(); it;
416        --it) {
417     base::TimeDelta delta = fps_counter->RecentFrameInterval(it.index() + 1);
418
419     // Skip this particular instantaneous frame rate if it is not likely to have
420     // been valid.
421     if (!fps_counter->IsBadFrameInterval(delta)) {
422       double fps = 1.0 / delta.InSecondsF();
423
424       // Clamp the FPS to the range we want to plot visually.
425       double p = fps / fps_graph_.current_upper_bound;
426       if (p > 1.0)
427         p = 1.0;
428
429       // Plot this data point.
430       SkPoint cur =
431           SkPoint::Make(graph_bounds.left() + it.index(),
432                         graph_bounds.bottom() - p * graph_bounds.height());
433       if (path.isEmpty())
434         path.moveTo(cur);
435       else
436         path.lineTo(cur);
437
438       // Use the fps value to find the right bucket in the histogram.
439       int bucket_index = floor(p * (kHistogramSize - 1));
440
441       // Add the delta time to take the time spent at that fps rate into
442       // account.
443       histogram[bucket_index] += delta.InSecondsF();
444       max_bucket_value = std::max(histogram[bucket_index], max_bucket_value);
445     }
446   }
447
448   // Draw FPS histogram.
449   paint.setColor(DebugColors::HUDSeparatorLineColor());
450   canvas->drawLine(histogram_bounds.left() - 1,
451                    histogram_bounds.top() - 1,
452                    histogram_bounds.left() - 1,
453                    histogram_bounds.bottom() + 1,
454                    paint);
455   canvas->drawLine(histogram_bounds.right() + 1,
456                    histogram_bounds.top() - 1,
457                    histogram_bounds.right() + 1,
458                    histogram_bounds.bottom() + 1,
459                    paint);
460
461   paint.setColor(DebugColors::FPSDisplayTextAndGraphColor());
462   const double bar_height = histogram_bounds.height() / kHistogramSize;
463
464   for (int i = kHistogramSize - 1; i >= 0; --i) {
465     if (histogram[i] > 0) {
466       double bar_width =
467           histogram[i] / max_bucket_value * histogram_bounds.width();
468       canvas->drawRect(
469           SkRect::MakeXYWH(histogram_bounds.left(),
470                            histogram_bounds.bottom() - (i + 1) * bar_height,
471                            bar_width,
472                            1),
473           paint);
474     }
475   }
476
477   // Draw FPS graph.
478   paint.setAntiAlias(true);
479   paint.setStyle(SkPaint::kStroke_Style);
480   paint.setStrokeWidth(1);
481   canvas->drawPath(path, paint);
482
483   return area;
484 }
485
486 SkRect HeadsUpDisplayLayerImpl::DrawMemoryDisplay(SkCanvas* canvas,
487                                                   int right,
488                                                   int top,
489                                                   int width) const {
490   if (!memory_entry_.total_bytes_used)
491     return SkRect::MakeEmpty();
492
493   const int kPadding = 4;
494   const int kFontHeight = 13;
495
496   const int height = 3 * kFontHeight + 4 * kPadding;
497   const int left = bounds().width() - width - right;
498   const SkRect area = SkRect::MakeXYWH(left, top, width, height);
499
500   const double kMegabyte = 1024.0 * 1024.0;
501
502   SkPaint paint = CreatePaint();
503   DrawGraphBackground(canvas, &paint, area);
504
505   SkPoint title_pos = SkPoint::Make(left + kPadding, top + kFontHeight);
506   SkPoint stat1_pos = SkPoint::Make(left + width - kPadding - 1,
507                                     top + kPadding + 2 * kFontHeight);
508   SkPoint stat2_pos = SkPoint::Make(left + width - kPadding - 1,
509                                     top + 2 * kPadding + 3 * kFontHeight);
510
511   paint.setColor(DebugColors::MemoryDisplayTextColor());
512   DrawText(canvas,
513            &paint,
514            "GPU memory",
515            SkPaint::kLeft_Align,
516            kFontHeight,
517            title_pos);
518
519   std::string text = base::StringPrintf(
520       "%6.1f MB used", memory_entry_.total_bytes_used / kMegabyte);
521   DrawText(canvas, &paint, text, SkPaint::kRight_Align, kFontHeight, stat1_pos);
522
523   if (!memory_entry_.had_enough_memory)
524     paint.setColor(SK_ColorRED);
525   text = base::StringPrintf("%6.1f MB max ",
526                             memory_entry_.total_budget_in_bytes / kMegabyte);
527   DrawText(canvas, &paint, text, SkPaint::kRight_Align, kFontHeight, stat2_pos);
528
529   return area;
530 }
531
532 SkRect HeadsUpDisplayLayerImpl::DrawPaintTimeDisplay(
533     SkCanvas* canvas,
534     const PaintTimeCounter* paint_time_counter,
535     int right,
536     int top) const {
537   const int kPadding = 4;
538   const int kFontHeight = 15;
539
540   const int kGraphWidth = paint_time_counter->HistorySize();
541   const int kGraphHeight = 40;
542
543   const int width = kGraphWidth + 2 * kPadding;
544   const int height =
545       kFontHeight + kGraphHeight + 4 * kPadding + 2 + kFontHeight + kPadding;
546   const int left = bounds().width() - width - right;
547
548   const SkRect area = SkRect::MakeXYWH(left, top, width, height);
549
550   SkPaint paint = CreatePaint();
551   DrawGraphBackground(canvas, &paint, area);
552
553   SkRect text_bounds = SkRect::MakeXYWH(
554       left + kPadding, top + kPadding, kGraphWidth, kFontHeight);
555   SkRect text_bounds2 = SkRect::MakeXYWH(left + kPadding,
556                                          text_bounds.bottom() + kPadding,
557                                          kGraphWidth,
558                                          kFontHeight);
559   SkRect graph_bounds = SkRect::MakeXYWH(left + kPadding,
560                                          text_bounds2.bottom() + 2 * kPadding,
561                                          kGraphWidth,
562                                          kGraphHeight);
563
564   const std::string value_text =
565       base::StringPrintf("%.1f", paint_time_graph_.value);
566   const std::string min_max_text = base::StringPrintf(
567       "%.1f-%.1f", paint_time_graph_.min, paint_time_graph_.max);
568
569   paint.setColor(DebugColors::PaintTimeDisplayTextAndGraphColor());
570   DrawText(canvas, &paint, "Compositor frame time (ms)", SkPaint::kLeft_Align,
571            kFontHeight, text_bounds.left(), text_bounds.bottom());
572   DrawText(canvas,
573            &paint,
574            value_text,
575            SkPaint::kLeft_Align,
576            kFontHeight,
577            text_bounds2.left(),
578            text_bounds2.bottom());
579   DrawText(canvas,
580            &paint,
581            min_max_text,
582            SkPaint::kRight_Align,
583            kFontHeight,
584            text_bounds2.right(),
585            text_bounds2.bottom());
586
587   paint.setColor(DebugColors::PaintTimeDisplayTextAndGraphColor());
588   for (PaintTimeCounter::RingBufferType::Iterator it =
589            paint_time_counter->End();
590        it;
591        --it) {
592     double pt = it->InMillisecondsF();
593
594     if (pt == 0.0)
595       continue;
596
597     double p = pt / paint_time_graph_.current_upper_bound;
598     if (p > 1.0)
599       p = 1.0;
600
601     canvas->drawRect(
602         SkRect::MakeXYWH(graph_bounds.left() + it.index(),
603                          graph_bounds.bottom() - p * graph_bounds.height(),
604                          1,
605                          p * graph_bounds.height()),
606         paint);
607   }
608
609   DrawGraphLines(canvas, &paint, graph_bounds, paint_time_graph_);
610
611   return area;
612 }
613
614 void HeadsUpDisplayLayerImpl::DrawDebugRect(
615     SkCanvas* canvas,
616     SkPaint* paint,
617     const DebugRect& rect,
618     SkColor stroke_color,
619     SkColor fill_color,
620     float stroke_width,
621     const std::string& label_text) const {
622   gfx::Rect debug_layer_rect = gfx::ScaleToEnclosingRect(
623       rect.rect, 1.0 / contents_scale_x(), 1.0 / contents_scale_y());
624   SkIRect sk_rect = RectToSkIRect(debug_layer_rect);
625   paint->setColor(fill_color);
626   paint->setStyle(SkPaint::kFill_Style);
627   canvas->drawIRect(sk_rect, *paint);
628
629   paint->setColor(stroke_color);
630   paint->setStyle(SkPaint::kStroke_Style);
631   paint->setStrokeWidth(SkFloatToScalar(stroke_width));
632   canvas->drawIRect(sk_rect, *paint);
633
634   if (label_text.length()) {
635     const int kFontHeight = 12;
636     const int kPadding = 3;
637
638     // The debug_layer_rect may be huge, and converting to a floating point may
639     // be lossy, so intersect with the HUD layer bounds first to prevent that.
640     gfx::Rect clip_rect = debug_layer_rect;
641     clip_rect.Intersect(gfx::Rect(content_bounds()));
642     SkRect sk_clip_rect = RectToSkRect(clip_rect);
643
644     canvas->save();
645     canvas->clipRect(sk_clip_rect);
646     canvas->translate(sk_clip_rect.x(), sk_clip_rect.y());
647
648     SkPaint label_paint = CreatePaint();
649     label_paint.setTextSize(kFontHeight);
650     label_paint.setTypeface(typeface_.get());
651     label_paint.setColor(stroke_color);
652
653     const SkScalar label_text_width =
654         label_paint.measureText(label_text.c_str(), label_text.length());
655     canvas->drawRect(SkRect::MakeWH(label_text_width + 2 * kPadding,
656                                     kFontHeight + 2 * kPadding),
657                      label_paint);
658
659     label_paint.setAntiAlias(true);
660     label_paint.setColor(SkColorSetARGB(255, 50, 50, 50));
661     canvas->drawText(label_text.c_str(),
662                      label_text.length(),
663                      kPadding,
664                      kFontHeight * 0.8f + kPadding,
665                      label_paint);
666
667     canvas->restore();
668   }
669 }
670
671 void HeadsUpDisplayLayerImpl::DrawDebugRects(
672     SkCanvas* canvas,
673     DebugRectHistory* debug_rect_history) {
674   SkPaint paint = CreatePaint();
675
676   const std::vector<DebugRect>& debug_rects = debug_rect_history->debug_rects();
677   std::vector<DebugRect> new_paint_rects;
678
679   for (size_t i = 0; i < debug_rects.size(); ++i) {
680     SkColor stroke_color = 0;
681     SkColor fill_color = 0;
682     float stroke_width = 0.f;
683     std::string label_text;
684
685     switch (debug_rects[i].type) {
686       case PAINT_RECT_TYPE:
687         new_paint_rects.push_back(debug_rects[i]);
688         continue;
689       case PROPERTY_CHANGED_RECT_TYPE:
690         stroke_color = DebugColors::PropertyChangedRectBorderColor();
691         fill_color = DebugColors::PropertyChangedRectFillColor();
692         stroke_width = DebugColors::PropertyChangedRectBorderWidth();
693         break;
694       case SURFACE_DAMAGE_RECT_TYPE:
695         stroke_color = DebugColors::SurfaceDamageRectBorderColor();
696         fill_color = DebugColors::SurfaceDamageRectFillColor();
697         stroke_width = DebugColors::SurfaceDamageRectBorderWidth();
698         break;
699       case REPLICA_SCREEN_SPACE_RECT_TYPE:
700         stroke_color = DebugColors::ScreenSpaceSurfaceReplicaRectBorderColor();
701         fill_color = DebugColors::ScreenSpaceSurfaceReplicaRectFillColor();
702         stroke_width = DebugColors::ScreenSpaceSurfaceReplicaRectBorderWidth();
703         break;
704       case SCREEN_SPACE_RECT_TYPE:
705         stroke_color = DebugColors::ScreenSpaceLayerRectBorderColor();
706         fill_color = DebugColors::ScreenSpaceLayerRectFillColor();
707         stroke_width = DebugColors::ScreenSpaceLayerRectBorderWidth();
708         break;
709       case OCCLUDING_RECT_TYPE:
710         stroke_color = DebugColors::OccludingRectBorderColor();
711         fill_color = DebugColors::OccludingRectFillColor();
712         stroke_width = DebugColors::OccludingRectBorderWidth();
713         break;
714       case NONOCCLUDING_RECT_TYPE:
715         stroke_color = DebugColors::NonOccludingRectBorderColor();
716         fill_color = DebugColors::NonOccludingRectFillColor();
717         stroke_width = DebugColors::NonOccludingRectBorderWidth();
718         break;
719       case TOUCH_EVENT_HANDLER_RECT_TYPE:
720         stroke_color = DebugColors::TouchEventHandlerRectBorderColor();
721         fill_color = DebugColors::TouchEventHandlerRectFillColor();
722         stroke_width = DebugColors::TouchEventHandlerRectBorderWidth();
723         label_text = "touch event listener";
724         break;
725       case WHEEL_EVENT_HANDLER_RECT_TYPE:
726         stroke_color = DebugColors::WheelEventHandlerRectBorderColor();
727         fill_color = DebugColors::WheelEventHandlerRectFillColor();
728         stroke_width = DebugColors::WheelEventHandlerRectBorderWidth();
729         label_text = "mousewheel event listener";
730         break;
731       case SCROLL_EVENT_HANDLER_RECT_TYPE:
732         stroke_color = DebugColors::ScrollEventHandlerRectBorderColor();
733         fill_color = DebugColors::ScrollEventHandlerRectFillColor();
734         stroke_width = DebugColors::ScrollEventHandlerRectBorderWidth();
735         label_text = "scroll event listener";
736         break;
737       case NON_FAST_SCROLLABLE_RECT_TYPE:
738         stroke_color = DebugColors::NonFastScrollableRectBorderColor();
739         fill_color = DebugColors::NonFastScrollableRectFillColor();
740         stroke_width = DebugColors::NonFastScrollableRectBorderWidth();
741         label_text = "repaints on scroll";
742         break;
743       case ANIMATION_BOUNDS_RECT_TYPE:
744         stroke_color = DebugColors::LayerAnimationBoundsBorderColor();
745         fill_color = DebugColors::LayerAnimationBoundsFillColor();
746         stroke_width = DebugColors::LayerAnimationBoundsBorderWidth();
747         label_text = "animation bounds";
748         break;
749     }
750
751     DrawDebugRect(canvas,
752                   &paint,
753                   debug_rects[i],
754                   stroke_color,
755                   fill_color,
756                   stroke_width,
757                   label_text);
758   }
759
760   if (new_paint_rects.size()) {
761     paint_rects_.swap(new_paint_rects);
762     fade_step_ = DebugColors::kFadeSteps;
763   }
764   if (fade_step_ > 0) {
765     fade_step_--;
766     for (size_t i = 0; i < paint_rects_.size(); ++i) {
767       DrawDebugRect(canvas,
768                     &paint,
769                     paint_rects_[i],
770                     DebugColors::PaintRectBorderColor(fade_step_),
771                     DebugColors::PaintRectFillColor(fade_step_),
772                     DebugColors::PaintRectBorderWidth(),
773                     "");
774     }
775   }
776 }
777
778 const char* HeadsUpDisplayLayerImpl::LayerTypeAsString() const {
779   return "cc::HeadsUpDisplayLayerImpl";
780 }
781
782 void HeadsUpDisplayLayerImpl::AsValueInto(
783     base::debug::TracedValue* dict) const {
784   LayerImpl::AsValueInto(dict);
785   dict->SetString("layer_name", "Heads Up Display Layer");
786 }
787
788 }  // namespace cc