Point.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/DeprecatedString.h>
  7. #include <LibGfx/Point.h>
  8. #include <LibGfx/Rect.h>
  9. #include <LibIPC/Decoder.h>
  10. #include <LibIPC/Encoder.h>
  11. namespace Gfx {
  12. template<typename T>
  13. void Point<T>::constrain(Rect<T> const& rect)
  14. {
  15. m_x = AK::clamp<T>(x(), rect.left(), rect.right());
  16. m_y = AK::clamp<T>(y(), rect.top(), rect.bottom());
  17. }
  18. template<typename T>
  19. [[nodiscard]] Point<T> Point<T>::end_point_for_aspect_ratio(Point<T> const& previous_end_point, float aspect_ratio) const
  20. {
  21. VERIFY(aspect_ratio > 0);
  22. const T x_sign = previous_end_point.x() >= x() ? 1 : -1;
  23. const T y_sign = previous_end_point.y() >= y() ? 1 : -1;
  24. T dx = AK::abs(previous_end_point.x() - x());
  25. T dy = AK::abs(previous_end_point.y() - y());
  26. if (dx > dy) {
  27. dy = (T)((float)dx / aspect_ratio);
  28. } else {
  29. dx = (T)((float)dy * aspect_ratio);
  30. }
  31. return { x() + x_sign * dx, y() + y_sign * dy };
  32. }
  33. template<>
  34. DeprecatedString IntPoint::to_deprecated_string() const
  35. {
  36. return DeprecatedString::formatted("[{},{}]", x(), y());
  37. }
  38. template<>
  39. DeprecatedString FloatPoint::to_deprecated_string() const
  40. {
  41. return DeprecatedString::formatted("[{},{}]", x(), y());
  42. }
  43. }
  44. namespace IPC {
  45. template<>
  46. ErrorOr<void> encode(Encoder& encoder, Gfx::IntPoint const& point)
  47. {
  48. TRY(encoder.encode(point.x()));
  49. TRY(encoder.encode(point.y()));
  50. return {};
  51. }
  52. template<>
  53. ErrorOr<Gfx::IntPoint> decode(Decoder& decoder)
  54. {
  55. auto x = TRY(decoder.decode<int>());
  56. auto y = TRY(decoder.decode<int>());
  57. return Gfx::IntPoint { x, y };
  58. }
  59. }
  60. template class Gfx::Point<int>;
  61. template class Gfx::Point<float>;