paint_manager.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. // Copyright (c) 2010 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. #include "pdf/paint_manager.h"
  5. #include <stddef.h>
  6. #include <stdint.h>
  7. #include <algorithm>
  8. #include <cmath>
  9. #include <utility>
  10. #include "base/auto_reset.h"
  11. #include "base/bind.h"
  12. #include "base/callback.h"
  13. #include "base/check.h"
  14. #include "base/location.h"
  15. #include "base/notreached.h"
  16. #include "base/threading/sequenced_task_runner_handle.h"
  17. #include "base/threading/thread_task_runner_handle.h"
  18. #include "pdf/paint_ready_rect.h"
  19. #include "third_party/skia/include/core/SkCanvas.h"
  20. #include "third_party/skia/include/core/SkImage.h"
  21. #include "third_party/skia/include/core/SkRect.h"
  22. #include "third_party/skia/include/core/SkRefCnt.h"
  23. #include "third_party/skia/include/core/SkSamplingOptions.h"
  24. #include "third_party/skia/include/core/SkSurface.h"
  25. #include "ui/gfx/blit.h"
  26. #include "ui/gfx/geometry/point.h"
  27. #include "ui/gfx/geometry/rect.h"
  28. #include "ui/gfx/geometry/size.h"
  29. #include "ui/gfx/geometry/skia_conversions.h"
  30. #include "ui/gfx/geometry/vector2d.h"
  31. #include "ui/gfx/geometry/vector2d_f.h"
  32. namespace chrome_pdf {
  33. PaintManager::PaintManager(Client* client) : client_(client) {
  34. DCHECK(client_);
  35. }
  36. PaintManager::~PaintManager() = default;
  37. // static
  38. gfx::Size PaintManager::GetNewContextSize(const gfx::Size& current_context_size,
  39. const gfx::Size& plugin_size) {
  40. // The amount of additional space in pixels to allocate to the right/bottom of
  41. // the context.
  42. constexpr int kBufferSize = 50;
  43. // Default to returning the same size.
  44. gfx::Size result = current_context_size;
  45. // The minimum size of the plugin before resizing the context to ensure we
  46. // aren't wasting too much memory. We deduct twice the kBufferSize from the
  47. // current context size which gives a threshhold that is kBufferSize below
  48. // the plugin size when the context size was last computed.
  49. gfx::Size min_size(
  50. std::max(current_context_size.width() - 2 * kBufferSize, 0),
  51. std::max(current_context_size.height() - 2 * kBufferSize, 0));
  52. // If the plugin size is bigger than the current context size, we need to
  53. // resize the context. If the plugin size is smaller than the current
  54. // context size by a given threshhold then resize the context so that we
  55. // aren't wasting too much memory.
  56. if (plugin_size.width() > current_context_size.width() ||
  57. plugin_size.height() > current_context_size.height() ||
  58. plugin_size.width() < min_size.width() ||
  59. plugin_size.height() < min_size.height()) {
  60. // Create a larger context than needed so that if we only resize by a
  61. // small margin, we don't need a new context.
  62. result = gfx::Size(plugin_size.width() + kBufferSize,
  63. plugin_size.height() + kBufferSize);
  64. }
  65. return result;
  66. }
  67. void PaintManager::SetSize(const gfx::Size& new_size, float device_scale) {
  68. if (GetEffectiveSize() == new_size &&
  69. GetEffectiveDeviceScale() == device_scale) {
  70. return;
  71. }
  72. has_pending_resize_ = true;
  73. pending_size_ = new_size;
  74. pending_device_scale_ = device_scale;
  75. view_size_changed_waiting_for_paint_ = true;
  76. Invalidate();
  77. }
  78. void PaintManager::SetTransform(float scale,
  79. const gfx::Point& origin,
  80. const gfx::Vector2d& translate,
  81. bool schedule_flush) {
  82. if (!surface_)
  83. return;
  84. if (scale <= 0.0f) {
  85. NOTREACHED();
  86. } else {
  87. // translate_with_origin = origin - scale * origin - translate
  88. gfx::Vector2dF translate_with_origin = origin.OffsetFromOrigin();
  89. translate_with_origin.Scale(1.0f - scale);
  90. translate_with_origin.Subtract(translate);
  91. // TODO(crbug.com/1263614): Should update be deferred until `Flush()`?
  92. client_->UpdateLayerTransform(scale, translate_with_origin);
  93. }
  94. if (!schedule_flush)
  95. return;
  96. if (flush_pending_) {
  97. flush_requested_ = true;
  98. return;
  99. }
  100. Flush();
  101. }
  102. void PaintManager::ClearTransform() {
  103. SetTransform(1.f, gfx::Point(), gfx::Vector2d(), false);
  104. }
  105. void PaintManager::Invalidate() {
  106. if (!surface_ && !has_pending_resize_)
  107. return;
  108. EnsureCallbackPending();
  109. aggregator_.InvalidateRect(gfx::Rect(GetEffectiveSize()));
  110. }
  111. void PaintManager::InvalidateRect(const gfx::Rect& rect) {
  112. DCHECK(!in_paint_);
  113. if (!surface_ && !has_pending_resize_)
  114. return;
  115. // Clip the rect to the device area.
  116. gfx::Rect clipped_rect =
  117. gfx::IntersectRects(rect, gfx::Rect(GetEffectiveSize()));
  118. if (clipped_rect.IsEmpty())
  119. return; // Nothing to do.
  120. EnsureCallbackPending();
  121. aggregator_.InvalidateRect(clipped_rect);
  122. }
  123. void PaintManager::ScrollRect(const gfx::Rect& clip_rect,
  124. const gfx::Vector2d& amount) {
  125. DCHECK(!in_paint_);
  126. if (!surface_ && !has_pending_resize_)
  127. return;
  128. EnsureCallbackPending();
  129. aggregator_.ScrollRect(clip_rect, amount);
  130. }
  131. gfx::Size PaintManager::GetEffectiveSize() const {
  132. return has_pending_resize_ ? pending_size_ : plugin_size_;
  133. }
  134. float PaintManager::GetEffectiveDeviceScale() const {
  135. return has_pending_resize_ ? pending_device_scale_ : device_scale_;
  136. }
  137. void PaintManager::EnsureCallbackPending() {
  138. // The best way for us to do the next update is to get a notification that
  139. // a previous one has completed. So if we're already waiting for one, we
  140. // don't have to do anything differently now.
  141. if (flush_pending_)
  142. return;
  143. // If no flush is pending, we need to do a manual call to get back to the
  144. // main thread. We may have one already pending, or we may need to schedule.
  145. if (manual_callback_pending_)
  146. return;
  147. base::ThreadTaskRunnerHandle::Get()->PostTask(
  148. FROM_HERE, base::BindOnce(&PaintManager::OnManualCallbackComplete,
  149. weak_factory_.GetWeakPtr()));
  150. manual_callback_pending_ = true;
  151. }
  152. void PaintManager::DoPaint() {
  153. base::AutoReset<bool> auto_reset_in_paint(&in_paint_, true);
  154. std::vector<PaintReadyRect> ready_rects;
  155. std::vector<gfx::Rect> pending_rects;
  156. DCHECK(aggregator_.HasPendingUpdate());
  157. // Apply any pending resize. Setting the graphics to this class must happen
  158. // before asking the plugin to paint in case it requests invalides or resizes.
  159. // However, the bind must not happen until afterward since we don't want to
  160. // have an unpainted device bound. The needs_binding flag tells us whether to
  161. // do this later.
  162. //
  163. // Note that `has_pending_resize_` will always be set on the first DoPaint().
  164. DCHECK(surface_ || has_pending_resize_);
  165. if (has_pending_resize_) {
  166. plugin_size_ = pending_size_;
  167. // Only create a new graphics context if the current context isn't big
  168. // enough or if it is far too big. This avoids creating a new context if
  169. // we only resize by a small amount.
  170. gfx::Size old_size = surface_
  171. ? gfx::Size(surface_->width(), surface_->height())
  172. : gfx::Size();
  173. gfx::Size new_size = GetNewContextSize(old_size, pending_size_);
  174. if (old_size != new_size || !surface_) {
  175. surface_ =
  176. SkSurface::MakeRasterN32Premul(new_size.width(), new_size.height());
  177. DCHECK(surface_);
  178. // TODO(crbug.com/1317832): Can we guarantee repainting some other way?
  179. client_->InvalidatePluginContainer();
  180. device_scale_ = 1.0f;
  181. // Since we're binding a new one, all of the callbacks have been canceled.
  182. manual_callback_pending_ = false;
  183. flush_pending_ = false;
  184. weak_factory_.InvalidateWeakPtrs();
  185. }
  186. if (pending_device_scale_ != device_scale_)
  187. client_->UpdateScale(1.0f / pending_device_scale_);
  188. device_scale_ = pending_device_scale_;
  189. // This must be cleared before calling into the plugin since it may do
  190. // additional invalidation or sizing operations.
  191. has_pending_resize_ = false;
  192. pending_size_ = gfx::Size();
  193. }
  194. PaintAggregator::PaintUpdate update = aggregator_.GetPendingUpdate();
  195. client_->OnPaint(update.paint_rects, ready_rects, pending_rects);
  196. if (ready_rects.empty() && pending_rects.empty())
  197. return; // Nothing was painted, don't schedule a flush.
  198. std::vector<PaintReadyRect> ready_now;
  199. if (pending_rects.empty()) {
  200. aggregator_.SetIntermediateResults(ready_rects, pending_rects);
  201. ready_now = aggregator_.GetReadyRects();
  202. aggregator_.ClearPendingUpdate();
  203. // First, apply any scroll amount less than the surface's size.
  204. if (update.has_scroll &&
  205. std::abs(update.scroll_delta.x()) < surface_->width() &&
  206. std::abs(update.scroll_delta.y()) < surface_->height()) {
  207. // TODO(crbug.com/1263614): Use `SkSurface::notifyContentWillChange()`.
  208. gfx::ScrollCanvas(surface_->getCanvas(), update.scroll_rect,
  209. update.scroll_delta);
  210. }
  211. view_size_changed_waiting_for_paint_ = false;
  212. } else {
  213. std::vector<PaintReadyRect> ready_later;
  214. for (const auto& ready_rect : ready_rects) {
  215. // Don't flush any part (i.e. scrollbars) if we're resizing the browser,
  216. // as that'll lead to flashes. Until we flush, the browser will use the
  217. // previous image, but if we flush, it'll revert to using the blank image.
  218. // We make an exception for the first paint since we want to show the
  219. // default background color instead of the pepper default of black.
  220. if (ready_rect.flush_now() &&
  221. (!view_size_changed_waiting_for_paint_ || first_paint_)) {
  222. ready_now.push_back(ready_rect);
  223. } else {
  224. ready_later.push_back(ready_rect);
  225. }
  226. }
  227. // Take the rectangles, except the ones that need to be flushed right away,
  228. // and save them so that everything is flushed at once.
  229. aggregator_.SetIntermediateResults(ready_later, pending_rects);
  230. if (ready_now.empty()) {
  231. EnsureCallbackPending();
  232. return;
  233. }
  234. }
  235. for (const auto& ready_rect : ready_now) {
  236. SkRect skia_rect = gfx::RectToSkRect(ready_rect.rect());
  237. surface_->getCanvas()->drawImageRect(
  238. &ready_rect.image(), skia_rect, skia_rect, SkSamplingOptions(), nullptr,
  239. SkCanvas::kStrict_SrcRectConstraint);
  240. }
  241. Flush();
  242. first_paint_ = false;
  243. }
  244. void PaintManager::Flush() {
  245. flush_requested_ = false;
  246. sk_sp<SkImage> snapshot = surface_->makeImageSnapshot();
  247. surface_->getCanvas()->drawImage(snapshot.get(), /*x=*/0, /*y=*/0,
  248. SkSamplingOptions(), /*paint=*/nullptr);
  249. client_->UpdateSnapshot(std::move(snapshot));
  250. // TODO(crbug.com/1302059): Complete flush synchronously.
  251. base::SequencedTaskRunnerHandle::Get()->PostTask(
  252. FROM_HERE, base::BindOnce(&PaintManager::OnFlushComplete,
  253. weak_factory_.GetWeakPtr()));
  254. flush_pending_ = true;
  255. }
  256. void PaintManager::OnFlushComplete() {
  257. DCHECK(flush_pending_);
  258. flush_pending_ = false;
  259. // If more paints were enqueued while we were waiting for the flush to
  260. // complete, execute them now.
  261. if (aggregator_.HasPendingUpdate())
  262. DoPaint();
  263. // If there was another flush request while flushing we flush again.
  264. if (flush_requested_) {
  265. Flush();
  266. }
  267. }
  268. void PaintManager::OnManualCallbackComplete() {
  269. DCHECK(manual_callback_pending_);
  270. manual_callback_pending_ = false;
  271. // Just because we have a manual callback doesn't mean there are actually any
  272. // invalid regions. Even though we only schedule this callback when something
  273. // is pending, a Flush callback could have come in before this callback was
  274. // executed and that could have cleared the queue.
  275. if (aggregator_.HasPendingUpdate())
  276. DoPaint();
  277. }
  278. } // namespace chrome_pdf