aboutsummaryrefslogtreecommitdiffstats
path: root/support/hololens/ServoApp/ServoControl/ServoControl.cpp
blob: 9e7323ae8f21a9785f16168978b30bc181d4ff35 (plain) (blame)
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
#include "pch.h"
#include "ServoControl.h"
#include "ServoControl.g.cpp"
#include <stdlib.h>

using namespace std::placeholders;
using namespace winrt::Windows::Graphics::Display;
using namespace winrt::Windows::UI::Xaml;
using namespace winrt::Windows::UI::Core;
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::System;
using namespace concurrency;
using namespace winrt::servo;

namespace winrt::ServoApp::implementation {

ServoControl::ServoControl() {
  mDPI = (float)DisplayInformation::GetForCurrentView().ResolutionScale() / 100;
  DefaultStyleKey(winrt::box_value(L"ServoApp.ServoControl"));
  Loaded(std::bind(&ServoControl::OnLoaded, this, _1, _2));
}

void ServoControl::Shutdown() {
  if (mServo != nullptr) {
    if (!mLooping) {
      // FIXME: this should not happen. In that case, we can't send the
      // shutdown event to Servo.
    } else {
      RunOnGLThread([=] { mServo->RequestShutdown(); });
      mLoopTask->wait();
      mLoopTask.reset();
      mServo.reset();
    }
  }
}

void ServoControl::OnLoaded(IInspectable const &, RoutedEventArgs const &) {
  auto panel = Panel();
  panel.Tapped(std::bind(&ServoControl::OnSurfaceTapped, this, _1, _2));
  panel.PointerPressed(
      std::bind(&ServoControl::OnSurfacePointerPressed, this, _1, _2));
  panel.PointerReleased(
      std::bind(&ServoControl::OnSurfacePointerPressed, this, _1, _2));
  panel.PointerCanceled(
      std::bind(&ServoControl::OnSurfacePointerCanceled, this, _1, _2));
  panel.PointerCaptureLost(
      std::bind(&ServoControl::OnSurfacePointerCanceled, this, _1, _2));
  panel.PointerMoved(
      std::bind(&ServoControl::OnSurfacePointerMoved, this, _1, _2));
  panel.PointerWheelChanged(
      std::bind(&ServoControl::OnSurfaceWheelChanged, this, _1, _2));
  panel.ManipulationStarted(
      [=](IInspectable const &,
          Input::ManipulationStartedRoutedEventArgs const &e) {
        mOnCaptureGesturesStartedEvent();
        e.Handled(true);
      });
  panel.ManipulationCompleted(
      [=](IInspectable const &,
          Input::ManipulationCompletedRoutedEventArgs const &e) {
        mOnCaptureGesturesEndedEvent();
        e.Handled(true);
      });
  panel.ManipulationDelta(
      std::bind(&ServoControl::OnSurfaceManipulationDelta, this, _1, _2));
  Panel().SizeChanged(std::bind(&ServoControl::OnSurfaceResized, this, _1, _2));
  InitializeConditionVariable(&mGLCondVar);
  InitializeCriticalSection(&mGLLock);
  CreateRenderSurface();
  StartRenderLoop();
}

Controls::SwapChainPanel ServoControl::Panel() {
  return GetTemplateChild(L"swapChainPanel").as<Controls::SwapChainPanel>();
}

void ServoControl::CreateRenderSurface() {
  if (mRenderSurface == EGL_NO_SURFACE) {
    mRenderSurface = mOpenGLES.CreateSurface(Panel(), mDPI);
  }
}

void ServoControl::DestroyRenderSurface() {
  mOpenGLES.DestroySurface(mRenderSurface);
  mRenderSurface = EGL_NO_SURFACE;
}

void ServoControl::RecoverFromLostDevice() {
  StopRenderLoop();
  DestroyRenderSurface();
  mOpenGLES.Reset();
  CreateRenderSurface();
  StartRenderLoop();
}

void ServoControl::OnSurfaceManipulationDelta(
    IInspectable const &, Input::ManipulationDeltaRoutedEventArgs const &e) {
  auto x = e.Position().X * mDPI;
  auto y = e.Position().Y * mDPI;
  auto dx = e.Delta().Translation.X * mDPI;
  auto dy = e.Delta().Translation.Y * mDPI;
  RunOnGLThread([=] { mServo->Scroll(dx, dy, x, y); });
  e.Handled(true);
}

void ServoControl::OnSurfaceTapped(IInspectable const &,
                                   Input::TappedRoutedEventArgs const &e) {
  auto coords = e.GetPosition(Panel());
  auto x = coords.X * mDPI;
  auto y = coords.Y * mDPI;
  RunOnGLThread([=] { mServo->Click(x, y); });
  e.Handled(true);
}

void ServoControl::OnSurfacePointerPressed(
    IInspectable const &, Input::PointerRoutedEventArgs const &e) {
  if (e.Pointer().PointerDeviceType() ==
      Windows::Devices::Input::PointerDeviceType::Mouse) {
    auto point = e.GetCurrentPoint(Panel());

    auto x = point.Position().X * mDPI;
    auto y = point.Position().Y * mDPI;
    auto props = point.Properties();
    std::optional<Servo::MouseButton> button = {};

    if (props.IsLeftButtonPressed()) {
      button = Servo::MouseButton::Left;
    } else if (props.IsRightButtonPressed()) {
      button = Servo::MouseButton::Right;
    } else if (props.IsMiddleButtonPressed()) {
      button = Servo::MouseButton::Middle;
    }

    if (!button.has_value() && mPressedMouseButton.has_value()) {
      auto releasedButton = *mPressedMouseButton;
      mPressedMouseButton = {};
      RunOnGLThread([=] { mServo->MouseUp(x, y, releasedButton); });
      e.Handled(true);
    }

    if (button.has_value()) {
      RunOnGLThread([=] { mServo->MouseDown(x, y, *button); });
      e.Handled(true);
    }

    mPressedMouseButton = button;
  }
}

void ServoControl::OnSurfacePointerCanceled(
    IInspectable const &, Input::PointerRoutedEventArgs const &e) {
    mPressedMouseButton = {};
}

void ServoControl::OnSurfacePointerMoved(
    IInspectable const &, Input::PointerRoutedEventArgs const &e) {
  if (e.Pointer().PointerDeviceType() ==
      Windows::Devices::Input::PointerDeviceType::Mouse) {
    auto point = e.GetCurrentPoint(Panel());
    auto x = point.Position().X * mDPI;
    auto y = point.Position().Y * mDPI;
    RunOnGLThread([=] { mServo->MouseMove(x, y); });
  }
}

void ServoControl::OnSurfaceWheelChanged(
    IInspectable const &, Input::PointerRoutedEventArgs const &e) {
  if (e.Pointer().PointerDeviceType() ==
      Windows::Devices::Input::PointerDeviceType::Mouse) {
    auto point = e.GetCurrentPoint(Panel());
    auto x = point.Position().X * mDPI;
    auto y = point.Position().Y * mDPI;
    auto delta = point.Properties().MouseWheelDelta() * mDPI;
    RunOnGLThread([=] { mServo->Scroll(0, (float)delta, x, y); });
  }
}

void ServoControl::OnSurfaceResized(IInspectable const &,
                                    SizeChangedEventArgs const &e) {
  auto size = e.NewSize();
  auto w = size.Width * mDPI;
  auto h = size.Height * mDPI;
  RunOnGLThread([=] { mServo->SetSize(w, h); });
}

void ServoControl::GoBack() {
  RunOnGLThread([=] { mServo->GoBack(); });
}
void ServoControl::GoForward() {
  RunOnGLThread([=] { mServo->GoForward(); });
}
void ServoControl::Reload() {
  RunOnGLThread([=] { mServo->Reload(); });
}
void ServoControl::Stop() {
  RunOnGLThread([=] { mServo->Stop(); });
}
Uri ServoControl::LoadURIOrSearch(hstring input) {
  auto uri = TryParseURI(input);
  if (uri == std::nullopt) {
    bool has_dot = wcsstr(input.c_str(), L".") != nullptr;
    hstring input2 = L"https://" + input;
    uri = TryParseURI(input2);
    if (uri == std::nullopt || !has_dot) {
      hstring input3 =
          L"https://duckduckgo.com/html/?q=" + Uri::EscapeComponent(input);
      uri = TryParseURI(input3);
    }
  }
  auto finalUri = uri.value();
  if (!mLooping) {
    mInitialURL = finalUri.ToString();
  } else {
    RunOnGLThread([=] { mServo->LoadUri(finalUri.ToString()); });
  }
  return finalUri;
}

void ServoControl::RunOnGLThread(std::function<void()> task) {
  EnterCriticalSection(&mGLLock);
  mTasks.push_back(task);
  LeaveCriticalSection(&mGLLock);
  WakeConditionVariable(&mGLCondVar);
}

/**** GL THREAD LOOP ****/

void ServoControl::Loop() {
  log("BrowserPage::Loop(). GL thread: %i", GetCurrentThreadId());

  mOpenGLES.MakeCurrent(mRenderSurface);

  EGLint panelWidth = 0;
  EGLint panelHeight = 0;
  mOpenGLES.GetSurfaceDimensions(mRenderSurface, &panelWidth, &panelHeight);
  glViewport(0, 0, panelWidth, panelHeight);

  if (mServo == nullptr) {
    log("Entering loop");
    ServoDelegate *sd = static_cast<ServoDelegate *>(this);
    mServo = std::make_unique<Servo>(mInitialURL, mArgs, panelWidth,
                                     panelHeight, mDPI, *sd);
  } else {
    // FIXME: this will fail since create_task didn't pick the thread
    // where Servo was running initially.
    throw winrt::hresult_error(E_FAIL, L"Recovering loop unimplemented");
  }

  mServo->SetBatchMode(true);

  while (true) {
    EnterCriticalSection(&mGLLock);
    while (mTasks.size() == 0 && !mAnimating && mLooping) {
      SleepConditionVariableCS(&mGLCondVar, &mGLLock, INFINITE);
    }
    if (!mLooping) {
      LeaveCriticalSection(&mGLLock);
      break;
    }
    for (auto &&task : mTasks) {
      task();
    }
    mTasks.clear();
    LeaveCriticalSection(&mGLLock);
    mServo->PerformUpdates();
  }
  mServo->DeInit();
  cancel_current_task();
}

void ServoControl::StartRenderLoop() {
  if (mLooping) {
#if defined _DEBUG
    throw winrt::hresult_error(E_FAIL, L"GL thread is already looping");
#else
    return;
#endif
  }
  mLooping = true;
  log("BrowserPage::StartRenderLoop(). UI thread: %i", GetCurrentThreadId());
  auto task = Concurrency::create_task([=] { Loop(); });
  mLoopTask = std::make_unique<Concurrency::task<void>>(task);
}

void ServoControl::StopRenderLoop() {
  if (mLooping) {
    EnterCriticalSection(&mGLLock);
    mLooping = false;
    LeaveCriticalSection(&mGLLock);
    WakeConditionVariable(&mGLCondVar);
    mLoopTask->wait();
    mLoopTask.reset();
  }
}

/**** SERVO CALLBACKS ****/

void ServoControl::OnServoLoadStarted() {
  RunOnUIThread([=] { mOnLoadStartedEvent(); });
}

void ServoControl::OnServoLoadEnded() {
  RunOnUIThread([=] { mOnLoadEndedEvent(); });
}

void ServoControl::OnServoHistoryChanged(bool back, bool forward) {
  RunOnUIThread([=] { mOnHistoryChangedEvent(back, forward); });
}

void ServoControl::OnServoShutdownComplete() {
  EnterCriticalSection(&mGLLock);
  mLooping = false;
  LeaveCriticalSection(&mGLLock);
}

void ServoControl::OnServoAlert(hstring message) {
  // FIXME: make this sync
  RunOnUIThread([=] {
    Windows::UI::Popups::MessageDialog msg{message};
    msg.ShowAsync();
  });
}

void ServoControl::OnServoTitleChanged(hstring title) {
  RunOnUIThread([=] { mOnTitleChangedEvent(*this, title); });
}

void ServoControl::OnServoURLChanged(hstring url) {
  RunOnUIThread([=] { mOnURLChangedEvent(*this, url); });
}

void ServoControl::Flush() {
  if (mOpenGLES.SwapBuffers(mRenderSurface) != GL_TRUE) {
    // The call to eglSwapBuffers might not be successful (i.e. due to Device
    // Lost) If the call fails, then we must reinitialize EGL and the GL
    // resources.
    RunOnUIThread([=] { RecoverFromLostDevice(); });
  }
}

void ServoControl::MakeCurrent() { mOpenGLES.MakeCurrent(mRenderSurface); }

void ServoControl::WakeUp() {
  RunOnGLThread([=] {});
}

bool ServoControl::OnServoAllowNavigation(hstring uri) {
  if (mTransient) {
    RunOnUIThread([=] { Launcher::LaunchUriAsync(Uri{uri}); });
  }
  return !mTransient;
}

void ServoControl::OnServoAnimatingChanged(bool animating) {
  EnterCriticalSection(&mGLLock);
  mAnimating = animating;
  LeaveCriticalSection(&mGLLock);
  WakeConditionVariable(&mGLCondVar);
}

void ServoControl::OnServoIMEStateChanged(bool aShow) {
  // FIXME:
  // https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-implementingtextandtextrange
}

template <typename Callable> void ServoControl::RunOnUIThread(Callable cb) {
  Dispatcher().RunAsync(CoreDispatcherPriority::High, cb);
}

} // namespace winrt::ServoApp::implementation