Point.cpp 1.6 KB

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