// services/shape_detection/public/mojom/facedetection.mojom-blink.cc is auto generated by mojom_bindings_generator.py, do not edit

// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-private-field"
#endif

#include "services/shape_detection/public/mojom/facedetection.mojom-blink.h"
#include <math.h>
#include <stdint.h>
#include <utility>
#include "base/debug/alias.h"
#include "base/notreached.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "base/trace_event/trace_event.h"
#include "base/trace_event/typed_macros.h"
#include "mojo/public/cpp/bindings/lib/default_construct_tag_internal.h"
#include "mojo/public/cpp/bindings/lib/generated_code_util.h"
#include "mojo/public/cpp/bindings/lib/message_internal.h"
#include "mojo/public/cpp/bindings/lib/proxy_to_responder.h"
#include "mojo/public/cpp/bindings/lib/send_message_helper.h"
#include "mojo/public/cpp/bindings/lib/serialization.h"
#include "mojo/public/cpp/bindings/lib/unserialized_message_context.h"
#include "mojo/public/cpp/bindings/lib/validate_params.h"
#include "mojo/public/cpp/bindings/lib/validation_errors.h"
#include "mojo/public/cpp/bindings/mojo_buildflags.h"
#include "mojo/public/cpp/bindings/urgent_message_scope.h"
#include "mojo/public/interfaces/bindings/interface_control_messages.mojom.h"
#include "third_party/perfetto/include/perfetto/tracing/traced_value.h"

#include "services/shape_detection/public/mojom/facedetection.mojom-params-data.h"
#include "services/shape_detection/public/mojom/facedetection.mojom-shared-message-ids.h"

#include "services/shape_detection/public/mojom/facedetection.mojom-blink-import-headers.h"
#include "services/shape_detection/public/mojom/facedetection.mojom-blink-test-utils.h"
#include "mojo/public/cpp/bindings/lib/wtf_serialization.h"


namespace shape_detection::mojom::blink {
Landmark::Landmark()
    : locations(),
      type() {}

Landmark::Landmark(
    ::blink::Vector<::gfx::PointF> locations_in,
    LandmarkType type_in)
    : locations(std::move(locations_in)),
      type(std::move(type_in)) {}

Landmark::~Landmark() = default;

void Landmark::WriteIntoTrace(
    perfetto::TracedValue traced_context) const {
  [[maybe_unused]] auto dict = std::move(traced_context).WriteDictionary();
  perfetto::WriteIntoTracedValueWithFallback(
    dict.AddItem(
      "locations"), this->locations,
#if BUILDFLAG(MOJO_TRACE_ENABLED)
      "<value of type const ::blink::Vector<::gfx::PointF>&>"
#else
      "<value>"
#endif  // BUILDFLAG(MOJO_TRACE_ENABLED)
    );
  perfetto::WriteIntoTracedValueWithFallback(
    dict.AddItem(
      "type"), this->type,
#if BUILDFLAG(MOJO_TRACE_ENABLED)
      "<value of type LandmarkType>"
#else
      "<value>"
#endif  // BUILDFLAG(MOJO_TRACE_ENABLED)
    );
}

bool Landmark::Validate(
    const void* data,
    mojo::internal::ValidationContext* validation_context) {
  return Data_::Validate(data, validation_context);
}
FaceDetectionResult::FaceDetectionResult()
    : bounding_box(),
      landmarks() {}

FaceDetectionResult::FaceDetectionResult(
    const ::gfx::RectF& bounding_box_in,
    ::blink::Vector<LandmarkPtr> landmarks_in)
    : bounding_box(std::move(bounding_box_in)),
      landmarks(std::move(landmarks_in)) {}

FaceDetectionResult::~FaceDetectionResult() = default;

void FaceDetectionResult::WriteIntoTrace(
    perfetto::TracedValue traced_context) const {
  [[maybe_unused]] auto dict = std::move(traced_context).WriteDictionary();
  perfetto::WriteIntoTracedValueWithFallback(
    dict.AddItem(
      "bounding_box"), this->bounding_box,
#if BUILDFLAG(MOJO_TRACE_ENABLED)
      "<value of type const ::gfx::RectF&>"
#else
      "<value>"
#endif  // BUILDFLAG(MOJO_TRACE_ENABLED)
    );
  perfetto::WriteIntoTracedValueWithFallback(
    dict.AddItem(
      "landmarks"), this->landmarks,
#if BUILDFLAG(MOJO_TRACE_ENABLED)
      "<value of type ::blink::Vector<LandmarkPtr>>"
#else
      "<value>"
#endif  // BUILDFLAG(MOJO_TRACE_ENABLED)
    );
}

bool FaceDetectionResult::Validate(
    const void* data,
    mojo::internal::ValidationContext* validation_context) {
  return Data_::Validate(data, validation_context);
}
FaceDetectorOptions::FaceDetectorOptions()
    : max_detected_faces(),
      fast_mode() {}

FaceDetectorOptions::FaceDetectorOptions(
    uint32_t max_detected_faces_in,
    bool fast_mode_in)
    : max_detected_faces(std::move(max_detected_faces_in)),
      fast_mode(std::move(fast_mode_in)) {}

FaceDetectorOptions::~FaceDetectorOptions() = default;
size_t FaceDetectorOptions::Hash(size_t seed) const {
  seed = mojo::internal::WTFHash(seed, this->max_detected_faces);
  seed = mojo::internal::WTFHash(seed, this->fast_mode);
  return seed;
}

void FaceDetectorOptions::WriteIntoTrace(
    perfetto::TracedValue traced_context) const {
  [[maybe_unused]] auto dict = std::move(traced_context).WriteDictionary();
  perfetto::WriteIntoTracedValueWithFallback(
    dict.AddItem(
      "max_detected_faces"), this->max_detected_faces,
#if BUILDFLAG(MOJO_TRACE_ENABLED)
      "<value of type uint32_t>"
#else
      "<value>"
#endif  // BUILDFLAG(MOJO_TRACE_ENABLED)
    );
  perfetto::WriteIntoTracedValueWithFallback(
    dict.AddItem(
      "fast_mode"), this->fast_mode,
#if BUILDFLAG(MOJO_TRACE_ENABLED)
      "<value of type bool>"
#else
      "<value>"
#endif  // BUILDFLAG(MOJO_TRACE_ENABLED)
    );
}

bool FaceDetectorOptions::Validate(
    const void* data,
    mojo::internal::ValidationContext* validation_context) {
  return Data_::Validate(data, validation_context);
}
// The declaration includes the definition on other builds.

FaceDetection::IPCStableHashFunction FaceDetection::MessageToMethodInfo_(mojo::Message& message) {
#if !BUILDFLAG(IS_FUCHSIA)
  switch (static_cast<messages::FaceDetection>(message.name())) {
    case messages::FaceDetection::kDetect: {
      return &FaceDetection::Detect_Sym::IPCStableHash;
    }
  }
#endif  // !BUILDFLAG(IS_FUCHSIA)
  return nullptr;
}


const char* FaceDetection::MessageToMethodName_(mojo::Message& message) {
#if BUILDFLAG(MOJO_TRACE_ENABLED)
  bool is_response = message.has_flag(mojo::Message::kFlagIsResponse);
  if (!is_response) {
    switch (static_cast<messages::FaceDetection>(message.name())) {
      case messages::FaceDetection::kDetect:
            return "Receive shape_detection::mojom::FaceDetection::Detect";
    }
  } else {
    switch (static_cast<messages::FaceDetection>(message.name())) {
      case messages::FaceDetection::kDetect:
            return "Receive reply shape_detection::mojom::FaceDetection::Detect";
    }
  }
  return "Receive unknown mojo message";
#else
  bool is_response = message.has_flag(mojo::Message::kFlagIsResponse);
  if (is_response) {
    return "Receive mojo reply";
  } else {
    return "Receive mojo message";
  }
#endif // BUILDFLAG(MOJO_TRACE_ENABLED)
}

#if !BUILDFLAG(IS_FUCHSIA)
uint32_t FaceDetection::Detect_Sym::IPCStableHash() {
  // This method's address is used for identifying the mojo method name after
  // symbolization. So each IPCStableHash should have a unique address.
  // We cannot use NO_CODE_FOLDING() here - it relies on the uniqueness of
  // __LINE__ value, which is not unique across different mojo modules.
  // The code below is very similar to NO_CODE_FOLDING, but it uses a unique
  // hash instead of __LINE__.
  static constexpr uint32_t kHash = 0x95eddb99;  // IPCStableHash for shape_detection::mojom::FaceDetection::Detect
  const uint32_t hash = kHash;
  base::debug::Alias(&hash);
  return hash;
}
# endif // !BUILDFLAG(IS_FUCHSIA)

class FaceDetection_Detect_ForwardToCallback
    : public mojo::MessageReceiver {
 public:
  FaceDetection_Detect_ForwardToCallback(
      FaceDetection::DetectCallback callback
      ) : callback_(std::move(callback)) {
  }

  FaceDetection_Detect_ForwardToCallback(const FaceDetection_Detect_ForwardToCallback&) = delete;
  FaceDetection_Detect_ForwardToCallback& operator=(const FaceDetection_Detect_ForwardToCallback&) = delete;

  bool Accept(mojo::Message* message) override;
 private:
  FaceDetection::DetectCallback callback_;
};

FaceDetectionProxy::FaceDetectionProxy(mojo::MessageReceiverWithResponder* receiver)
    : receiver_(receiver) {
}

void FaceDetectionProxy::Detect(
    const ::SkBitmap& in_bitmap_data, DetectCallback callback) {
#if BUILDFLAG(MOJO_TRACE_ENABLED)
  TRACE_EVENT1(
    "mojom", "Send shape_detection::mojom::FaceDetection::Detect", "input_parameters",
    [&](perfetto::TracedValue context){
      auto dict = std::move(context).WriteDictionary();
      perfetto::WriteIntoTracedValueWithFallback(
           dict.AddItem("bitmap_data"), in_bitmap_data,
                        "<value of type const ::SkBitmap&>");
   });
#endif

  const bool kExpectsResponse = true;
  const bool kIsSync = false;
  const bool kAllowInterrupt = true;
  const bool is_urgent = false;

  const uint32_t kFlags =
      ((kExpectsResponse) ? mojo::Message::kFlagExpectsResponse : 0) |
      ((kIsSync) ? mojo::Message::kFlagIsSync : 0) |
      ((kAllowInterrupt) ? 0 : mojo::Message::kFlagNoInterrupt) |
      ((is_urgent) ? mojo::Message::kFlagIsUrgent : 0);

  const size_t estimated_payload_size =
    0;
  mojo::Message message(
      std::to_underlying(messages::FaceDetection::kDetect), kFlags, estimated_payload_size);
  mojo::internal::MessageFragment<
      ::shape_detection::mojom::internal::FaceDetection_Detect_Params_Data> params(
          message);
  params.Allocate();
  mojo::internal::MessageFragment<
      typename decltype(params->bitmap_data)::BaseType> bitmap_data_fragment(
          params.message());
  
  mojo::internal::Serialize<::skia::mojom::BitmapN32DataView>(
    in_bitmap_data,
    bitmap_data_fragment);

  params->bitmap_data.Set(
      bitmap_data_fragment.is_null() ? nullptr : bitmap_data_fragment.data());

  
  MOJO_INTERNAL_CHECK_SERIALIZATION(
    mojo::internal::SendValidation::kDefault,
    !(params->bitmap_data.is_null()),
    mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER,
    "null bitmap_data in FaceDetection.Detect request");

#if defined(ENABLE_IPC_FUZZER)
  message.set_interface_name(FaceDetection::Name_);
  message.set_method_name("Detect");
#endif
  std::unique_ptr<mojo::MessageReceiver> responder(
      new FaceDetection_Detect_ForwardToCallback(
          std::move(callback)));
  ::mojo::internal::SendMojoMessage(*receiver_, message, std::move(responder));
}
class FaceDetection_Detect_ProxyToResponder : public ::mojo::internal::ProxyToResponder {
 public:
  static FaceDetection::DetectCallback CreateCallback(
      ::mojo::Message& message,
      std::unique_ptr<mojo::MessageReceiverWithStatus> responder) {
    std::unique_ptr<FaceDetection_Detect_ProxyToResponder> proxy(
        new FaceDetection_Detect_ProxyToResponder(
            message, std::move(responder)));
    return base::BindOnce(&FaceDetection_Detect_ProxyToResponder::Run,
                          std::move(proxy));
  }

  ~FaceDetection_Detect_ProxyToResponder() {
#if DCHECK_IS_ON()
    if (responder_) {
      // If we're being destroyed without being run, we want to ensure the
      // binding endpoint has been closed. This checks for that asynchronously.
      // We pass a bound generated callback to handle the response so that any
      // resulting DCHECK stack will have useful interface type information.
      // Instantiate a ScopedFizzleBlockShutdownTasks to allow this request to
      // fizzle if this happens after shutdown and the endpoint is bound to a
      // BLOCK_SHUTDOWN sequence.
      base::ThreadPoolInstance::ScopedFizzleBlockShutdownTasks fizzler;
      responder_->IsConnectedAsync(base::BindOnce(&OnIsConnectedComplete));
    }
#endif
  }

 private:
  FaceDetection_Detect_ProxyToResponder(
      ::mojo::Message& message,
      std::unique_ptr<mojo::MessageReceiverWithStatus> responder)
      : ::mojo::internal::ProxyToResponder(message, std::move(responder)) {
  }

#if DCHECK_IS_ON()
  static void OnIsConnectedComplete(bool connected) {
    DCHECK(!connected)
        << "FaceDetection::DetectCallback was destroyed without "
        << "first either being run or its corresponding binding being closed. "
        << "It is an error to drop response callbacks which still correspond "
        << "to an open interface pipe.";
  }
#endif

  void Run(
      ::blink::Vector<FaceDetectionResultPtr> in_results);
};

bool FaceDetection_Detect_ForwardToCallback::Accept(
    mojo::Message* message) {
  DCHECK(message->is_serialized());
  internal::FaceDetection_Detect_ResponseParams_Data* params =
      reinterpret_cast<
          internal::FaceDetection_Detect_ResponseParams_Data*>(
              message->mutable_payload());
  

  // Validation for FaceDetection.0
  bool success = true;
  ::blink::Vector<FaceDetectionResultPtr> p_results{};
  FaceDetection_Detect_ResponseParamsDataView input_data_view(params, message);
  
  if (success && !input_data_view.ReadResults(&p_results))
    success = false;
  if (!success) {
    ReportValidationErrorForMessage(
        message,
        mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED,
        FaceDetection::Name_, 0, true);
    return false;
  }
  if (!callback_.is_null()) {
    std::move(callback_).Run(
std::move(p_results));
  }
  return true;
}

void FaceDetection_Detect_ProxyToResponder::Run(
    ::blink::Vector<FaceDetectionResultPtr> in_results) {
#if BUILDFLAG(MOJO_TRACE_ENABLED)
  TRACE_EVENT1(
    "mojom", "Send reply shape_detection::mojom::FaceDetection::Detect", "async_response_parameters",
    [&](perfetto::TracedValue context){
      auto dict = std::move(context).WriteDictionary();
      perfetto::WriteIntoTracedValueWithFallback(
           dict.AddItem("results"), in_results,
                        "<value of type ::blink::Vector<FaceDetectionResultPtr>>");
   });
#endif

  const uint32_t kFlags = mojo::Message::kFlagIsResponse |
      ((is_sync_) ? mojo::Message::kFlagIsSync : 0) |
      ((true) ? 0 : mojo::Message::kFlagNoInterrupt) |
      ((false) ? mojo::Message::kFlagIsUrgent : 0);

  const size_t estimated_payload_size =
    0;
  mojo::Message message(
      std::to_underlying(messages::FaceDetection::kDetect), kFlags, estimated_payload_size);
  mojo::internal::MessageFragment<
      ::shape_detection::mojom::internal::FaceDetection_Detect_ResponseParams_Data> params(
          message);
  params.Allocate();
  mojo::internal::MessageFragment<
      typename decltype(params->results)::BaseType>
      results_fragment(params.message());
  constexpr const mojo::internal::ContainerValidateParams& results_validate_params =
      mojo::internal::GetArrayValidator<0, false, nullptr>();
  
  mojo::internal::Serialize<mojo::ArrayDataView<::shape_detection::mojom::FaceDetectionResultDataView>>(
    in_results,
    results_fragment,
    &results_validate_params);

  params->results.Set(
      results_fragment.is_null() ? nullptr : results_fragment.data());

  
  MOJO_INTERNAL_CHECK_SERIALIZATION(
    mojo::internal::SendValidation::kDefault,
    !(params->results.is_null()),
    mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER,
    "null results in ");

#if defined(ENABLE_IPC_FUZZER)
  message.set_interface_name(FaceDetection::Name_);
  message.set_method_name("Detect");
#endif

  message.set_request_id(request_id_);
  message.set_trace_nonce(trace_nonce_);
  ::mojo::internal::SendMojoMessage(*responder_, message);
  // SendMojoMessage() fails silently if the responder connection is closed,
  // or if the message is malformed.
  //
  // TODO(darin): If Accept() returns false due to a malformed message, that
  // may be good reason to close the connection. However, we don't have a
  // way to do that from here. We should add a way.
  responder_ = nullptr;
}

// static
bool FaceDetectionStubDispatch::Accept(
    FaceDetection* impl,
    mojo::Message* message) {
  switch (static_cast<messages::FaceDetection>(message->header()->name)) {
    case messages::FaceDetection::kDetect: {
      break;
    }
  }
  return false;
}

// static
bool FaceDetectionStubDispatch::AcceptWithResponder(
    FaceDetection* impl,
    mojo::Message* message,
    std::unique_ptr<mojo::MessageReceiverWithStatus> responder) {
  [[maybe_unused]] const bool message_is_sync =
      message->has_flag(mojo::Message::kFlagIsSync);
  [[maybe_unused]] const uint64_t request_id = message->request_id();
  switch (static_cast<messages::FaceDetection>(message->header()->name)) {
    case messages::FaceDetection::kDetect: {
      internal::FaceDetection_Detect_Params_Data* params =
          reinterpret_cast<
              internal::FaceDetection_Detect_Params_Data*>(
                  message->mutable_payload());
      

      // Validation for FaceDetection.0
      bool success = true;
      ::SkBitmap p_bitmap_data{};
      FaceDetection_Detect_ParamsDataView input_data_view(params, message);
      
      if (success && !input_data_view.ReadBitmapData(&p_bitmap_data))
        success = false;
      if (!success) {
        ReportValidationErrorForMessage(
            message,
            mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED,
            FaceDetection::Name_, 0, false);
        return false;
      }
      auto callback =
          FaceDetection_Detect_ProxyToResponder::CreateCallback(
              *message, std::move(responder));
      // A null |impl| means no implementation was bound.
      DCHECK(impl);
      impl->Detect(        
        std::move(p_bitmap_data), std::move(callback));
      return true;
    }
  }
  return false;
}
namespace {
}  // namespace
static const mojo::internal::GenericValidationInfo kFaceDetectionValidationInfo[] = {
    { &internal::FaceDetection_Detect_Params_Data::Validate,
     &internal::FaceDetection_Detect_ResponseParams_Data::Validate},
};

bool FaceDetectionRequestValidator::Accept(mojo::Message* message) {
  return mojo::internal::ValidateRequestGenericPacked(
    message,
    ::shape_detection::mojom::blink::FaceDetection::Name_,
    kFaceDetectionValidationInfo);
}

bool FaceDetectionResponseValidator::Accept(mojo::Message* message) {
  return mojo::internal::ValidateResponseGenericPacked(
    message,
    ::shape_detection::mojom::blink::FaceDetection::Name_,
    kFaceDetectionValidationInfo);
}


}  // shape_detection::mojom::blink


namespace mojo {


// static
bool StructTraits<::shape_detection::mojom::blink::Landmark::DataView, ::shape_detection::mojom::blink::LandmarkPtr>::Read(
    ::shape_detection::mojom::blink::Landmark::DataView input,
    ::shape_detection::mojom::blink::LandmarkPtr* output) {
  bool success = true;
  ::shape_detection::mojom::blink::LandmarkPtr result(::shape_detection::mojom::blink::Landmark::New());
  
      if (success && !input.ReadLocations(&result->locations))
        success = false;
      if (success && !input.ReadType(&result->type))
        success = false;
  *output = std::move(result);
  return success;
}


// static
bool StructTraits<::shape_detection::mojom::blink::FaceDetectionResult::DataView, ::shape_detection::mojom::blink::FaceDetectionResultPtr>::Read(
    ::shape_detection::mojom::blink::FaceDetectionResult::DataView input,
    ::shape_detection::mojom::blink::FaceDetectionResultPtr* output) {
  bool success = true;
  ::shape_detection::mojom::blink::FaceDetectionResultPtr result(::shape_detection::mojom::blink::FaceDetectionResult::New());
  
      if (success && !input.ReadBoundingBox(&result->bounding_box))
        success = false;
      if (success && !input.ReadLandmarks(&result->landmarks))
        success = false;
  *output = std::move(result);
  return success;
}


// static
bool StructTraits<::shape_detection::mojom::blink::FaceDetectorOptions::DataView, ::shape_detection::mojom::blink::FaceDetectorOptionsPtr>::Read(
    ::shape_detection::mojom::blink::FaceDetectorOptions::DataView input,
    ::shape_detection::mojom::blink::FaceDetectorOptionsPtr* output) {
  bool success = true;
  ::shape_detection::mojom::blink::FaceDetectorOptionsPtr result(::shape_detection::mojom::blink::FaceDetectorOptions::New());
  
      if (success)
        result->max_detected_faces = input.max_detected_faces();
      if (success)
        result->fast_mode = input.fast_mode();
  *output = std::move(result);
  return success;
}

}  // namespace mojo


// Symbols declared in the -test-utils.h header are defined here instead of a
// separate .cc file to save compile time.


namespace shape_detection::mojom::blink {


void FaceDetectionInterceptorForTesting::Detect(const ::SkBitmap& bitmap_data, DetectCallback callback) {
  GetForwardingInterface()->Detect(
    std::move(bitmap_data)
    , std::move(callback));
}
FaceDetectionAsyncWaiter::FaceDetectionAsyncWaiter(
    FaceDetection* proxy) : proxy_(proxy) {}

FaceDetectionAsyncWaiter::~FaceDetectionAsyncWaiter() = default;


void FaceDetectionAsyncWaiter::Detect(
    const ::SkBitmap& bitmap_data, ::blink::Vector<FaceDetectionResultPtr>* out_results) {
  base::RunLoop loop;
  proxy_->Detect(
      std::move(bitmap_data),
      base::BindOnce(
          [](base::RunLoop* loop,
             ::blink::Vector<FaceDetectionResultPtr>* out_results
,
             ::blink::Vector<FaceDetectionResultPtr> results) {*out_results = std::move(results);
            loop->Quit();
          },
          &loop,
          out_results));
  loop.Run();
}

::blink::Vector<FaceDetectionResultPtr> FaceDetectionAsyncWaiter::Detect(
    const ::SkBitmap& bitmap_data) {
  ::blink::Vector<FaceDetectionResultPtr> async_wait_result;
  Detect(std::move(bitmap_data),&async_wait_result);
  return async_wait_result;
}






}  // shape_detection::mojom::blink


#if defined(__clang__)
#pragma clang diagnostic pop
#endif