summaryrefslogtreecommitdiffstats
path: root/xbmc/windowing/wayland/SeatSelection.cpp
blob: f66555a0d4f080a41672165cb405610669a20278 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/*
 *  Copyright (C) 2017-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#include "SeatSelection.h"

#include "Connection.h"
#include "Registry.h"
#include "WinEventsWayland.h"
#include "utils/StringUtils.h"
#include "utils/log.h"

#include "platform/posix/utils/FileHandle.h"

#include <cerrno>
#include <chrono>
#include <cstring>
#include <mutex>
#include <system_error>
#include <utility>

#include <poll.h>
#include <unistd.h>

using namespace KODI::UTILS::POSIX;
using namespace KODI::WINDOWING::WAYLAND;

namespace
{

const std::vector<std::string> MIME_TYPES_PREFERENCE =
{
  "text/plain;charset=utf-8",
  "text/plain;charset=iso-8859-1",
  "text/plain;charset=us-ascii",
  "text/plain"
};

}

CSeatSelection::CSeatSelection(CConnection& connection, wayland::seat_t const& seat)
{
  wayland::data_device_manager_t manager;
  {
    CRegistry registry{connection};
    registry.RequestSingleton(manager, 1, 3, false);
    registry.Bind();
  }

  if (!manager)
  {
    CLog::Log(LOGWARNING, "No data device manager announced by compositor, clipboard will not be available");
    return;
  }

  m_dataDevice = manager.get_data_device(seat);

  // Class is created in response to seat add events - so no events can get lost
  m_dataDevice.on_data_offer() = [this](wayland::data_offer_t offer)
  {
    // We don't know yet whether this is drag-and-drop or selection, so collect
    // MIME types in either case
    m_currentOffer = std::move(offer);
    m_mimeTypeOffers.clear();
    m_currentOffer.on_offer() = [this](std::string mime)
    {
      m_mimeTypeOffers.push_back(std::move(mime));
    };
  };
  m_dataDevice.on_selection() = [this](const wayland::data_offer_t& offer)
  {
    std::unique_lock<CCriticalSection> lock(m_currentSelectionMutex);
    m_matchedMimeType.clear();

    if (offer != m_currentOffer)
    {
      // Selection was not previously introduced by offer (could be NULL for example)
      m_currentSelection.proxy_release();
    }
    else
    {
      m_currentSelection = offer;
      std::string offers = StringUtils::Join(m_mimeTypeOffers, ", ");

      // Match MIME type by priority: Find first preferred MIME type that is in the
      // set of offered types
      // Charset is not case-sensitive in MIME type spec, so match case-insensitively
      auto mimeIt = std::find_first_of(MIME_TYPES_PREFERENCE.cbegin(), MIME_TYPES_PREFERENCE.cend(),
                                       m_mimeTypeOffers.cbegin(), m_mimeTypeOffers.cend(),
                                       // static_cast needed for overload resolution
                                       static_cast<bool (*)(std::string const&, std::string const&)> (&StringUtils::EqualsNoCase));
      if (mimeIt != MIME_TYPES_PREFERENCE.cend())
      {
        m_matchedMimeType = *mimeIt;
        CLog::Log(LOGDEBUG, "Chose selection MIME type {} out of offered {}", m_matchedMimeType,
                  offers);
      }
      else
      {
        CLog::Log(LOGDEBUG, "Could not find compatible MIME type for selection data (offered: {})",
                  offers);
      }
    }
  };
}

std::string CSeatSelection::GetSelectionText() const
{
  std::unique_lock<CCriticalSection> lock(m_currentSelectionMutex);
  if (!m_currentSelection || m_matchedMimeType.empty())
  {
    return "";
  }

  std::array<int, 2> fds;
  if (pipe(fds.data()) != 0)
  {
    CLog::LogF(LOGERROR, "Could not open pipe for selection data transfer: {}",
               std::strerror(errno));
    return "";
  }

  CFileHandle readFd{fds[0]};
  CFileHandle writeFd{fds[1]};

  m_currentSelection.receive(m_matchedMimeType, writeFd);
  lock.unlock();
  // Make sure the other party gets the request as soon as possible
  CWinEventsWayland::Flush();
  // Fd now gets sent to the other party -> make sure our write end is closed
  // so we get POLLHUP when the other party closes its write fd
  writeFd.reset();

  pollfd fd =
  {
    .fd = readFd,
    .events = POLLIN,
    .revents = 0
  };

  // UI will block in this function when Ctrl+V is pressed, so timeout should be
  // rather short!
  const std::chrono::seconds TIMEOUT{1};
  const std::size_t MAX_SIZE{4096};
  std::array<char, MAX_SIZE> buffer;

  auto start = std::chrono::steady_clock::now();
  std::size_t totalBytesRead{0};

  do
  {
    auto now = std::chrono::steady_clock::now();
    // Do not permit negative timeouts (would cause infinitely long poll)
    auto remainingTimeout = std::max(std::chrono::milliseconds(0), std::chrono::duration_cast<std::chrono::milliseconds> (TIMEOUT - (now - start))).count();
    // poll() for changes until poll signals POLLHUP and the remaining data was read
    int ret{poll(&fd, 1, remainingTimeout)};
    if (ret == 0)
    {
      // Timeout
      CLog::LogF(LOGERROR, "Reading from selection data pipe timed out");
      return "";
    }
    else if (ret < 0 && errno == EINTR)
    {
      continue;
    }
    else if (ret < 0)
    {
      throw std::system_error(errno, std::generic_category(), "Error polling selection pipe");
    }
    else if (fd.revents & POLLNVAL || fd.revents & POLLERR)
    {
      CLog::LogF(LOGERROR, "poll() indicated error on selection pipe");
      return "";
    }
    else if (fd.revents & POLLIN)
    {
      if (totalBytesRead >= buffer.size())
      {
        CLog::LogF(LOGERROR, "Selection data is too big, aborting read");
        return "";
      }
      ssize_t readBytes{read(fd.fd, buffer.data() + totalBytesRead, buffer.size() - totalBytesRead)};
      if (readBytes < 0)
      {
        CLog::LogF(LOGERROR, "read() from selection pipe failed: {}", std::strerror(errno));
        return "";
      }
      totalBytesRead += readBytes;
    }
  }
  while (!(fd.revents & POLLHUP));

  return std::string(buffer.data(), totalBytesRead);
}