pdf_view_web_plugin.cc 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003
  1. // Copyright 2020 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/pdf_view_web_plugin.h"
  5. #include <stddef.h>
  6. #include <stdint.h>
  7. #include <algorithm>
  8. #include <memory>
  9. #include <string>
  10. #include <utility>
  11. #include <vector>
  12. #include "base/bind.h"
  13. #include "base/callback.h"
  14. #include "base/check_op.h"
  15. #include "base/containers/fixed_flat_map.h"
  16. #include "base/containers/queue.h"
  17. #include "base/debug/crash_logging.h"
  18. #include "base/i18n/char_iterator.h"
  19. #include "base/i18n/string_search.h"
  20. #include "base/i18n/time_formatting.h"
  21. #include "base/logging.h"
  22. #include "base/memory/raw_ptr.h"
  23. #include "base/no_destructor.h"
  24. #include "base/notreached.h"
  25. #include "base/numerics/safe_conversions.h"
  26. #include "base/strings/strcat.h"
  27. #include "base/strings/string_number_conversions.h"
  28. #include "base/strings/string_piece.h"
  29. #include "base/strings/string_split.h"
  30. #include "base/strings/string_util.h"
  31. #include "base/thread_annotations.h"
  32. #include "base/threading/sequenced_task_runner_handle.h"
  33. #include "base/threading/thread_checker.h"
  34. #include "base/threading/thread_task_runner_handle.h"
  35. #include "base/time/time.h"
  36. #include "base/values.h"
  37. #include "cc/paint/paint_canvas.h"
  38. #include "cc/paint/paint_flags.h"
  39. #include "cc/paint/paint_image.h"
  40. #include "cc/paint/paint_image_builder.h"
  41. #include "net/cookies/site_for_cookies.h"
  42. #include "pdf/accessibility_structs.h"
  43. #include "pdf/buildflags.h"
  44. #include "pdf/content_restriction.h"
  45. #include "pdf/document_layout.h"
  46. #include "pdf/loader/result_codes.h"
  47. #include "pdf/loader/url_loader.h"
  48. #include "pdf/metrics_handler.h"
  49. #include "pdf/mojom/pdf.mojom.h"
  50. #include "pdf/paint_ready_rect.h"
  51. #include "pdf/parsed_params.h"
  52. #include "pdf/pdf_accessibility_data_handler.h"
  53. #include "pdf/pdf_engine.h"
  54. #include "pdf/pdf_init.h"
  55. #include "pdf/pdfium/pdfium_engine.h"
  56. #include "pdf/post_message_receiver.h"
  57. #include "pdf/ui/document_properties.h"
  58. #include "pdf/ui/file_name.h"
  59. #include "pdf/ui/thumbnail.h"
  60. #include "printing/metafile_skia.h"
  61. #include "services/network/public/mojom/referrer_policy.mojom-shared.h"
  62. #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
  63. #include "third_party/blink/public/common/input/web_coalesced_input_event.h"
  64. #include "third_party/blink/public/common/input/web_input_event.h"
  65. #include "third_party/blink/public/common/input/web_keyboard_event.h"
  66. #include "third_party/blink/public/common/metrics/document_update_reason.h"
  67. #include "third_party/blink/public/mojom/input/focus_type.mojom-shared.h"
  68. #include "third_party/blink/public/platform/platform.h"
  69. #include "third_party/blink/public/platform/web_input_event_result.h"
  70. #include "third_party/blink/public/platform/web_string.h"
  71. #include "third_party/blink/public/platform/web_text_input_type.h"
  72. #include "third_party/blink/public/platform/web_url.h"
  73. #include "third_party/blink/public/platform/web_url_error.h"
  74. #include "third_party/blink/public/platform/web_url_response.h"
  75. #include "third_party/blink/public/web/web_associated_url_loader.h"
  76. #include "third_party/blink/public/web/web_associated_url_loader_options.h"
  77. #include "third_party/blink/public/web/web_document.h"
  78. #include "third_party/blink/public/web/web_frame.h"
  79. #include "third_party/blink/public/web/web_plugin_container.h"
  80. #include "third_party/blink/public/web/web_plugin_params.h"
  81. #include "third_party/blink/public/web/web_print_params.h"
  82. #include "third_party/blink/public/web/web_print_preset_options.h"
  83. #include "third_party/blink/public/web/web_view.h"
  84. #include "third_party/blink/public/web/web_widget.h"
  85. #include "third_party/skia/include/core/SkBitmap.h"
  86. #include "third_party/skia/include/core/SkColor.h"
  87. #include "third_party/skia/include/core/SkImage.h"
  88. #include "third_party/skia/include/core/SkImageInfo.h"
  89. #include "third_party/skia/include/core/SkRect.h"
  90. #include "third_party/skia/include/core/SkRefCnt.h"
  91. #include "third_party/skia/include/core/SkSize.h"
  92. #include "ui/base/cursor/cursor.h"
  93. #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
  94. #include "ui/base/text/bytes_formatting.h"
  95. #include "ui/events/base_event_utils.h"
  96. #include "ui/events/blink/blink_event_util.h"
  97. #include "ui/events/keycodes/keyboard_codes.h"
  98. #include "ui/gfx/geometry/point.h"
  99. #include "ui/gfx/geometry/point_f.h"
  100. #include "ui/gfx/geometry/rect.h"
  101. #include "ui/gfx/geometry/size.h"
  102. #include "ui/gfx/geometry/skia_conversions.h"
  103. #include "ui/gfx/geometry/vector2d.h"
  104. #include "ui/gfx/geometry/vector2d_f.h"
  105. #include "ui/gfx/range/range.h"
  106. #include "url/gurl.h"
  107. #include "v8/include/v8.h"
  108. namespace chrome_pdf {
  109. namespace {
  110. // The minimum zoom level allowed.
  111. constexpr double kMinZoom = 0.01;
  112. constexpr base::TimeDelta kFindResultCooldown = base::Milliseconds(100);
  113. constexpr base::StringPiece kChromeExtensionHost =
  114. "chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/";
  115. // Print Preview base URL.
  116. constexpr base::StringPiece kChromePrintHost = "chrome://print/";
  117. // Untrusted Print Preview base URL.
  118. constexpr base::StringPiece kChromeUntrustedPrintHost =
  119. "chrome-untrusted://print/";
  120. // Same value as `printing::COMPLETE_PREVIEW_DOCUMENT_INDEX`.
  121. constexpr int kCompletePDFIndex = -1;
  122. // A different negative value to differentiate itself from `kCompletePDFIndex`.
  123. constexpr int kInvalidPDFIndex = -2;
  124. // Enumeration of pinch states.
  125. // This should match PinchPhase enum in
  126. // chrome/browser/resources/pdf/viewport.ts.
  127. enum class PinchPhase {
  128. kNone = 0,
  129. kStart = 1,
  130. kUpdateZoomOut = 2,
  131. kUpdateZoomIn = 3,
  132. kEnd = 4,
  133. };
  134. // Initialization performed per renderer process. Initialization may be
  135. // triggered from multiple plugin instances, but should only execute once.
  136. //
  137. // TODO(crbug.com/1123621): We may be able to simplify this once we've figured
  138. // out exactly which processes need to initialize and shutdown PDFium.
  139. class PerProcessInitializer final {
  140. public:
  141. static PerProcessInitializer& GetInstance() {
  142. static base::NoDestructor<PerProcessInitializer,
  143. base::AllowForTriviallyDestructibleType>
  144. instance;
  145. return *instance;
  146. }
  147. void Acquire() {
  148. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  149. DCHECK_GE(init_count_, 0);
  150. if (init_count_++ > 0)
  151. return;
  152. DCHECK(!IsSDKInitializedViaPlugin());
  153. InitializeSDK(/*enable_v8=*/true, FontMappingMode::kBlink);
  154. SetIsSDKInitializedViaPlugin(true);
  155. }
  156. void Release() {
  157. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  158. DCHECK_GT(init_count_, 0);
  159. if (--init_count_ > 0)
  160. return;
  161. DCHECK(IsSDKInitializedViaPlugin());
  162. ShutdownSDK();
  163. SetIsSDKInitializedViaPlugin(false);
  164. }
  165. private:
  166. int init_count_ GUARDED_BY_CONTEXT(thread_checker_) = 0;
  167. // TODO(crbug.com/1123731): Assuming PDFium is thread-hostile for now, and
  168. // must use one thread exclusively.
  169. THREAD_CHECKER(thread_checker_);
  170. };
  171. base::Value::Dict DictFromRect(const gfx::Rect& rect) {
  172. base::Value::Dict dict;
  173. dict.Set("x", rect.x());
  174. dict.Set("y", rect.y());
  175. dict.Set("width", rect.width());
  176. dict.Set("height", rect.height());
  177. return dict;
  178. }
  179. bool IsPrintPreviewUrl(base::StringPiece url) {
  180. return base::StartsWith(url, kChromeUntrustedPrintHost);
  181. }
  182. int ExtractPrintPreviewPageIndex(base::StringPiece src_url) {
  183. // Sample `src_url` format: chrome-untrusted://print/id/page_index/print.pdf
  184. // The page_index is zero-based, but can be negative with special meanings.
  185. std::vector<base::StringPiece> url_substr =
  186. base::SplitStringPiece(src_url.substr(kChromeUntrustedPrintHost.size()),
  187. "/", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
  188. if (url_substr.size() != 3)
  189. return kInvalidPDFIndex;
  190. if (url_substr[2] != "print.pdf")
  191. return kInvalidPDFIndex;
  192. int page_index = 0;
  193. if (!base::StringToInt(url_substr[1], &page_index))
  194. return kInvalidPDFIndex;
  195. return page_index;
  196. }
  197. bool IsPreviewingPDF(int print_preview_page_count) {
  198. return print_preview_page_count == 0;
  199. }
  200. // Prepares messages from the plugin that reply to messages from the embedder.
  201. // If the "type" value of `message` is "foo", then the `reply_type` must be
  202. // "fooReply". The `message` from the embedder must have a "messageId" value
  203. // that will be copied to the reply message.
  204. base::Value::Dict PrepareReplyMessage(base::StringPiece reply_type,
  205. const base::Value::Dict& message) {
  206. DCHECK_EQ(reply_type, *message.FindString("type") + "Reply");
  207. base::Value::Dict reply;
  208. reply.Set("type", reply_type);
  209. reply.Set("messageId", *message.FindString("messageId"));
  210. return reply;
  211. }
  212. } // namespace
  213. std::unique_ptr<PDFiumEngine> PdfViewWebPlugin::Client::CreateEngine(
  214. PDFEngine::Client* client,
  215. PDFiumFormFiller::ScriptOption script_option) {
  216. return std::make_unique<PDFiumEngine>(client, script_option);
  217. }
  218. std::unique_ptr<PdfAccessibilityDataHandler>
  219. PdfViewWebPlugin::Client::CreateAccessibilityDataHandler(
  220. PdfAccessibilityActionHandler* action_handler) {
  221. return nullptr;
  222. }
  223. PdfViewWebPlugin::PdfViewWebPlugin(
  224. std::unique_ptr<Client> client,
  225. mojo::AssociatedRemote<pdf::mojom::PdfService> pdf_service,
  226. const blink::WebPluginParams& params)
  227. : client_(std::move(client)),
  228. pdf_service_(std::move(pdf_service)),
  229. initial_params_(params),
  230. pdf_accessibility_data_handler_(
  231. client_->CreateAccessibilityDataHandler(this)) {
  232. DCHECK(pdf_service_);
  233. pdf_service_->SetListener(listener_receiver_.BindNewPipeAndPassRemote());
  234. }
  235. PdfViewWebPlugin::~PdfViewWebPlugin() = default;
  236. std::unique_ptr<PDFiumEngine> PdfViewWebPlugin::CreateEngine(
  237. PDFEngine::Client* client,
  238. PDFiumFormFiller::ScriptOption script_option) {
  239. return client_->CreateEngine(client, script_option);
  240. }
  241. // TODO(crbug.com/1302059): Delete after merging with `PdfViewPluginBase`.
  242. const PDFiumEngine* PdfViewWebPlugin::engine() const {
  243. return engine_.get();
  244. }
  245. // TODO(crbug.com/1302059): Delete after merging with `PdfViewPluginBase`.
  246. PDFiumEngine* PdfViewWebPlugin::engine() {
  247. return engine_.get();
  248. }
  249. bool PdfViewWebPlugin::Initialize(blink::WebPluginContainer* container) {
  250. DCHECK(container);
  251. client_->SetPluginContainer(container);
  252. DCHECK_EQ(container->Plugin(), this);
  253. return InitializeCommon();
  254. }
  255. bool PdfViewWebPlugin::InitializeForTesting() {
  256. return InitializeCommon();
  257. }
  258. bool PdfViewWebPlugin::InitializeCommon() {
  259. // Allow the plugin to handle touch events.
  260. client_->RequestTouchEventType(
  261. blink::WebPluginContainer::kTouchEventRequestTypeRaw);
  262. // Allow the plugin to handle find requests.
  263. client_->UsePluginAsFindHandler();
  264. absl::optional<ParsedParams> params = ParseWebPluginParams(initial_params_);
  265. // The contents of `initial_params_` are no longer needed.
  266. initial_params_ = {};
  267. if (!params.has_value())
  268. return false;
  269. // Sets crash keys like `ppapi::proxy::PDFResource::SetCrashData()`. Note that
  270. // we don't set the active URL from the top-level URL, as unlike within a
  271. // plugin process, the active URL changes frequently within a renderer process
  272. // (see crbug.com/1266050 for details).
  273. //
  274. // TODO(crbug.com/1266087): If multiple PDF plugin instances share the same
  275. // renderer process, the crash key will be overwritten by the newest value.
  276. static base::debug::CrashKeyString* subresource_url =
  277. base::debug::AllocateCrashKeyString("subresource_url",
  278. base::debug::CrashKeySize::Size256);
  279. base::debug::SetCrashKeyString(subresource_url, params->original_url);
  280. PerProcessInitializer::GetInstance().Acquire();
  281. // Check if the PDF is being loaded in the PDF chrome extension. We only allow
  282. // the plugin to be loaded in the extension and print preview to avoid
  283. // exposing sensitive APIs directly to external websites.
  284. //
  285. // This is enforced before creating the plugin (see
  286. // `pdf::CreateInternalPlugin()`), so we just `CHECK` for defense-in-depth.
  287. const std::string& embedder_origin = client_->GetEmbedderOriginString();
  288. is_print_preview_ = (embedder_origin == kChromePrintHost);
  289. CHECK(IsPrintPreview() || embedder_origin == kChromeExtensionHost);
  290. full_frame_ = params->full_frame;
  291. background_color_ = params->background_color;
  292. engine_ = CreateEngine(this, params->script_option);
  293. DCHECK(engine_);
  294. SendSetSmoothScrolling();
  295. // Skip the remaining initialization when in Print Preview mode. Loading will
  296. // continue after the plugin receives a "resetPrintPreviewMode" message.
  297. if (IsPrintPreview())
  298. return true;
  299. set_last_progress_sent(0);
  300. LoadUrl(params->src_url, base::BindOnce(&PdfViewWebPlugin::DidOpen,
  301. weak_factory_.GetWeakPtr()));
  302. url_ = params->original_url;
  303. // Not all edits go through the PDF plugin's form filler. The plugin instance
  304. // can be restarted by exiting annotation mode on ChromeOS, which can set the
  305. // document to an edited state.
  306. edit_mode_ = params->has_edits;
  307. #if !BUILDFLAG(ENABLE_INK)
  308. DCHECK(!edit_mode_);
  309. #endif // !BUILDFLAG(ENABLE_INK)
  310. metrics_handler_ = std::make_unique<MetricsHandler>();
  311. return true;
  312. }
  313. void PdfViewWebPlugin::SendSetSmoothScrolling() {
  314. base::Value::Dict message;
  315. message.Set("type", "setSmoothScrolling");
  316. message.Set("smoothScrolling",
  317. blink::Platform::Current()->IsScrollAnimatorEnabled());
  318. SendMessage(std::move(message));
  319. }
  320. void PdfViewWebPlugin::DidOpen(std::unique_ptr<UrlLoader> loader,
  321. int32_t result) {
  322. if (result == kSuccess) {
  323. if (!engine_->HandleDocumentLoad(std::move(loader), url_)) {
  324. set_document_load_state(DocumentLoadState::kLoading);
  325. DocumentLoadFailed();
  326. }
  327. } else if (result != kErrorAborted) {
  328. DocumentLoadFailed();
  329. }
  330. }
  331. void PdfViewWebPlugin::Destroy() {
  332. if (client_->PluginContainer()) {
  333. // Explicitly destroy the PDFEngine during destruction as it may call back
  334. // into this object.
  335. preview_engine_.reset();
  336. engine_.reset();
  337. PerProcessInitializer::GetInstance().Release();
  338. client_->SetPluginContainer(nullptr);
  339. }
  340. delete this;
  341. }
  342. blink::WebPluginContainer* PdfViewWebPlugin::Container() const {
  343. return client_->PluginContainer();
  344. }
  345. v8::Local<v8::Object> PdfViewWebPlugin::V8ScriptableObject(
  346. v8::Isolate* isolate) {
  347. if (scriptable_receiver_.IsEmpty()) {
  348. // TODO(crbug.com/1123731): Messages should not be handled on the renderer
  349. // main thread.
  350. scriptable_receiver_.Reset(
  351. isolate, PostMessageReceiver::Create(
  352. isolate, client_->GetWeakPtr(), weak_factory_.GetWeakPtr(),
  353. base::SequencedTaskRunnerHandle::Get()));
  354. }
  355. return scriptable_receiver_.Get(isolate);
  356. }
  357. bool PdfViewWebPlugin::SupportsKeyboardFocus() const {
  358. return !IsPrintPreview();
  359. }
  360. void PdfViewWebPlugin::UpdateAllLifecyclePhases(
  361. blink::DocumentUpdateReason reason) {}
  362. void PdfViewWebPlugin::Paint(cc::PaintCanvas* canvas, const gfx::Rect& rect) {
  363. // Clip the intersection of the paint rect and the plugin rect, so that
  364. // painting outside the plugin or the paint rect area can be avoided.
  365. // Note: `rect` is in CSS pixels. We need to use `css_plugin_rect_`
  366. // to calculate the intersection.
  367. SkRect invalidate_rect =
  368. gfx::RectToSkRect(gfx::IntersectRects(css_plugin_rect_, rect));
  369. cc::PaintCanvasAutoRestore auto_restore(canvas, /*save=*/true);
  370. canvas->clipRect(invalidate_rect);
  371. // Paint with the plugin's background color if the snapshot is not ready.
  372. if (snapshot_.GetSkImageInfo().isEmpty()) {
  373. cc::PaintFlags flags;
  374. flags.setBlendMode(SkBlendMode::kSrc);
  375. flags.setColor(GetBackgroundColor());
  376. canvas->drawRect(invalidate_rect, flags);
  377. return;
  378. }
  379. // Layer translate is independent of scaling, so apply first.
  380. if (!total_translate_.IsZero())
  381. canvas->translate(total_translate_.x(), total_translate_.y());
  382. if (device_to_css_scale_ != 1.0f)
  383. canvas->scale(device_to_css_scale_, device_to_css_scale_);
  384. // Position layer at plugin origin before layer scaling.
  385. if (!plugin_rect_.origin().IsOrigin())
  386. canvas->translate(plugin_rect_.x(), plugin_rect_.y());
  387. if (snapshot_scale_ != 1.0f)
  388. canvas->scale(snapshot_scale_, snapshot_scale_);
  389. canvas->drawImage(snapshot_, 0, 0);
  390. }
  391. void PdfViewWebPlugin::PrepareForFirstPaint(
  392. std::vector<PaintReadyRect>& ready) {
  393. if (!first_paint_)
  394. return;
  395. // Fill the image data buffer with the background color.
  396. first_paint_ = false;
  397. image_data().eraseColor(background_color_);
  398. ready.emplace_back(gfx::SkIRectToRect(image_data().bounds()),
  399. image_data().asImage(), /*flush_now=*/true);
  400. }
  401. void PdfViewWebPlugin::UpdateGeometry(const gfx::Rect& window_rect,
  402. const gfx::Rect& clip_rect,
  403. const gfx::Rect& unobscured_rect,
  404. bool is_visible) {
  405. // An empty `window_rect` can be received here in the following cases:
  406. // - If the embedded plugin size is 0.
  407. // - If the embedded plugin size is not 0, it can come from re-layouts during
  408. // the plugin initialization.
  409. // For either case, there is no need to create a graphic device to display
  410. // a PDF in an empty window. Since an empty `window_rect` can cause failure
  411. // to create the graphic device, avoid all updates on the geometries and the
  412. // device scales used by the plugin, the PaintManager and the PDFiumEngine
  413. // unless a non-empty `window_rect` is received.
  414. if (window_rect.IsEmpty())
  415. return;
  416. OnViewportChanged(window_rect, client_->DeviceScaleFactor());
  417. gfx::PointF scroll_position = client_->GetScrollPosition();
  418. // Convert back to CSS pixels.
  419. scroll_position.Scale(1.0f / device_scale_);
  420. UpdateScroll(scroll_position);
  421. }
  422. void PdfViewWebPlugin::UpdateScroll(const gfx::PointF& scroll_position) {
  423. if (stop_scrolling_)
  424. return;
  425. float max_x = std::max(document_size().width() * static_cast<float>(zoom()) -
  426. plugin_dip_size_.width(),
  427. 0.0f);
  428. float max_y = std::max(document_size().height() * static_cast<float>(zoom()) -
  429. plugin_dip_size_.height(),
  430. 0.0f);
  431. gfx::PointF scaled_scroll_position(
  432. base::clamp(scroll_position.x(), 0.0f, max_x),
  433. base::clamp(scroll_position.y(), 0.0f, max_y));
  434. scaled_scroll_position.Scale(device_scale_);
  435. engine_->ScrolledToXPosition(scaled_scroll_position.x());
  436. engine_->ScrolledToYPosition(scaled_scroll_position.y());
  437. }
  438. void PdfViewWebPlugin::UpdateFocus(bool focused,
  439. blink::mojom::FocusType focus_type) {
  440. if (has_focus_ != focused) {
  441. engine_->UpdateFocus(focused);
  442. client_->UpdateTextInputState();
  443. client_->UpdateSelectionBounds();
  444. }
  445. has_focus_ = focused;
  446. if (!has_focus_ || !SupportsKeyboardFocus())
  447. return;
  448. if (focus_type != blink::mojom::FocusType::kBackward &&
  449. focus_type != blink::mojom::FocusType::kForward) {
  450. return;
  451. }
  452. const int modifiers = focus_type == blink::mojom::FocusType::kForward
  453. ? blink::WebInputEvent::kNoModifiers
  454. : blink::WebInputEvent::kShiftKey;
  455. blink::WebKeyboardEvent simulated_event(blink::WebInputEvent::Type::kKeyDown,
  456. modifiers, base::TimeTicks());
  457. simulated_event.windows_key_code = ui::KeyboardCode::VKEY_TAB;
  458. HandleWebInputEvent(simulated_event);
  459. }
  460. void PdfViewWebPlugin::UpdateVisibility(bool visibility) {}
  461. blink::WebInputEventResult PdfViewWebPlugin::HandleInputEvent(
  462. const blink::WebCoalescedInputEvent& event,
  463. ui::Cursor* cursor) {
  464. // TODO(crbug.com/1302059): The input events received by the Pepper plugin
  465. // already have the viewport-to-DIP scale applied. The scaling done here
  466. // should be moved into `HandleWebInputEvent()` once the Pepper plugin is
  467. // removed.
  468. std::unique_ptr<blink::WebInputEvent> scaled_event =
  469. ui::ScaleWebInputEvent(event.Event(), viewport_to_dip_scale_);
  470. const blink::WebInputEvent& event_to_handle =
  471. scaled_event ? *scaled_event : event.Event();
  472. const blink::WebInputEventResult result =
  473. HandleWebInputEvent(event_to_handle)
  474. ? blink::WebInputEventResult::kHandledApplication
  475. : blink::WebInputEventResult::kNotHandled;
  476. *cursor = cursor_type_;
  477. return result;
  478. }
  479. void PdfViewWebPlugin::DidReceiveResponse(
  480. const blink::WebURLResponse& response) {}
  481. void PdfViewWebPlugin::DidReceiveData(const char* data, size_t data_length) {}
  482. void PdfViewWebPlugin::DidFinishLoading() {}
  483. void PdfViewWebPlugin::DidFailLoading(const blink::WebURLError& error) {}
  484. bool PdfViewWebPlugin::SupportsPaginatedPrint() {
  485. return true;
  486. }
  487. bool PdfViewWebPlugin::GetPrintPresetOptionsFromDocument(
  488. blink::WebPrintPresetOptions* print_preset_options) {
  489. print_preset_options->is_scaling_disabled = !engine_->GetPrintScaling();
  490. print_preset_options->copies = engine_->GetCopiesToPrint();
  491. print_preset_options->duplex_mode = engine_->GetDuplexMode();
  492. print_preset_options->uniform_page_size = engine_->GetUniformPageSizePoints();
  493. return true;
  494. }
  495. int PdfViewWebPlugin::PrintBegin(const blink::WebPrintParams& print_params) {
  496. // The returned value is always equal to the number of pages in the PDF
  497. // document irrespective of the printable area.
  498. int32_t ret = engine_->GetNumberOfPages();
  499. if (!ret)
  500. return 0;
  501. if (!engine_->HasPermission(DocumentPermission::kPrintLowQuality))
  502. return 0;
  503. print_params_ = print_params;
  504. if (!engine_->HasPermission(DocumentPermission::kPrintHighQuality))
  505. print_params_->rasterize_pdf = true;
  506. engine_->PrintBegin();
  507. return ret;
  508. }
  509. void PdfViewWebPlugin::PrintPage(int page_number, cc::PaintCanvas* canvas) {
  510. // The entire document goes into one metafile. However, it is impossible to
  511. // know if a call to `PrintPage()` is the last call. Thus, `PrintPage()` just
  512. // stores the pages to print and the metafile. Eventually, the printed output
  513. // is generated in `PrintEnd()` and copied over to the metafile.
  514. // Every `canvas` passed to this method should have a valid `metafile`.
  515. printing::MetafileSkia* metafile = canvas->GetPrintingMetafile();
  516. DCHECK(metafile);
  517. // `pages_to_print_` should be empty iff `printing_metafile_` is not set.
  518. DCHECK_EQ(pages_to_print_.empty(), !printing_metafile_);
  519. // The metafile should be the same across all calls for a given print job.
  520. DCHECK(!printing_metafile_ || (printing_metafile_ == metafile));
  521. if (!printing_metafile_)
  522. printing_metafile_ = metafile;
  523. pages_to_print_.push_back(page_number);
  524. }
  525. void PdfViewWebPlugin::PrintEnd() {
  526. if (pages_to_print_.empty())
  527. return;
  528. print_pages_called_ = true;
  529. printing_metafile_->InitFromData(
  530. engine_->PrintPages(pages_to_print_, print_params_.value()));
  531. if (print_pages_called_)
  532. UserMetricsRecordAction("PDF.PrintPage");
  533. print_pages_called_ = false;
  534. print_params_.reset();
  535. engine_->PrintEnd();
  536. printing_metafile_ = nullptr;
  537. pages_to_print_.clear();
  538. }
  539. bool PdfViewWebPlugin::HasSelection() const {
  540. return !selected_text_.IsEmpty();
  541. }
  542. blink::WebString PdfViewWebPlugin::SelectionAsText() const {
  543. return selected_text_;
  544. }
  545. blink::WebString PdfViewWebPlugin::SelectionAsMarkup() const {
  546. return selected_text_;
  547. }
  548. bool PdfViewWebPlugin::CanEditText() const {
  549. return engine_->CanEditText();
  550. }
  551. bool PdfViewWebPlugin::HasEditableText() const {
  552. return engine_->HasEditableText();
  553. }
  554. bool PdfViewWebPlugin::CanUndo() const {
  555. return engine_->CanUndo();
  556. }
  557. bool PdfViewWebPlugin::CanRedo() const {
  558. return engine_->CanRedo();
  559. }
  560. bool PdfViewWebPlugin::CanCopy() const {
  561. return engine_->HasPermission(DocumentPermission::kCopy);
  562. }
  563. bool PdfViewWebPlugin::ExecuteEditCommand(const blink::WebString& name,
  564. const blink::WebString& value) {
  565. if (name == "SelectAll")
  566. return SelectAll();
  567. if (name == "Cut")
  568. return Cut();
  569. if (name == "Paste" || name == "PasteAndMatchStyle")
  570. return Paste(value);
  571. if (name == "Undo")
  572. return Undo();
  573. if (name == "Redo")
  574. return Redo();
  575. return false;
  576. }
  577. blink::WebURL PdfViewWebPlugin::LinkAtPosition(
  578. const gfx::Point& /*position*/) const {
  579. return GURL(link_under_cursor_);
  580. }
  581. bool PdfViewWebPlugin::StartFind(const blink::WebString& search_text,
  582. bool case_sensitive,
  583. int identifier) {
  584. ResetRecentlySentFindUpdate();
  585. find_identifier_ = identifier;
  586. engine_->StartFind(search_text.Utf8(), case_sensitive);
  587. return true;
  588. }
  589. void PdfViewWebPlugin::SelectFindResult(bool forward, int identifier) {
  590. find_identifier_ = identifier;
  591. engine_->SelectFindResult(forward);
  592. }
  593. void PdfViewWebPlugin::StopFind() {
  594. find_identifier_ = -1;
  595. engine_->StopFind();
  596. tickmarks_.clear();
  597. client_->ReportFindInPageTickmarks(tickmarks_);
  598. }
  599. bool PdfViewWebPlugin::CanRotateView() {
  600. return !IsPrintPreview();
  601. }
  602. void PdfViewWebPlugin::RotateView(blink::WebPlugin::RotationType type) {
  603. DCHECK(CanRotateView());
  604. switch (type) {
  605. case blink::WebPlugin::RotationType::k90Clockwise:
  606. engine_->RotateClockwise();
  607. break;
  608. case blink::WebPlugin::RotationType::k90Counterclockwise:
  609. engine_->RotateCounterclockwise();
  610. break;
  611. }
  612. }
  613. bool PdfViewWebPlugin::ShouldDispatchImeEventsToPlugin() {
  614. return true;
  615. }
  616. blink::WebTextInputType PdfViewWebPlugin::GetPluginTextInputType() {
  617. return text_input_type_;
  618. }
  619. gfx::Rect PdfViewWebPlugin::GetPluginCaretBounds() {
  620. return caret_rect_;
  621. }
  622. void PdfViewWebPlugin::ImeSetCompositionForPlugin(
  623. const blink::WebString& text,
  624. const std::vector<ui::ImeTextSpan>& /*ime_text_spans*/,
  625. const gfx::Range& /*replacement_range*/,
  626. int /*selection_start*/,
  627. int /*selection_end*/) {
  628. composition_text_ = text;
  629. }
  630. void PdfViewWebPlugin::ImeCommitTextForPlugin(
  631. const blink::WebString& text,
  632. const std::vector<ui::ImeTextSpan>& /*ime_text_spans*/,
  633. const gfx::Range& /*replacement_range*/,
  634. int /*relative_cursor_pos*/) {
  635. HandleImeCommit(text);
  636. }
  637. void PdfViewWebPlugin::ImeFinishComposingTextForPlugin(
  638. bool /*keep_selection*/) {
  639. HandleImeCommit(composition_text_);
  640. }
  641. void PdfViewWebPlugin::ProposeDocumentLayout(const DocumentLayout& layout) {
  642. base::Value::Dict message;
  643. message.Set("type", "documentDimensions");
  644. message.Set("width", layout.size().width());
  645. message.Set("height", layout.size().height());
  646. message.Set("layoutOptions", layout.options().ToValue());
  647. base::Value::List page_dimensions;
  648. for (size_t i = 0; i < layout.page_count(); ++i)
  649. page_dimensions.Append(DictFromRect(layout.page_rect(i)));
  650. message.Set("pageDimensions", std::move(page_dimensions));
  651. SendMessage(std::move(message));
  652. // Reload the accessibility tree on layout changes because the relative page
  653. // bounds are no longer valid.
  654. if (layout.dirty() && accessibility_state() == AccessibilityState::kLoaded)
  655. LoadAccessibility();
  656. }
  657. void PdfViewWebPlugin::UpdateCursor(ui::mojom::CursorType new_cursor_type) {
  658. cursor_type_ = new_cursor_type;
  659. }
  660. void PdfViewWebPlugin::UpdateTickMarks(
  661. const std::vector<gfx::Rect>& tickmarks) {
  662. float inverse_scale = 1.0f / device_scale_;
  663. tickmarks_.clear();
  664. tickmarks_.reserve(tickmarks.size());
  665. std::transform(tickmarks.begin(), tickmarks.end(),
  666. std::back_inserter(tickmarks_),
  667. [inverse_scale](const gfx::Rect& t) -> gfx::Rect {
  668. return gfx::ScaleToEnclosingRect(t, inverse_scale);
  669. });
  670. }
  671. void PdfViewWebPlugin::NotifyNumberOfFindResultsChanged(int total,
  672. bool final_result) {
  673. // We don't want to spam the renderer with too many updates to the number of
  674. // find results. Don't send an update if we sent one too recently. If it's the
  675. // final update, we always send it though.
  676. if (recently_sent_find_update_ && !final_result)
  677. return;
  678. // After stopping search and setting `find_identifier_` to -1 there still may
  679. // be a NotifyNumberOfFindResultsChanged notification pending from engine.
  680. // Just ignore them.
  681. if (find_identifier_ != -1) {
  682. client_->ReportFindInPageMatchCount(find_identifier_, total, final_result);
  683. }
  684. client_->ReportFindInPageTickmarks(tickmarks_);
  685. if (final_result)
  686. return;
  687. recently_sent_find_update_ = true;
  688. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  689. FROM_HERE,
  690. base::BindOnce(&PdfViewWebPlugin::ResetRecentlySentFindUpdate,
  691. weak_factory_.GetWeakPtr()),
  692. kFindResultCooldown);
  693. }
  694. void PdfViewWebPlugin::NotifySelectedFindResultChanged(int current_find_index,
  695. bool final_result) {
  696. if (find_identifier_ == -1 || !client_->PluginContainer())
  697. return;
  698. DCHECK_GE(current_find_index, -1);
  699. client_->ReportFindInPageSelection(find_identifier_, current_find_index + 1,
  700. final_result);
  701. }
  702. void PdfViewWebPlugin::CaretChanged(const gfx::Rect& caret_rect) {
  703. caret_rect_ = gfx::ScaleToEnclosingRect(
  704. caret_rect + available_area().OffsetFromOrigin(), device_to_css_scale_);
  705. }
  706. void PdfViewWebPlugin::GetDocumentPassword(
  707. base::OnceCallback<void(const std::string&)> callback) {
  708. DCHECK(password_callback_.is_null());
  709. password_callback_ = std::move(callback);
  710. base::Value::Dict message;
  711. message.Set("type", "getPassword");
  712. SendMessage(std::move(message));
  713. }
  714. void PdfViewWebPlugin::Beep() {
  715. base::Value::Dict message;
  716. message.Set("type", "beep");
  717. SendMessage(std::move(message));
  718. }
  719. void PdfViewWebPlugin::Alert(const std::string& message) {
  720. client_->Alert(blink::WebString::FromUTF8(message));
  721. }
  722. bool PdfViewWebPlugin::Confirm(const std::string& message) {
  723. return client_->Confirm(blink::WebString::FromUTF8(message));
  724. }
  725. std::string PdfViewWebPlugin::Prompt(const std::string& question,
  726. const std::string& default_answer) {
  727. return client_
  728. ->Prompt(blink::WebString::FromUTF8(question),
  729. blink::WebString::FromUTF8(default_answer))
  730. .Utf8();
  731. }
  732. std::string PdfViewWebPlugin::GetURL() {
  733. return url_;
  734. }
  735. void PdfViewWebPlugin::LoadUrl(base::StringPiece url,
  736. LoadUrlCallback callback) {
  737. UrlRequest request;
  738. request.url = std::string(url);
  739. request.method = "GET";
  740. request.ignore_redirects = true;
  741. auto loader = std::make_unique<UrlLoader>(weak_factory_.GetWeakPtr());
  742. UrlLoader* raw_loader = loader.get();
  743. raw_loader->Open(request,
  744. base::BindOnce(std::move(callback), std::move(loader)));
  745. }
  746. void PdfViewWebPlugin::Print() {
  747. if (!engine_)
  748. return;
  749. const bool can_print =
  750. engine_->HasPermission(DocumentPermission::kPrintLowQuality) ||
  751. engine_->HasPermission(DocumentPermission::kPrintHighQuality);
  752. if (!can_print)
  753. return;
  754. base::ThreadTaskRunnerHandle::Get()->PostTask(
  755. FROM_HERE, base::BindOnce(&PdfViewWebPlugin::OnInvokePrintDialog,
  756. weak_factory_.GetWeakPtr()));
  757. }
  758. void PdfViewWebPlugin::SubmitForm(const std::string& url,
  759. const void* data,
  760. int length) {
  761. // `url` might be a relative URL. Resolve it against the document's URL.
  762. // TODO(crbug.com/1322928): Probably redundant with `Client::CompleteURL()`.
  763. GURL resolved_url = GURL(url_).Resolve(url);
  764. if (!resolved_url.is_valid())
  765. return;
  766. UrlRequest request;
  767. request.url = resolved_url.spec();
  768. request.method = "POST";
  769. request.body.assign(static_cast<const char*>(data), length);
  770. form_loader_ = std::make_unique<UrlLoader>(weak_factory_.GetWeakPtr());
  771. form_loader_->Open(request, base::BindOnce(&PdfViewWebPlugin::DidFormOpen,
  772. weak_factory_.GetWeakPtr()));
  773. }
  774. void PdfViewWebPlugin::DidFormOpen(int32_t result) {
  775. // TODO(crbug.com/719344): Process response.
  776. LOG_IF(ERROR, result != kSuccess) << "DidFormOpen failed: " << result;
  777. form_loader_.reset();
  778. }
  779. std::unique_ptr<UrlLoader> PdfViewWebPlugin::CreateUrlLoader() {
  780. if (full_frame_) {
  781. DidStartLoading();
  782. // Disable save and print until the document is fully loaded, since they
  783. // would generate an incomplete document. This needs to be done each time
  784. // DidStartLoading() is called because that resets the content restrictions.
  785. SetContentRestrictions(kContentRestrictionSave | kContentRestrictionPrint);
  786. }
  787. return std::make_unique<UrlLoader>(weak_factory_.GetWeakPtr());
  788. }
  789. std::vector<PDFEngine::Client::SearchStringResult>
  790. PdfViewWebPlugin::SearchString(const char16_t* string,
  791. const char16_t* term,
  792. bool case_sensitive) {
  793. base::i18n::RepeatingStringSearch searcher(
  794. /*find_this=*/term, /*in_this=*/string, case_sensitive);
  795. std::vector<SearchStringResult> results;
  796. int match_index;
  797. int match_length;
  798. while (searcher.NextMatchResult(match_index, match_length))
  799. results.push_back({.start_index = match_index, .length = match_length});
  800. return results;
  801. }
  802. void PdfViewWebPlugin::DocumentHasUnsupportedFeature(
  803. const std::string& feature) {
  804. DCHECK(!feature.empty());
  805. std::string metric = base::StrCat({"PDF_Unsupported_", feature});
  806. if (unsupported_features_reported_.insert(metric).second)
  807. client_->RecordComputedAction(metric);
  808. if (!full_frame() || notified_browser_about_unsupported_feature_)
  809. return;
  810. notified_browser_about_unsupported_feature_ = true;
  811. pdf_service_->HasUnsupportedFeature();
  812. }
  813. bool PdfViewWebPlugin::IsPrintPreview() const {
  814. return is_print_preview_;
  815. }
  816. SkColor PdfViewWebPlugin::GetBackgroundColor() const {
  817. return background_color_;
  818. }
  819. void PdfViewWebPlugin::EnteredEditMode() {
  820. edit_mode_ = true;
  821. pdf_service_->SetPluginCanSave(true);
  822. base::Value::Dict message;
  823. message.Set("type", "setIsEditing");
  824. SendMessage(std::move(message));
  825. }
  826. void PdfViewWebPlugin::SetSelectedText(const std::string& selected_text) {
  827. selected_text_ = blink::WebString::FromUTF8(selected_text);
  828. client_->TextSelectionChanged(selected_text_, /*offset=*/0,
  829. gfx::Range(0, selected_text_.length()));
  830. }
  831. void PdfViewWebPlugin::SetLinkUnderCursor(
  832. const std::string& link_under_cursor) {
  833. link_under_cursor_ = link_under_cursor;
  834. }
  835. bool PdfViewWebPlugin::IsValidLink(const std::string& url) {
  836. return base::Value(url).is_string();
  837. }
  838. void PdfViewWebPlugin::SetCaretPosition(const gfx::PointF& position) {
  839. engine_->SetCaretPosition(FrameToPdfCoordinates(position));
  840. }
  841. void PdfViewWebPlugin::MoveRangeSelectionExtent(const gfx::PointF& extent) {
  842. engine_->MoveRangeSelectionExtent(FrameToPdfCoordinates(extent));
  843. }
  844. void PdfViewWebPlugin::SetSelectionBounds(const gfx::PointF& base,
  845. const gfx::PointF& extent) {
  846. engine_->SetSelectionBounds(FrameToPdfCoordinates(base),
  847. FrameToPdfCoordinates(extent));
  848. }
  849. bool PdfViewWebPlugin::IsValid() const {
  850. return client_->HasFrame();
  851. }
  852. blink::WebURL PdfViewWebPlugin::CompleteURL(
  853. const blink::WebString& partial_url) const {
  854. DCHECK(IsValid());
  855. return client_->CompleteURL(partial_url);
  856. }
  857. net::SiteForCookies PdfViewWebPlugin::SiteForCookies() const {
  858. DCHECK(IsValid());
  859. return client_->SiteForCookies();
  860. }
  861. void PdfViewWebPlugin::SetReferrerForRequest(
  862. blink::WebURLRequest& request,
  863. const blink::WebURL& referrer_url) {
  864. client_->SetReferrerForRequest(request, referrer_url);
  865. }
  866. std::unique_ptr<blink::WebAssociatedURLLoader>
  867. PdfViewWebPlugin::CreateAssociatedURLLoader(
  868. const blink::WebAssociatedURLLoaderOptions& options) {
  869. return client_->CreateAssociatedURLLoader(options);
  870. }
  871. void PdfViewWebPlugin::OnMessage(const base::Value::Dict& message) {
  872. using MessageHandler = void (PdfViewWebPlugin::*)(const base::Value::Dict&);
  873. // Settings this as const instead of constexpr to workaround a bug
  874. // in GCC, that will try to reinterpret_cast the method pointers.
  875. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105996
  876. // TODO(crbug.com/1302059): make it constexpr again when we get rid
  877. // of PdfViewPluginBase
  878. static const auto kMessageHandlers =
  879. base::MakeFixedFlatMap<base::StringPiece, MessageHandler>({
  880. {"displayAnnotations",
  881. &PdfViewWebPlugin::HandleDisplayAnnotationsMessage},
  882. {"getNamedDestination",
  883. &PdfViewWebPlugin::HandleGetNamedDestinationMessage},
  884. {"getPasswordComplete",
  885. &PdfViewWebPlugin::HandleGetPasswordCompleteMessage},
  886. {"getSelectedText", &PdfViewWebPlugin::HandleGetSelectedTextMessage},
  887. {"getThumbnail", &PdfViewWebPlugin::HandleGetThumbnailMessage},
  888. {"print", &PdfViewWebPlugin::HandlePrintMessage},
  889. {"loadPreviewPage", &PdfViewWebPlugin::HandleLoadPreviewPageMessage},
  890. {"resetPrintPreviewMode",
  891. &PdfViewWebPlugin::HandleResetPrintPreviewModeMessage},
  892. {"rotateClockwise", &PdfViewWebPlugin::HandleRotateClockwiseMessage},
  893. {"rotateCounterclockwise",
  894. &PdfViewWebPlugin::HandleRotateCounterclockwiseMessage},
  895. {"save", &PdfViewWebPlugin::HandleSaveMessage},
  896. {"saveAttachment", &PdfViewWebPlugin::HandleSaveAttachmentMessage},
  897. {"selectAll", &PdfViewWebPlugin::HandleSelectAllMessage},
  898. {"setBackgroundColor",
  899. &PdfViewWebPlugin::HandleSetBackgroundColorMessage},
  900. {"setPresentationMode",
  901. &PdfViewWebPlugin::HandleSetPresentationModeMessage},
  902. {"setTwoUpView", &PdfViewWebPlugin::HandleSetTwoUpViewMessage},
  903. {"stopScrolling", &PdfViewWebPlugin::HandleStopScrollingMessage},
  904. {"viewport", &PdfViewWebPlugin::HandleViewportMessage},
  905. });
  906. MessageHandler handler = kMessageHandlers.at(*message.FindString("type"));
  907. (this->*handler)(message);
  908. }
  909. void PdfViewWebPlugin::HandleDisplayAnnotationsMessage(
  910. const base::Value::Dict& message) {
  911. engine_->DisplayAnnotations(message.FindBool("display").value());
  912. }
  913. void PdfViewWebPlugin::HandleGetNamedDestinationMessage(
  914. const base::Value::Dict& message) {
  915. absl::optional<PDFEngine::NamedDestination> named_destination =
  916. engine_->GetNamedDestination(*message.FindString("namedDestination"));
  917. const int page_number = named_destination.has_value()
  918. ? base::checked_cast<int>(named_destination->page)
  919. : -1;
  920. base::Value::Dict reply =
  921. PrepareReplyMessage("getNamedDestinationReply", message);
  922. reply.Set("pageNumber", page_number);
  923. if (named_destination.has_value() && !named_destination->view.empty()) {
  924. std::ostringstream view_stream;
  925. view_stream << named_destination->view;
  926. if (named_destination->xyz_params.empty()) {
  927. for (unsigned long i = 0; i < named_destination->num_params; ++i)
  928. view_stream << "," << named_destination->params[i];
  929. } else {
  930. view_stream << "," << named_destination->xyz_params;
  931. }
  932. reply.Set("namedDestinationView", view_stream.str());
  933. }
  934. SendMessage(std::move(reply));
  935. }
  936. void PdfViewWebPlugin::HandleGetPasswordCompleteMessage(
  937. const base::Value::Dict& message) {
  938. DCHECK(password_callback_);
  939. std::move(password_callback_).Run(*message.FindString("password"));
  940. }
  941. void PdfViewWebPlugin::HandleGetSelectedTextMessage(
  942. const base::Value::Dict& message) {
  943. // Always return unix newlines to JavaScript.
  944. std::string selected_text;
  945. base::RemoveChars(engine_->GetSelectedText(), "\r", &selected_text);
  946. base::Value::Dict reply =
  947. PrepareReplyMessage("getSelectedTextReply", message);
  948. reply.Set("selectedText", selected_text);
  949. SendMessage(std::move(reply));
  950. }
  951. void PdfViewWebPlugin::HandleGetThumbnailMessage(
  952. const base::Value::Dict& message) {
  953. const int page_index = message.FindInt("page").value();
  954. base::Value::Dict reply = PrepareReplyMessage("getThumbnailReply", message);
  955. engine_->RequestThumbnail(
  956. page_index, device_scale(),
  957. base::BindOnce(&PdfViewWebPlugin::SendThumbnail,
  958. weak_factory_.GetWeakPtr(), std::move(reply)));
  959. }
  960. void PdfViewWebPlugin::HandlePrintMessage(
  961. const base::Value::Dict& /*message*/) {
  962. Print();
  963. }
  964. void PdfViewWebPlugin::HandleRotateClockwiseMessage(
  965. const base::Value::Dict& /*message*/) {
  966. engine_->RotateClockwise();
  967. }
  968. void PdfViewWebPlugin::HandleRotateCounterclockwiseMessage(
  969. const base::Value::Dict& /*message*/) {
  970. engine_->RotateCounterclockwise();
  971. }
  972. void PdfViewWebPlugin::HandleSaveAttachmentMessage(
  973. const base::Value::Dict& message) {
  974. const int index = message.FindInt("attachmentIndex").value();
  975. const std::vector<DocumentAttachmentInfo>& list =
  976. engine_->GetDocumentAttachmentInfoList();
  977. DCHECK_GE(index, 0);
  978. DCHECK_LT(static_cast<size_t>(index), list.size());
  979. DCHECK(list[index].is_readable);
  980. DCHECK(IsSaveDataSizeValid(list[index].size_bytes));
  981. std::vector<uint8_t> data = engine_->GetAttachmentData(index);
  982. base::Value data_to_save(
  983. IsSaveDataSizeValid(data.size()) ? data : std::vector<uint8_t>());
  984. base::Value::Dict reply = PrepareReplyMessage("saveAttachmentReply", message);
  985. reply.Set("dataToSave", std::move(data_to_save));
  986. SendMessage(std::move(reply));
  987. }
  988. void PdfViewWebPlugin::HandleSaveMessage(const base::Value::Dict& message) {
  989. const std::string& token = *message.FindString("token");
  990. int request_type = message.FindInt("saveRequestType").value();
  991. DCHECK_GE(request_type, static_cast<int>(SaveRequestType::kAnnotation));
  992. DCHECK_LE(request_type, static_cast<int>(SaveRequestType::kEdited));
  993. switch (static_cast<SaveRequestType>(request_type)) {
  994. case SaveRequestType::kAnnotation:
  995. #if BUILDFLAG(ENABLE_INK)
  996. // In annotation mode, assume the user will make edits and prefer saving
  997. // using the plugin data.
  998. pdf_service_->SetPluginCanSave(true);
  999. SaveToBuffer(token);
  1000. #else
  1001. NOTREACHED();
  1002. #endif // BUILDFLAG(ENABLE_INK)
  1003. break;
  1004. case SaveRequestType::kOriginal:
  1005. pdf_service_->SetPluginCanSave(false);
  1006. SaveToFile(token);
  1007. pdf_service_->SetPluginCanSave(edit_mode_);
  1008. break;
  1009. case SaveRequestType::kEdited:
  1010. SaveToBuffer(token);
  1011. break;
  1012. }
  1013. }
  1014. void PdfViewWebPlugin::HandleSelectAllMessage(
  1015. const base::Value::Dict& /*message*/) {
  1016. engine_->SelectAll();
  1017. }
  1018. void PdfViewWebPlugin::HandleSetBackgroundColorMessage(
  1019. const base::Value::Dict& message) {
  1020. background_color_ =
  1021. base::checked_cast<SkColor>(message.FindDouble("color").value());
  1022. }
  1023. void PdfViewWebPlugin::HandleSetPresentationModeMessage(
  1024. const base::Value::Dict& message) {
  1025. engine_->SetReadOnly(message.FindBool("enablePresentationMode").value());
  1026. }
  1027. void PdfViewWebPlugin::HandleSetTwoUpViewMessage(
  1028. const base::Value::Dict& message) {
  1029. engine_->SetDocumentLayout(message.FindBool("enableTwoUpView").value()
  1030. ? DocumentLayout::PageSpread::kTwoUpOdd
  1031. : DocumentLayout::PageSpread::kOneUp);
  1032. }
  1033. void PdfViewWebPlugin::HandleStopScrollingMessage(
  1034. const base::Value::Dict& /*message*/) {
  1035. stop_scrolling_ = true;
  1036. }
  1037. void PdfViewWebPlugin::HandleViewportMessage(const base::Value::Dict& message) {
  1038. const base::Value::Dict* layout_options_value =
  1039. message.FindDict("layoutOptions");
  1040. if (layout_options_value) {
  1041. DocumentLayout::Options layout_options;
  1042. layout_options.FromValue(*layout_options_value);
  1043. ui_direction_ = layout_options.direction();
  1044. // TODO(crbug.com/1013800): Eliminate need to get document size from here.
  1045. set_document_size(engine_->ApplyDocumentLayout(layout_options));
  1046. OnGeometryChanged(zoom(), device_scale_);
  1047. if (!document_size().IsEmpty())
  1048. paint_manager().InvalidateRect(gfx::Rect(plugin_rect_.size()));
  1049. // Send 100% loading progress only after initial layout negotiated.
  1050. if (last_progress_sent() < 100 &&
  1051. document_load_state() == DocumentLoadState::kComplete) {
  1052. SendLoadingProgress(/*percentage=*/100);
  1053. }
  1054. }
  1055. gfx::Vector2dF scroll_offset(*message.FindDouble("xOffset"),
  1056. *message.FindDouble("yOffset"));
  1057. double new_zoom = *message.FindDouble("zoom");
  1058. const PinchPhase pinch_phase =
  1059. static_cast<PinchPhase>(*message.FindInt("pinchPhase"));
  1060. received_viewport_message_ = true;
  1061. stop_scrolling_ = false;
  1062. const double zoom_ratio = new_zoom / zoom();
  1063. if (pinch_phase == PinchPhase::kStart) {
  1064. scroll_offset_at_last_raster_ = scroll_offset;
  1065. last_bitmap_smaller_ = false;
  1066. needs_reraster_ = false;
  1067. return;
  1068. }
  1069. // When zooming in, we set a layer transform to avoid unneeded rerasters.
  1070. // Also, if we're zooming out and the last time we rerastered was when
  1071. // we were even further zoomed out (i.e. we pinch zoomed in and are now
  1072. // pinch zooming back out in the same gesture), we update the layer
  1073. // transform instead of rerastering.
  1074. if (pinch_phase == PinchPhase::kUpdateZoomIn ||
  1075. (pinch_phase == PinchPhase::kUpdateZoomOut && zoom_ratio > 1.0)) {
  1076. // Get the coordinates of the center of the pinch gesture.
  1077. const double pinch_x = *message.FindDouble("pinchX");
  1078. const double pinch_y = *message.FindDouble("pinchY");
  1079. gfx::Point pinch_center(pinch_x, pinch_y);
  1080. // Get the pinch vector which represents the panning caused by the change in
  1081. // pinch center between the start and the end of the gesture.
  1082. const double pinch_vector_x = *message.FindDouble("pinchVectorX");
  1083. const double pinch_vector_y = *message.FindDouble("pinchVectorY");
  1084. gfx::Vector2d pinch_vector =
  1085. gfx::Vector2d(pinch_vector_x * zoom_ratio, pinch_vector_y * zoom_ratio);
  1086. gfx::Vector2d scroll_delta;
  1087. // If the rendered document doesn't fill the display area we will
  1088. // use `paint_offset` to anchor the paint vertically into the same place.
  1089. // We use the scroll bars instead of the pinch vector to get the actual
  1090. // position on screen of the paint.
  1091. gfx::Vector2d paint_offset;
  1092. if (plugin_rect_.width() > GetDocumentPixelWidth() * zoom_ratio) {
  1093. // We want to keep the paint in the middle but it must stay in the same
  1094. // position relative to the scroll bars.
  1095. paint_offset = gfx::Vector2d(0, (1 - zoom_ratio) * pinch_center.y());
  1096. scroll_delta = gfx::Vector2d(
  1097. 0,
  1098. (scroll_offset.y() - scroll_offset_at_last_raster_.y() * zoom_ratio));
  1099. pinch_vector = gfx::Vector2d();
  1100. last_bitmap_smaller_ = true;
  1101. } else if (last_bitmap_smaller_) {
  1102. // When the document width covers the display area's width, we will anchor
  1103. // the scroll bars disregarding where the actual pinch certer is.
  1104. pinch_center = gfx::Point((plugin_rect_.width() / device_scale_) / 2,
  1105. (plugin_rect_.height() / device_scale_) / 2);
  1106. const double zoom_when_doc_covers_plugin_width =
  1107. zoom() * plugin_rect_.width() / GetDocumentPixelWidth();
  1108. paint_offset = gfx::Vector2d(
  1109. (1 - new_zoom / zoom_when_doc_covers_plugin_width) * pinch_center.x(),
  1110. (1 - zoom_ratio) * pinch_center.y());
  1111. pinch_vector = gfx::Vector2d();
  1112. scroll_delta = gfx::Vector2d(
  1113. (scroll_offset.x() - scroll_offset_at_last_raster_.x() * zoom_ratio),
  1114. (scroll_offset.y() - scroll_offset_at_last_raster_.y() * zoom_ratio));
  1115. }
  1116. paint_manager().SetTransform(zoom_ratio, pinch_center,
  1117. pinch_vector + paint_offset + scroll_delta,
  1118. true);
  1119. needs_reraster_ = false;
  1120. return;
  1121. }
  1122. if (pinch_phase == PinchPhase::kUpdateZoomOut ||
  1123. pinch_phase == PinchPhase::kEnd) {
  1124. // We reraster on pinch zoom out in order to solve the invalid regions
  1125. // that appear after zooming out.
  1126. // On pinch end the scale is again 1.f and we request a reraster
  1127. // in the new position.
  1128. paint_manager().ClearTransform();
  1129. last_bitmap_smaller_ = false;
  1130. needs_reraster_ = true;
  1131. // If we're rerastering due to zooming out, we need to update the scroll
  1132. // offset for the last raster, in case the user continues the gesture by
  1133. // zooming in.
  1134. scroll_offset_at_last_raster_ = scroll_offset;
  1135. }
  1136. // Bound the input parameters.
  1137. new_zoom = std::max(kMinZoom, new_zoom);
  1138. DCHECK(message.FindBool("userInitiated").has_value());
  1139. SetZoom(new_zoom);
  1140. UpdateScroll(GetScrollPositionFromOffset(scroll_offset));
  1141. }
  1142. void PdfViewWebPlugin::SaveToBuffer(const std::string& token) {
  1143. engine_->KillFormFocus();
  1144. base::Value::Dict message;
  1145. message.Set("type", "saveData");
  1146. message.Set("token", token);
  1147. message.Set("fileName", GetFileNameForSaveFromUrl(url_));
  1148. // Expose `edit_mode_` state for integration testing.
  1149. message.Set("editModeForTesting", edit_mode_);
  1150. base::Value data_to_save;
  1151. if (edit_mode_) {
  1152. base::Value::BlobStorage data = engine_->GetSaveData();
  1153. if (IsSaveDataSizeValid(data.size()))
  1154. data_to_save = base::Value(std::move(data));
  1155. } else {
  1156. #if BUILDFLAG(ENABLE_INK)
  1157. uint32_t length = engine_->GetLoadedByteSize();
  1158. if (IsSaveDataSizeValid(length)) {
  1159. base::Value::BlobStorage data(length);
  1160. if (engine_->ReadLoadedBytes(length, data.data()))
  1161. data_to_save = base::Value(std::move(data));
  1162. }
  1163. #else
  1164. NOTREACHED();
  1165. #endif // BUILDFLAG(ENABLE_INK)
  1166. }
  1167. message.Set("dataToSave", std::move(data_to_save));
  1168. SendMessage(std::move(message));
  1169. }
  1170. void PdfViewWebPlugin::SaveToFile(const std::string& token) {
  1171. engine_->KillFormFocus();
  1172. base::Value::Dict message;
  1173. message.Set("type", "consumeSaveToken");
  1174. message.Set("token", token);
  1175. SendMessage(std::move(message));
  1176. // TODO(crbug.com/1302059): Is there a good reason to null-terminate here?
  1177. pdf_service_->SaveUrlAs(GURL(url_.c_str()),
  1178. network::mojom::ReferrerPolicy::kDefault);
  1179. }
  1180. void PdfViewWebPlugin::InvalidatePluginContainer() {
  1181. client_->Invalidate();
  1182. }
  1183. void PdfViewWebPlugin::UpdateSnapshot(sk_sp<SkImage> snapshot) {
  1184. snapshot_ =
  1185. cc::PaintImageBuilder::WithDefault()
  1186. .set_image(std::move(snapshot), cc::PaintImage::GetNextContentId())
  1187. .set_id(cc::PaintImage::GetNextId())
  1188. .TakePaintImage();
  1189. if (!plugin_rect_.IsEmpty())
  1190. InvalidatePluginContainer();
  1191. }
  1192. void PdfViewWebPlugin::UpdateScaledValues() {
  1193. total_translate_ = snapshot_translate_;
  1194. if (viewport_to_dip_scale_ != 1.0f)
  1195. total_translate_.Scale(1.0f / viewport_to_dip_scale_);
  1196. }
  1197. void PdfViewWebPlugin::UpdateScale(float scale) {
  1198. if (scale <= 0.0f) {
  1199. NOTREACHED();
  1200. return;
  1201. }
  1202. viewport_to_dip_scale_ = scale;
  1203. device_to_css_scale_ = 1.0f;
  1204. UpdateScaledValues();
  1205. }
  1206. void PdfViewWebPlugin::UpdateLayerTransform(float scale,
  1207. const gfx::Vector2dF& translate) {
  1208. snapshot_translate_ = translate;
  1209. snapshot_scale_ = scale;
  1210. UpdateScaledValues();
  1211. }
  1212. void PdfViewWebPlugin::EnableAccessibility() {
  1213. if (accessibility_state() == AccessibilityState::kLoaded)
  1214. return;
  1215. if (accessibility_state() == AccessibilityState::kOff)
  1216. set_accessibility_state(AccessibilityState::kPending);
  1217. if (document_load_state() == DocumentLoadState::kComplete)
  1218. LoadAccessibility();
  1219. }
  1220. void PdfViewWebPlugin::HandleAccessibilityAction(
  1221. const AccessibilityActionData& action_data) {
  1222. engine_->HandleAccessibilityAction(action_data);
  1223. }
  1224. base::WeakPtr<PdfViewPluginBase> PdfViewWebPlugin::GetWeakPtr() {
  1225. return weak_factory_.GetWeakPtr();
  1226. }
  1227. void PdfViewWebPlugin::OnPrintPreviewLoaded() {
  1228. // Scroll location is retained across document loads in Print Preview, so
  1229. // there's no need to override the scroll position by scrolling again.
  1230. if (IsPreviewingPDF(print_preview_page_count_)) {
  1231. SendPrintPreviewLoadedNotification();
  1232. } else {
  1233. DCHECK_EQ(0, print_preview_loaded_page_count_);
  1234. print_preview_loaded_page_count_ = 1;
  1235. engine_->AppendBlankPages(print_preview_page_count_);
  1236. LoadNextPreviewPage();
  1237. }
  1238. OnGeometryChanged(0, 0);
  1239. if (!document_size().IsEmpty())
  1240. paint_manager().InvalidateRect(gfx::Rect(plugin_rect_.size()));
  1241. }
  1242. void PdfViewWebPlugin::OnDocumentLoadComplete() {
  1243. RecordDocumentMetrics();
  1244. SendAttachments();
  1245. SendBookmarks();
  1246. SendMetadata();
  1247. if (accessibility_state() == AccessibilityState::kPending)
  1248. LoadAccessibility();
  1249. }
  1250. void PdfViewWebPlugin::SendMessage(base::Value::Dict message) {
  1251. client_->PostMessage(std::move(message));
  1252. }
  1253. void PdfViewWebPlugin::SetFormTextFieldInFocus(bool in_focus) {
  1254. text_input_type_ = in_focus ? blink::WebTextInputType::kWebTextInputTypeText
  1255. : blink::WebTextInputType::kWebTextInputTypeNone;
  1256. client_->UpdateTextInputState();
  1257. }
  1258. void PdfViewWebPlugin::SetAccessibilityDocInfo(AccessibilityDocInfo doc_info) {
  1259. pdf_accessibility_data_handler_->SetAccessibilityDocInfo(std::move(doc_info));
  1260. }
  1261. void PdfViewWebPlugin::SetAccessibilityPageInfo(
  1262. AccessibilityPageInfo page_info,
  1263. std::vector<AccessibilityTextRunInfo> text_runs,
  1264. std::vector<AccessibilityCharInfo> chars,
  1265. AccessibilityPageObjects page_objects) {
  1266. pdf_accessibility_data_handler_->SetAccessibilityPageInfo(
  1267. std::move(page_info), std::move(text_runs), std::move(chars),
  1268. std::move(page_objects));
  1269. }
  1270. void PdfViewWebPlugin::SetAccessibilityViewportInfo(
  1271. AccessibilityViewportInfo viewport_info) {
  1272. pdf_accessibility_data_handler_->SetAccessibilityViewportInfo(
  1273. std::move(viewport_info));
  1274. }
  1275. void PdfViewWebPlugin::SetContentRestrictions(int content_restrictions) {
  1276. pdf_service_->UpdateContentRestrictions(content_restrictions);
  1277. }
  1278. void PdfViewWebPlugin::DidStartLoading() {
  1279. if (did_call_start_loading_)
  1280. return;
  1281. client_->DidStartLoading();
  1282. did_call_start_loading_ = true;
  1283. }
  1284. void PdfViewWebPlugin::DidStopLoading() {
  1285. if (!did_call_start_loading_)
  1286. return;
  1287. client_->DidStopLoading();
  1288. did_call_start_loading_ = false;
  1289. }
  1290. void PdfViewWebPlugin::NotifySelectionChanged(const gfx::PointF& left,
  1291. int left_height,
  1292. const gfx::PointF& right,
  1293. int right_height) {
  1294. pdf_service_->SelectionChanged(left, left_height, right, right_height);
  1295. }
  1296. // TODO(crbug.com/1302059): Delete after merging with `PdfViewPluginBase`.
  1297. void PdfViewWebPlugin::UserMetricsRecordAction(const std::string& action) {
  1298. client_->RecordComputedAction(action);
  1299. }
  1300. // TODO(crbug.com/1302059): Delete after merging with `PdfViewPluginBase`.
  1301. bool PdfViewWebPlugin::full_frame() const {
  1302. return full_frame_;
  1303. }
  1304. // TODO(crbug.com/1302059): Delete after merging with `PdfViewPluginBase`.
  1305. const gfx::Size& PdfViewWebPlugin::plugin_dip_size() const {
  1306. return plugin_dip_size_;
  1307. }
  1308. // TODO(crbug.com/1302059): Delete after merging with `PdfViewPluginBase`.
  1309. const gfx::Rect& PdfViewWebPlugin::plugin_rect() const {
  1310. return plugin_rect_;
  1311. }
  1312. // TODO(crbug.com/1302059): Delete after merging with `PdfViewPluginBase`.
  1313. float PdfViewWebPlugin::device_scale() const {
  1314. return device_scale_;
  1315. }
  1316. // TODO(crbug.com/1302059): Delete after merging with `PdfViewPluginBase`.
  1317. bool PdfViewWebPlugin::needs_reraster() const {
  1318. return needs_reraster_;
  1319. }
  1320. // TODO(crbug.com/1302059): Delete after merging with `PdfViewPluginBase`.
  1321. base::i18n::TextDirection PdfViewWebPlugin::ui_direction() const {
  1322. return ui_direction_;
  1323. }
  1324. // TODO(crbug.com/1302059): Delete after merging with `PdfViewPluginBase`.
  1325. bool PdfViewWebPlugin::received_viewport_message() const {
  1326. return received_viewport_message_;
  1327. }
  1328. void PdfViewWebPlugin::OnViewportChanged(
  1329. const gfx::Rect& new_plugin_rect_in_css_pixel,
  1330. float new_device_scale) {
  1331. DCHECK_GT(new_device_scale, 0.0f);
  1332. css_plugin_rect_ = new_plugin_rect_in_css_pixel;
  1333. if (new_device_scale == device_scale_ &&
  1334. new_plugin_rect_in_css_pixel == plugin_rect_) {
  1335. return;
  1336. }
  1337. const float old_device_scale = device_scale_;
  1338. device_scale_ = new_device_scale;
  1339. plugin_rect_ = new_plugin_rect_in_css_pixel;
  1340. // TODO(crbug.com/1250173): We should try to avoid the downscaling in this
  1341. // calculation, perhaps by migrating off `plugin_dip_size_`.
  1342. plugin_dip_size_ = gfx::ScaleToEnclosingRect(new_plugin_rect_in_css_pixel,
  1343. 1.0f / new_device_scale)
  1344. .size();
  1345. paint_manager().SetSize(plugin_rect_.size(), device_scale_);
  1346. // Initialize the image data buffer if the context size changes.
  1347. const gfx::Size old_image_size =
  1348. gfx::SkISizeToSize(image_data().dimensions());
  1349. const gfx::Size new_image_size =
  1350. PaintManager::GetNewContextSize(old_image_size, plugin_rect_.size());
  1351. if (new_image_size != old_image_size) {
  1352. image_data().allocPixels(
  1353. SkImageInfo::MakeN32Premul(gfx::SizeToSkISize(new_image_size)));
  1354. first_paint_ = true;
  1355. }
  1356. // Skip updating the geometry if the new image data buffer is empty.
  1357. if (image_data().drawsNothing())
  1358. return;
  1359. OnGeometryChanged(zoom(), old_device_scale);
  1360. }
  1361. bool PdfViewWebPlugin::SelectAll() {
  1362. if (!CanEditText())
  1363. return false;
  1364. engine_->SelectAll();
  1365. return true;
  1366. }
  1367. bool PdfViewWebPlugin::Cut() {
  1368. if (!HasSelection() || !CanEditText())
  1369. return false;
  1370. engine_->ReplaceSelection("");
  1371. return true;
  1372. }
  1373. bool PdfViewWebPlugin::Paste(const blink::WebString& value) {
  1374. if (!CanEditText())
  1375. return false;
  1376. engine_->ReplaceSelection(value.Utf8());
  1377. return true;
  1378. }
  1379. bool PdfViewWebPlugin::Undo() {
  1380. if (!CanUndo())
  1381. return false;
  1382. engine_->Undo();
  1383. return true;
  1384. }
  1385. bool PdfViewWebPlugin::Redo() {
  1386. if (!CanRedo())
  1387. return false;
  1388. engine_->Redo();
  1389. return true;
  1390. }
  1391. bool PdfViewWebPlugin::HandleWebInputEvent(const blink::WebInputEvent& event) {
  1392. // Ignore user input in read-only mode.
  1393. if (engine_->IsReadOnly())
  1394. return false;
  1395. // `engine_` expects input events in device coordinates.
  1396. std::unique_ptr<blink::WebInputEvent> transformed_event =
  1397. ui::TranslateAndScaleWebInputEvent(
  1398. event, gfx::Vector2dF(-available_area().x() / device_scale(), 0),
  1399. device_scale());
  1400. const blink::WebInputEvent& event_to_handle =
  1401. transformed_event ? *transformed_event : event;
  1402. if (engine_->HandleInputEvent(event_to_handle))
  1403. return true;
  1404. // Middle click is used for scrolling and is handled by the container page.
  1405. if (blink::WebInputEvent::IsMouseEventType(event_to_handle.GetType()) &&
  1406. static_cast<const blink::WebMouseEvent&>(event_to_handle).button ==
  1407. blink::WebPointerProperties::Button::kMiddle) {
  1408. return false;
  1409. }
  1410. // Return true for unhandled clicks so the plugin takes focus.
  1411. return event_to_handle.GetType() == blink::WebInputEvent::Type::kMouseDown;
  1412. }
  1413. void PdfViewWebPlugin::HandleImeCommit(const blink::WebString& text) {
  1414. if (text.IsEmpty())
  1415. return;
  1416. std::u16string text16 = text.Utf16();
  1417. composition_text_.Reset();
  1418. size_t i = 0;
  1419. for (base::i18n::UTF16CharIterator iterator(text16); iterator.Advance();) {
  1420. blink::WebKeyboardEvent char_event(blink::WebInputEvent::Type::kChar,
  1421. blink::WebInputEvent::kNoModifiers,
  1422. ui::EventTimeForNow());
  1423. char_event.windows_key_code = text16[i];
  1424. char_event.native_key_code = text16[i];
  1425. for (const size_t char_start = i; i < iterator.array_pos(); ++i) {
  1426. char_event.text[i - char_start] = text16[i];
  1427. char_event.unmodified_text[i - char_start] = text16[i];
  1428. }
  1429. blink::WebCoalescedInputEvent input_event(char_event, ui::LatencyInfo());
  1430. ui::Cursor dummy_cursor_info;
  1431. HandleInputEvent(input_event, &dummy_cursor_info);
  1432. }
  1433. }
  1434. void PdfViewWebPlugin::OnInvokePrintDialog() {
  1435. client_->Print();
  1436. }
  1437. void PdfViewWebPlugin::ResetRecentlySentFindUpdate() {
  1438. recently_sent_find_update_ = false;
  1439. }
  1440. void PdfViewWebPlugin::RecordDocumentMetrics() {
  1441. if (!metrics_handler_)
  1442. return;
  1443. metrics_handler_->RecordDocumentMetrics(engine_->GetDocumentMetadata());
  1444. metrics_handler_->RecordAttachmentTypes(
  1445. engine_->GetDocumentAttachmentInfoList());
  1446. }
  1447. void PdfViewWebPlugin::SendAttachments() {
  1448. const std::vector<DocumentAttachmentInfo>& attachment_infos =
  1449. engine_->GetDocumentAttachmentInfoList();
  1450. if (attachment_infos.empty())
  1451. return;
  1452. base::Value::List attachments;
  1453. for (const DocumentAttachmentInfo& attachment_info : attachment_infos) {
  1454. // Send `size` as -1 to indicate that the attachment is too large to be
  1455. // downloaded.
  1456. const int size = attachment_info.size_bytes <= kMaximumSavedFileSize
  1457. ? static_cast<int>(attachment_info.size_bytes)
  1458. : -1;
  1459. base::Value::Dict attachment;
  1460. attachment.Set("name", attachment_info.name);
  1461. attachment.Set("size", size);
  1462. attachment.Set("readable", attachment_info.is_readable);
  1463. attachments.Append(std::move(attachment));
  1464. }
  1465. base::Value::Dict message;
  1466. message.Set("type", "attachments");
  1467. message.Set("attachmentsData", std::move(attachments));
  1468. SendMessage(std::move(message));
  1469. }
  1470. void PdfViewWebPlugin::SendBookmarks() {
  1471. base::Value::List bookmarks = engine_->GetBookmarks();
  1472. if (bookmarks.empty())
  1473. return;
  1474. base::Value::Dict message;
  1475. message.Set("type", "bookmarks");
  1476. message.Set("bookmarksData", std::move(bookmarks));
  1477. SendMessage(std::move(message));
  1478. }
  1479. void PdfViewWebPlugin::SendMetadata() {
  1480. base::Value::Dict metadata;
  1481. const DocumentMetadata& document_metadata = engine_->GetDocumentMetadata();
  1482. const std::string version = FormatPdfVersion(document_metadata.version);
  1483. if (!version.empty())
  1484. metadata.Set("version", version);
  1485. metadata.Set("fileSize", ui::FormatBytes(document_metadata.size_bytes));
  1486. metadata.Set("linearized", document_metadata.linearized);
  1487. if (!document_metadata.title.empty())
  1488. metadata.Set("title", document_metadata.title);
  1489. if (!document_metadata.author.empty())
  1490. metadata.Set("author", document_metadata.author);
  1491. if (!document_metadata.subject.empty())
  1492. metadata.Set("subject", document_metadata.subject);
  1493. if (!document_metadata.keywords.empty())
  1494. metadata.Set("keywords", document_metadata.keywords);
  1495. if (!document_metadata.creator.empty())
  1496. metadata.Set("creator", document_metadata.creator);
  1497. if (!document_metadata.producer.empty())
  1498. metadata.Set("producer", document_metadata.producer);
  1499. if (!document_metadata.creation_date.is_null()) {
  1500. metadata.Set("creationDate", base::TimeFormatShortDateAndTime(
  1501. document_metadata.creation_date));
  1502. }
  1503. if (!document_metadata.mod_date.is_null()) {
  1504. metadata.Set("modDate",
  1505. base::TimeFormatShortDateAndTime(document_metadata.mod_date));
  1506. }
  1507. metadata.Set("pageSize", FormatPageSize(engine_->GetUniformPageSizePoints()));
  1508. metadata.Set("canSerializeDocument",
  1509. IsSaveDataSizeValid(engine_->GetLoadedByteSize()));
  1510. base::Value::Dict message;
  1511. message.Set("type", "metadata");
  1512. message.Set("metadataData", std::move(metadata));
  1513. SendMessage(std::move(message));
  1514. }
  1515. void PdfViewWebPlugin::HandleResetPrintPreviewModeMessage(
  1516. const base::Value::Dict& message) {
  1517. const std::string& url = *message.FindString("url");
  1518. bool is_grayscale = message.FindBool("grayscale").value();
  1519. int print_preview_page_count = message.FindInt("pageCount").value();
  1520. // For security reasons, crash if `url` is not for Print Preview.
  1521. CHECK(IsPrintPreview());
  1522. CHECK(IsPrintPreviewUrl(url));
  1523. DCHECK_GE(print_preview_page_count, 0);
  1524. int page_index = ExtractPrintPreviewPageIndex(url);
  1525. if (IsPreviewingPDF(print_preview_page_count)) {
  1526. DCHECK_EQ(page_index, kCompletePDFIndex);
  1527. } else {
  1528. DCHECK_GE(page_index, 0);
  1529. }
  1530. print_preview_page_count_ = print_preview_page_count;
  1531. print_preview_loaded_page_count_ = 0;
  1532. url_ = url;
  1533. preview_pages_info_ = base::queue<PreviewPageInfo>();
  1534. preview_document_load_state_ = DocumentLoadState::kComplete;
  1535. set_document_load_state(DocumentLoadState::kLoading);
  1536. set_last_progress_sent(0);
  1537. LoadUrl(url_, base::BindOnce(&PdfViewWebPlugin::DidOpen,
  1538. weak_factory_.GetWeakPtr()));
  1539. preview_engine_.reset();
  1540. // TODO(crbug.com/1237952): Figure out a more consistent way to preserve
  1541. // engine settings across a Print Preview reset.
  1542. engine_ = CreateEngine(this, PDFiumFormFiller::ScriptOption::kNoJavaScript);
  1543. engine_->ZoomUpdated(zoom() * device_scale_);
  1544. engine_->PageOffsetUpdated(available_area().OffsetFromOrigin());
  1545. engine_->PluginSizeUpdated(available_area().size());
  1546. engine_->SetGrayscale(is_grayscale);
  1547. paint_manager().InvalidateRect(gfx::Rect(plugin_rect_.size()));
  1548. }
  1549. void PdfViewWebPlugin::HandleLoadPreviewPageMessage(
  1550. const base::Value::Dict& message) {
  1551. const std::string& url = *message.FindString("url");
  1552. int dest_page_index = message.FindInt("index").value();
  1553. // For security reasons, crash if `url` is not for Print Preview.
  1554. CHECK(IsPrintPreview());
  1555. CHECK(IsPrintPreviewUrl(url));
  1556. DCHECK_GE(dest_page_index, 0);
  1557. DCHECK_LT(dest_page_index, print_preview_page_count_);
  1558. // Print Preview JS will send the loadPreviewPage message for every page,
  1559. // including the first page in the print preview, which has already been
  1560. // loaded when handing the resetPrintPreviewMode message. Just ignore it.
  1561. if (dest_page_index == 0)
  1562. return;
  1563. int src_page_index = ExtractPrintPreviewPageIndex(url);
  1564. DCHECK_GE(src_page_index, 0);
  1565. preview_pages_info_.push({.url = url, .dest_page_index = dest_page_index});
  1566. LoadAvailablePreviewPage();
  1567. }
  1568. void PdfViewWebPlugin::LoadAvailablePreviewPage() {
  1569. if (preview_pages_info_.empty() ||
  1570. document_load_state() != DocumentLoadState::kComplete ||
  1571. preview_document_load_state_ == DocumentLoadState::kLoading) {
  1572. return;
  1573. }
  1574. preview_document_load_state_ = DocumentLoadState::kLoading;
  1575. const std::string& url = preview_pages_info_.front().url;
  1576. // Note that `last_progress_sent_` is not reset for preview page loads.
  1577. LoadUrl(url, base::BindOnce(&PdfViewWebPlugin::DidOpenPreview,
  1578. weak_factory_.GetWeakPtr()));
  1579. }
  1580. void PdfViewWebPlugin::DidOpenPreview(std::unique_ptr<UrlLoader> loader,
  1581. int32_t result) {
  1582. DCHECK_EQ(result, kSuccess);
  1583. preview_client_ = std::make_unique<PreviewModeClient>(this);
  1584. preview_engine_ = CreateEngine(preview_client_.get(),
  1585. PDFiumFormFiller::ScriptOption::kNoJavaScript);
  1586. preview_engine_->PluginSizeUpdated({});
  1587. preview_engine_->HandleDocumentLoad(std::move(loader), url_);
  1588. }
  1589. void PdfViewWebPlugin::PreviewDocumentLoadComplete() {
  1590. if (preview_document_load_state_ != DocumentLoadState::kLoading ||
  1591. preview_pages_info_.empty()) {
  1592. return;
  1593. }
  1594. preview_document_load_state_ = DocumentLoadState::kComplete;
  1595. int dest_page_index = preview_pages_info_.front().dest_page_index;
  1596. DCHECK_GT(dest_page_index, 0);
  1597. preview_pages_info_.pop();
  1598. DCHECK(preview_engine_);
  1599. engine_->AppendPage(preview_engine_.get(), dest_page_index);
  1600. ++print_preview_loaded_page_count_;
  1601. LoadNextPreviewPage();
  1602. }
  1603. void PdfViewWebPlugin::PreviewDocumentLoadFailed() {
  1604. client_->RecordComputedAction("PDF.PreviewDocumentLoadFailure");
  1605. if (preview_document_load_state_ != DocumentLoadState::kLoading ||
  1606. preview_pages_info_.empty()) {
  1607. return;
  1608. }
  1609. // Even if a print preview page failed to load, keep going.
  1610. preview_document_load_state_ = DocumentLoadState::kFailed;
  1611. preview_pages_info_.pop();
  1612. ++print_preview_loaded_page_count_;
  1613. LoadNextPreviewPage();
  1614. }
  1615. void PdfViewWebPlugin::LoadNextPreviewPage() {
  1616. if (!preview_pages_info_.empty()) {
  1617. DCHECK_LT(print_preview_loaded_page_count_, print_preview_page_count_);
  1618. LoadAvailablePreviewPage();
  1619. return;
  1620. }
  1621. if (print_preview_loaded_page_count_ == print_preview_page_count_)
  1622. SendPrintPreviewLoadedNotification();
  1623. }
  1624. void PdfViewWebPlugin::SendPrintPreviewLoadedNotification() {
  1625. base::Value::Dict message;
  1626. message.Set("type", "printPreviewLoaded");
  1627. SendMessage(std::move(message));
  1628. }
  1629. void PdfViewWebPlugin::SendThumbnail(base::Value::Dict reply,
  1630. Thumbnail thumbnail) {
  1631. DCHECK_EQ(*reply.FindString("type"), "getThumbnailReply");
  1632. DCHECK(reply.FindString("messageId"));
  1633. reply.Set("imageData", thumbnail.TakeData());
  1634. reply.Set("width", thumbnail.image_size().width());
  1635. reply.Set("height", thumbnail.image_size().height());
  1636. SendMessage(std::move(reply));
  1637. }
  1638. } // namespace chrome_pdf