Point.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ByteString.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() - 1);
  16. m_y = AK::clamp<T>(y(), rect.top(), rect.bottom() - 1);
  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. ByteString IntPoint::to_byte_string() const
  35. {
  36. return ByteString::formatted("[{},{}]", x(), y());
  37. }
  38. template<>
  39. ByteString FloatPoint::to_byte_string() const
  40. {
  41. return ByteString::formatted("[{},{}]", x(), y());
  42. }
  43. }
  44. namespace IPC {
  45. template<OneOf<Gfx::IntPoint, Gfx::FloatPoint> Point>
  46. ErrorOr<void> encode(Encoder& encoder, Point const& point)
  47. {
  48. TRY(encoder.encode(point.x()));
  49. TRY(encoder.encode(point.y()));
  50. return {};
  51. }
  52. template ErrorOr<void> encode(Encoder&, Gfx::IntPoint const& point);
  53. template ErrorOr<void> encode(Encoder&, Gfx::FloatPoint const& point);
  54. template<>
  55. ErrorOr<Gfx::IntPoint> decode(Decoder& decoder)
  56. {
  57. auto x = TRY(decoder.decode<int>());
  58. auto y = TRY(decoder.decode<int>());
  59. return Gfx::IntPoint { x, y };
  60. }
  61. template<>
  62. ErrorOr<Gfx::FloatPoint> decode(Decoder& decoder)
  63. {
  64. auto x = TRY(decoder.decode<float>());
  65. auto y = TRY(decoder.decode<float>());
  66. return Gfx::FloatPoint { x, y };
  67. }
  68. }
  69. template class Gfx::Point<int>;
  70. template class Gfx::Point<float>;