metafile.cc 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2014 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 "printing/metafile.h"
  5. #include <stdint.h>
  6. #include <vector>
  7. #include "base/files/file.h"
  8. #include "base/logging.h"
  9. #include "base/memory/read_only_shared_memory_region.h"
  10. #include "base/numerics/safe_conversions.h"
  11. #include "build/build_config.h"
  12. namespace printing {
  13. MetafilePlayer::MetafilePlayer() = default;
  14. MetafilePlayer::~MetafilePlayer() = default;
  15. Metafile::Metafile() = default;
  16. Metafile::~Metafile() = default;
  17. bool Metafile::GetDataAsVector(std::vector<char>* buffer) const {
  18. buffer->resize(GetDataSize());
  19. if (buffer->empty())
  20. return false;
  21. return GetData(&buffer->front(),
  22. base::checked_cast<uint32_t>(buffer->size()));
  23. }
  24. base::MappedReadOnlyRegion Metafile::GetDataAsSharedMemoryRegion() const {
  25. uint32_t data_size = GetDataSize();
  26. if (data_size == 0) {
  27. DLOG(ERROR) << "Metafile has no data to map to a region.";
  28. return base::MappedReadOnlyRegion();
  29. }
  30. base::MappedReadOnlyRegion region_mapping =
  31. base::ReadOnlySharedMemoryRegion::Create(data_size);
  32. if (!region_mapping.IsValid()) {
  33. DLOG(ERROR) << "Failure mapping metafile data into region for size "
  34. << data_size;
  35. return base::MappedReadOnlyRegion();
  36. }
  37. if (!GetData(region_mapping.mapping.memory(), data_size)) {
  38. DLOG(ERROR) << "Failure getting metafile data into region";
  39. return base::MappedReadOnlyRegion();
  40. }
  41. return region_mapping;
  42. }
  43. #if !BUILDFLAG(IS_ANDROID)
  44. bool Metafile::SaveTo(base::File* file) const {
  45. if (!file->IsValid())
  46. return false;
  47. std::vector<char> buffer;
  48. if (!GetDataAsVector(&buffer))
  49. return false;
  50. if (!file->WriteAtCurrentPosAndCheck(
  51. base::as_bytes(base::make_span(buffer)))) {
  52. DLOG(ERROR) << "Failed to save file.";
  53. return false;
  54. }
  55. return true;
  56. }
  57. #endif // !BUILDFLAG(IS_ANDROID)
  58. } // namespace printing