summaryrefslogtreecommitdiffstats
path: root/widget/gtk/WindowSurfaceWaylandMultiBuffer.cpp
blob: 0238bdb0e58fd08f7443f762c6c3ff614c6a7e69 (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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "WindowSurfaceWaylandMultiBuffer.h"

#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <prenv.h>

#include "gfx2DGlue.h"
#include "gfxPlatform.h"
#include "MozContainer.h"
#include "mozilla/gfx/DataSurfaceHelpers.h"
#include "mozilla/gfx/Tools.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/StaticPrefs_widget.h"
#include "mozilla/WidgetUtils.h"

#undef LOG
#ifdef MOZ_LOGGING
#  include "mozilla/Logging.h"
#  include "Units.h"
extern mozilla::LazyLogModule gWidgetWaylandLog;
#  define LOGWAYLAND(...) \
    MOZ_LOG(gWidgetWaylandLog, mozilla::LogLevel::Debug, (__VA_ARGS__))
#else
#  define LOGWAYLAND(...)
#endif /* MOZ_LOGGING */

namespace mozilla::widget {

/*
  Wayland multi-thread rendering scheme

  Every rendering thread (main thread, compositor thread) contains its own
  nsWaylandDisplay object connected to Wayland compositor (Mutter, Weston, etc.)

  WindowSurfaceWayland implements WindowSurface class and draws nsWindow by
  WindowSurface interface (Lock, Commit) to screen through nsWaylandDisplay.

  ----------------------
  | Wayland compositor |
  ----------------------
             ^
             |
  ----------------------
  |  nsWaylandDisplay  |
  ----------------------
        ^          ^
        |          |
        |          |
        |       ---------------------------------        ------------------
        |       | WindowSurfaceWayland          |<------>| nsWindow       |
        |       |                               |        ------------------
        |       |  -----------------------      |
        |       |  | WaylandBufferSHM    |      |
        |       |  |                     |      |
        |       |  | ------------------- |      |
        |       |  | |  WaylandShmPool | |      |
        |       |  | ------------------- |      |
        |       |  -----------------------      |
        |       |                               |
        |       |  -----------------------      |
        |       |  | WaylandBufferSHM    |      |
        |       |  |                     |      |
        |       |  | ------------------- |      |
        |       |  | |  WaylandShmPool | |      |
        |       |  | ------------------- |      |
        |       |  -----------------------      |
        |       ---------------------------------
        |
        |
  ---------------------------------        ------------------
  | WindowSurfaceWayland          |<------>| nsWindow       |
  |                               |        ------------------
  |  -----------------------      |
  |  | WaylandBufferSHM    |      |
  |  |                     |      |
  |  | ------------------- |      |
  |  | |  WaylandShmPool | |      |
  |  | ------------------- |      |
  |  -----------------------      |
  |                               |
  |  -----------------------      |
  |  | WaylandBufferSHM    |      |
  |  |                     |      |
  |  | ------------------- |      |
  |  | |  WaylandShmPool | |      |
  |  | ------------------- |      |
  |  -----------------------      |
  ---------------------------------


nsWaylandDisplay

Is our connection to Wayland display server,
holds our display connection (wl_display) and event queue (wl_event_queue).

nsWaylandDisplay is created for every thread which sends data to Wayland
compositor. Wayland events for main thread is served by default Gtk+ loop,
for other threads (compositor) we must create wl_event_queue and run event loop.


WindowSurfaceWayland

Is a Wayland implementation of WindowSurface class for WindowSurfaceProvider,
we implement Lock() and Commit() interfaces from WindowSurface
for actual drawing.

One WindowSurfaceWayland draws one nsWindow so those are tied 1:1.
At Wayland level it holds one wl_surface object.

To perform visualiation of nsWindow, WindowSurfaceWayland contains one
wl_surface and two wl_buffer objects (owned by WaylandBufferSHM)
as we use double buffering. When nsWindow drawing is finished to wl_buffer,
the wl_buffer is attached to wl_surface and it's sent to Wayland compositor.

When there's no wl_buffer available for drawing (all wl_buffers are locked in
compositor for instance) we store the drawing to WindowImageSurface object
and draw later when wl_buffer becomes available or discard the
WindowImageSurface cache when whole screen is invalidated.

WaylandBufferSHM

Is a class which provides a wl_buffer for drawing.
Wl_buffer is a main Wayland object with actual graphics data.
Wl_buffer basically represent one complete window screen.
When double buffering is involved every window (GdkWindow for instance)
utilises two wl_buffers which are cycled. One is filed with data by application
and one is rendered by compositor.

WaylandBufferSHM is implemented by shared memory (shm).
It owns wl_buffer object, owns WaylandShmPool
(which provides the shared memory) and ties them together.

WaylandShmPool

WaylandShmPool acts as a manager of shared memory for WaylandBufferSHM.
Allocates it, holds reference to it and releases it.

We allocate shared memory (shm) by mmap(..., MAP_SHARED,...) as an interface
between us and wayland compositor. We draw our graphics data to the shm and
handle to wayland compositor by WaylandBufferSHM/WindowSurfaceWayland
(wl_buffer/wl_surface).
*/

using gfx::DataSourceSurface;

#define BACK_BUFFER_NUM 3

WindowSurfaceWaylandMB::WindowSurfaceWaylandMB(RefPtr<nsWindow> aWindow)
    : mSurfaceLock("WindowSurfaceWayland lock"),
      mWindow(std::move(aWindow)),
      mFrameInProcess(false),
      mCallbackRequested(false) {}

already_AddRefed<DrawTarget> WindowSurfaceWaylandMB::Lock(
    const LayoutDeviceIntRegion& aInvalidRegion) {
  MutexAutoLock lock(mSurfaceLock);

#ifdef MOZ_LOGGING
  gfx::IntRect lockRect = aInvalidRegion.GetBounds().ToUnknownRect();
  LOGWAYLAND("WindowSurfaceWaylandMB::Lock [%p] [%d,%d] -> [%d x %d] rects %d",
             (void*)mWindow.get(), lockRect.x, lockRect.y, lockRect.width,
             lockRect.height, aInvalidRegion.GetNumRects());
#endif

  if (mWindow->WindowType() == eWindowType_invisible) {
    return nullptr;
  }
  mFrameInProcess = true;

  CollectPendingSurfaces(lock);

  LayoutDeviceIntSize newMozContainerSize = mWindow->GetMozContainerSize();
  if (mMozContainerSize != newMozContainerSize) {
    mMozContainerSize = newMozContainerSize;
    LOGWAYLAND("  new MozContainer size [%d x %d]", mMozContainerSize.width,
               mMozContainerSize.height);
    if (mInProgressBuffer) {
      ReturnBufferToPool(lock, mInProgressBuffer);
      mInProgressBuffer = nullptr;
    }
    if (mFrontBuffer) {
      ReturnBufferToPool(lock, mFrontBuffer);
      mFrontBuffer = nullptr;
    }
    mAvailableBuffers.Clear();
  }

  if (!mInProgressBuffer) {
    if (mFrontBuffer && !mFrontBuffer->IsAttached()) {
      mInProgressBuffer = mFrontBuffer;
    } else {
      mInProgressBuffer = ObtainBufferFromPool(lock, mMozContainerSize);
      if (!mInProgressBuffer) {
        return nullptr;
      }
      if (mFrontBuffer) {
        HandlePartialUpdate(lock, aInvalidRegion);
        ReturnBufferToPool(lock, mFrontBuffer);
      }
    }
    mFrontBuffer = nullptr;
    mFrontBufferInvalidRegion.SetEmpty();
  }

  RefPtr<DrawTarget> dt = mInProgressBuffer->Lock();
  return dt.forget();
}

void WindowSurfaceWaylandMB::HandlePartialUpdate(
    const MutexAutoLock& aProofOfLock,
    const LayoutDeviceIntRegion& aInvalidRegion) {
  LayoutDeviceIntRegion copyRegion;
  if (mInProgressBuffer->GetBufferAge() == 2) {
    copyRegion.Sub(mFrontBufferInvalidRegion, aInvalidRegion);
  } else {
    LayoutDeviceIntSize frontBufferSize = mFrontBuffer->GetSize();
    copyRegion = LayoutDeviceIntRegion(LayoutDeviceIntRect(
        0, 0, frontBufferSize.width, frontBufferSize.height));
    copyRegion.SubOut(aInvalidRegion);
  }

  if (!copyRegion.IsEmpty()) {
    RefPtr<DataSourceSurface> dataSourceSurface =
        mozilla::gfx::CreateDataSourceSurfaceFromData(
            mFrontBuffer->GetSize().ToUnknownSize(),
            mFrontBuffer->GetSurfaceFormat(),
            (const uint8_t*)mFrontBuffer->GetShmPool()->GetImageData(),
            mFrontBuffer->GetSize().width *
                BytesPerPixel(mFrontBuffer->GetSurfaceFormat()));
    RefPtr<DrawTarget> dt = mInProgressBuffer->Lock();

    for (auto iter = copyRegion.RectIter(); !iter.Done(); iter.Next()) {
      LayoutDeviceIntRect r = iter.Get();
      dt->CopySurface(dataSourceSurface, r.ToUnknownRect(),
                      gfx::IntPoint(r.x, r.y));
    }
  }
}

void WindowSurfaceWaylandMB::Commit(
    const LayoutDeviceIntRegion& aInvalidRegion) {
  MutexAutoLock lock(mSurfaceLock);
  Commit(lock, aInvalidRegion);
}

void WindowSurfaceWaylandMB::Commit(
    const MutexAutoLock& aProofOfLock,
    const LayoutDeviceIntRegion& aInvalidRegion) {
#ifdef MOZ_LOGGING
  gfx::IntRect invalidRect = aInvalidRegion.GetBounds().ToUnknownRect();
  LOGWAYLAND(
      "WindowSurfaceWaylandMB::Commit [%p] damage rect [%d, %d] -> [%d x %d] "
      "MozContainer [%d x %d]\n",
      (void*)mWindow.get(), invalidRect.x, invalidRect.y, invalidRect.width,
      invalidRect.height, mMozContainerSize.width, mMozContainerSize.height);
#endif

  if (!mInProgressBuffer) {
    // invisible window
    return;
  }
  mFrameInProcess = false;

  MozContainer* container = mWindow->GetMozContainer();
  MozContainerSurfaceLock lock(container);
  struct wl_surface* waylandSurface = lock.GetSurface();
  if (!waylandSurface) {
    LOGWAYLAND(
        "WindowSurfaceWaylandMB::Commit [%p] frame queued: can't lock "
        "wl_surface\n",
        (void*)mWindow.get());
    if (!mCallbackRequested) {
      RefPtr<WindowSurfaceWaylandMB> self(this);
      moz_container_wayland_add_initial_draw_callback_locked(
          container, [self, aInvalidRegion]() -> void {
            MutexAutoLock lock(self->mSurfaceLock);
            if (!self->mFrameInProcess) {
              self->Commit(lock, aInvalidRegion);
            }
            self->mCallbackRequested = false;
          });
      mCallbackRequested = true;
    }
    return;
  }

  if (moz_container_wayland_is_commiting_to_parent(container)) {
    // When committing to parent surface we must use wl_surface_damage().
    // A parent surface is created as v.3 object which does not support
    // wl_surface_damage_buffer().
    wl_surface_damage(waylandSurface, 0, 0, INT32_MAX, INT32_MAX);
  } else {
    for (auto iter = aInvalidRegion.RectIter(); !iter.Done(); iter.Next()) {
      LayoutDeviceIntRect r = iter.Get();
      wl_surface_damage_buffer(waylandSurface, r.x, r.y, r.width, r.height);
    }
  }

  moz_container_wayland_set_scale_factor_locked(aProofOfLock, container);
  mInProgressBuffer->AttachAndCommit(waylandSurface);

  mInProgressBuffer->ResetBufferAge();
  mFrontBuffer = mInProgressBuffer;
  mFrontBufferInvalidRegion = aInvalidRegion;
  mInProgressBuffer = nullptr;

  EnforcePoolSizeLimit(aProofOfLock);
  IncrementBufferAge(aProofOfLock);

  if (wl_display_flush(WaylandDisplayGet()->GetDisplay()) == -1) {
    LOGWAYLAND("WindowSurfaceWaylandMB::Commit [%p] flush failed\n",
               (void*)mWindow.get());
  }
}

RefPtr<WaylandBufferSHM> WindowSurfaceWaylandMB::ObtainBufferFromPool(
    const MutexAutoLock& aProofOfLock, const LayoutDeviceIntSize& aSize) {
  if (!mAvailableBuffers.IsEmpty()) {
    RefPtr<WaylandBufferSHM> buffer = mAvailableBuffers.PopLastElement();
    mInUseBuffers.AppendElement(buffer);
    return buffer;
  }

  RefPtr<WaylandBufferSHM> buffer = WaylandBufferSHM::Create(aSize);
  if (buffer) {
    mInUseBuffers.AppendElement(buffer);
  }

  return buffer;
}

void WindowSurfaceWaylandMB::ReturnBufferToPool(
    const MutexAutoLock& aProofOfLock,
    const RefPtr<WaylandBufferSHM>& aBuffer) {
  if (aBuffer->IsAttached()) {
    mPendingBuffers.AppendElement(aBuffer);
  } else if (aBuffer->IsMatchingSize(mMozContainerSize)) {
    mAvailableBuffers.AppendElement(aBuffer);
  }
  mInUseBuffers.RemoveElement(aBuffer);
}

void WindowSurfaceWaylandMB::EnforcePoolSizeLimit(
    const MutexAutoLock& aProofOfLock) {
  // Enforce the pool size limit, removing least-recently-used entries as
  // necessary.
  while (mAvailableBuffers.Length() > BACK_BUFFER_NUM) {
    mAvailableBuffers.RemoveElementAt(0);
  }

  NS_WARNING_ASSERTION(mPendingBuffers.Length() < BACK_BUFFER_NUM,
                       "Are we leaking pending buffers?");
  NS_WARNING_ASSERTION(mInUseBuffers.Length() < BACK_BUFFER_NUM,
                       "Are we leaking in-use buffers?");
}

void WindowSurfaceWaylandMB::CollectPendingSurfaces(
    const MutexAutoLock& aProofOfLock) {
  mPendingBuffers.RemoveElementsBy([&](auto& buffer) {
    if (!buffer->IsAttached()) {
      if (buffer->IsMatchingSize(mMozContainerSize)) {
        mAvailableBuffers.AppendElement(std::move(buffer));
      }
      return true;
    }
    return false;
  });
}

void WindowSurfaceWaylandMB::IncrementBufferAge(
    const MutexAutoLock& aProofOfLock) {
  for (const RefPtr<WaylandBufferSHM>& buffer : mInUseBuffers) {
    buffer->IncrementBufferAge();
  }
  for (const RefPtr<WaylandBufferSHM>& buffer : mPendingBuffers) {
    buffer->IncrementBufferAge();
  }
  for (const RefPtr<WaylandBufferSHM>& buffer : mAvailableBuffers) {
    buffer->IncrementBufferAge();
  }
}

}  // namespace mozilla::widget