@ng-native/desktop 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. package/README.md +6 -3
  2. package/bin/app-config.mjs +1 -0
  3. package/bin/archive.mjs +166 -0
  4. package/bin/autolink.mjs +61 -30
  5. package/bin/cli.mjs +127 -27
  6. package/bin/host.mjs +255 -58
  7. package/bin/package-linux.mjs +1394 -0
  8. package/bin/package.mjs +171 -35
  9. package/bin/plist.mjs +6 -2
  10. package/bin/png-icon.mjs +315 -0
  11. package/bin/prebuilt.mjs +147 -26
  12. package/bin/toolchain.mjs +258 -19
  13. package/native/CMakeLists.txt +64 -6
  14. package/native/appkit/CMakeLists.txt +2 -1
  15. package/native/appkit/appkit-backend.h +1 -0
  16. package/native/appkit/appkit-backend.mm +13 -0
  17. package/native/appkit/header-toolbar.mm +28 -25
  18. package/native/appkit/host-view.h +10 -0
  19. package/native/appkit/host-view.mm +146 -40
  20. package/native/appkit/input-replay.h +6 -0
  21. package/native/appkit/input-replay.mm +21 -12
  22. package/native/appkit/main.mm +11 -7
  23. package/native/appkit/native-controls.mm +13 -1
  24. package/native/appkit/split-view.mm +7 -13
  25. package/native/appkit/text-input-field.h +4 -0
  26. package/native/appkit/text-input-field.mm +20 -1
  27. package/native/cmake/curl.cmake +79 -0
  28. package/native/cmake/libraries/react-native-reanimated.cmake +5 -0
  29. package/native/cmake/libraries/react-native-worklets.cmake +5 -0
  30. package/native/cmake/linked-modules.cmake +20 -4
  31. package/native/cmake/react-native.cmake +18 -1
  32. package/native/core/include/ngn/accent-colors.h +38 -0
  33. package/native/core/include/ngn/accessibility-relations.h +65 -0
  34. package/native/core/include/ngn/accessibility.h +26 -0
  35. package/native/core/include/ngn/animated-frame-loop.h +56 -0
  36. package/native/core/include/ngn/app-info.h +24 -8
  37. package/native/core/include/ngn/app-menus.h +14 -1
  38. package/native/core/include/ngn/app-windows.h +15 -2
  39. package/native/core/include/ngn/aria-role.h +96 -0
  40. package/native/core/include/ngn/audio.h +2 -0
  41. package/native/core/include/ngn/camera.h +9 -0
  42. package/native/core/include/ngn/control-sizes.h +7 -2
  43. package/native/core/include/ngn/crash-report.h +31 -0
  44. package/native/core/include/ngn/curl-network.h +93 -0
  45. package/native/core/include/ngn/dbus-menu.h +39 -0
  46. package/native/core/include/ngn/default-menu.h +36 -0
  47. package/native/core/include/ngn/desktop-expo.h +7 -1
  48. package/native/core/include/ngn/desktop-modules.h +22 -0
  49. package/native/core/include/ngn/desktop-props.h +21 -1
  50. package/native/core/include/ngn/desktop-view-props.h +6 -0
  51. package/native/core/include/ngn/focus-order.h +10 -0
  52. package/native/core/include/ngn/header-bar.h +22 -0
  53. package/native/core/include/ngn/host-os.h +6 -0
  54. package/native/core/include/ngn/host-reload.h +21 -0
  55. package/native/core/include/ngn/host-state.h +23 -0
  56. package/native/core/include/ngn/image-source.h +26 -1
  57. package/native/core/include/ngn/input-script.h +3 -3
  58. package/native/core/include/ngn/input.h +4 -1
  59. package/native/core/include/ngn/launch-frame.h +21 -0
  60. package/native/core/include/ngn/launch-settings.h +23 -5
  61. package/native/core/include/ngn/mounting-backend.h +5 -0
  62. package/native/core/include/ngn/mounting-manager.h +1 -0
  63. package/native/core/include/ngn/native-controls.h +26 -5
  64. package/native/core/include/ngn/notification-schedule.h +74 -0
  65. package/native/core/include/ngn/notifications.h +2 -1
  66. package/native/core/include/ngn/openssl-update-crypto.h +15 -0
  67. package/native/core/include/ngn/photo-library.h +60 -20
  68. package/native/core/include/ngn/posix-locale.h +43 -0
  69. package/native/core/include/ngn/runtime.h +5 -0
  70. package/native/core/include/ngn/safe-areas.h +14 -2
  71. package/native/core/include/ngn/split-view.h +78 -0
  72. package/native/core/include/ngn/surface-metrics.h +7 -0
  73. package/native/core/include/ngn/system.h +14 -0
  74. package/native/core/include/ngn/text-input.h +13 -0
  75. package/native/core/include/ngn/text-units.h +38 -0
  76. package/native/core/include/ngn/updates.h +14 -2
  77. package/native/core/include/ngn/view-box.h +40 -0
  78. package/native/core/include/ngn/view-transform.h +15 -0
  79. package/native/core/include/ngn/web-browser.h +46 -0
  80. package/native/core/src/accent-colors.cpp +88 -0
  81. package/native/core/src/accessibility-relations.cpp +138 -0
  82. package/native/core/src/accessibility.cpp +50 -0
  83. package/native/core/src/animated-frame-loop.cpp +166 -0
  84. package/native/core/src/app-menus.cpp +26 -9
  85. package/native/core/src/app-windows.cpp +27 -6
  86. package/native/core/src/aria-role.cpp +127 -0
  87. package/native/core/src/control-sizes.cpp +9 -5
  88. package/native/core/src/crash-report.cpp +196 -0
  89. package/native/core/src/curl-network.cpp +1562 -0
  90. package/native/core/src/dbus-menu.cpp +71 -0
  91. package/native/core/src/default-menu.cpp +134 -0
  92. package/native/core/src/desktop-view-props.cpp +14 -0
  93. package/native/core/src/focus-order.cpp +19 -0
  94. package/native/core/src/header-bar.cpp +20 -0
  95. package/native/core/src/host-os.cpp +19 -0
  96. package/native/core/src/host-reload.cpp +45 -0
  97. package/native/core/src/host-state.cpp +8 -0
  98. package/native/core/src/image-source.cpp +90 -0
  99. package/native/core/src/input-dispatcher.cpp +27 -5
  100. package/native/core/src/input-script.cpp +3 -2
  101. package/native/core/src/launch-settings.cpp +76 -0
  102. package/native/core/src/libraries/react-native-reanimated.cpp +6 -1
  103. package/native/core/src/modules/app-info.cpp +55 -6
  104. package/native/core/src/modules/app-modules.cpp +1 -1
  105. package/native/core/src/modules/audio.cpp +4 -2
  106. package/native/core/src/modules/camera.cpp +8 -11
  107. package/native/core/src/modules/desktop-expo.cpp +10 -5
  108. package/native/core/src/modules/desktop-modules.cpp +106 -41
  109. package/native/core/src/modules/file-photo-picker.cpp +408 -0
  110. package/native/core/src/modules/notifications.cpp +13 -17
  111. package/native/core/src/modules/photo-library.cpp +42 -13
  112. package/native/core/src/modules/web-browser.cpp +89 -0
  113. package/native/core/src/mounting-manager.cpp +12 -0
  114. package/native/core/src/native-controls.cpp +42 -1
  115. package/native/core/src/notification-schedule.cpp +429 -0
  116. package/native/core/src/openssl-update-crypto.cpp +83 -0
  117. package/native/core/src/posix-locale.cpp +192 -0
  118. package/native/core/src/runtime.cpp +30 -1
  119. package/native/core/src/safe-areas.cpp +19 -4
  120. package/native/core/src/spawn-rules.cpp +4 -1
  121. package/native/core/src/split-view.cpp +93 -0
  122. package/native/core/src/system.cpp +19 -0
  123. package/native/core/src/text-input.cpp +18 -1
  124. package/native/core/src/text-units.cpp +99 -0
  125. package/native/core/src/updates.cpp +76 -17
  126. package/native/core/src/view-box.cpp +75 -40
  127. package/native/core/src/view-transform.cpp +28 -0
  128. package/native/docker/Dockerfile +38 -0
  129. package/native/docker/Dockerfile.fedora +36 -0
  130. package/native/docker/glibc-floor.sh +49 -0
  131. package/native/gtk/CMakeLists.txt +137 -0
  132. package/native/gtk/accent-colour.cpp +57 -0
  133. package/native/gtk/accent-colour.h +41 -0
  134. package/native/gtk/accessibility-settings.cpp +159 -0
  135. package/native/gtk/accessibility-settings.h +62 -0
  136. package/native/gtk/accessible-text.cpp +151 -0
  137. package/native/gtk/accessible-text.h +49 -0
  138. package/native/gtk/accessible.cpp +306 -0
  139. package/native/gtk/accessible.h +75 -0
  140. package/native/gtk/alerts.cpp +267 -0
  141. package/native/gtk/alerts.h +30 -0
  142. package/native/gtk/animation-frames.cpp +159 -0
  143. package/native/gtk/animation-frames.h +20 -0
  144. package/native/gtk/app-info.cpp +91 -0
  145. package/native/gtk/app-info.h +25 -0
  146. package/native/gtk/app-windows.cpp +439 -0
  147. package/native/gtk/app-windows.h +150 -0
  148. package/native/gtk/audio.cpp +370 -0
  149. package/native/gtk/audio.h +54 -0
  150. package/native/gtk/auth-session.cpp +73 -0
  151. package/native/gtk/auth-session.h +16 -0
  152. package/native/gtk/battery.cpp +110 -0
  153. package/native/gtk/battery.h +19 -0
  154. package/native/gtk/box-paint.cpp +262 -0
  155. package/native/gtk/box-paint.h +32 -0
  156. package/native/gtk/cairo-canvas.cpp +755 -0
  157. package/native/gtk/cairo-canvas.h +49 -0
  158. package/native/gtk/camera.cpp +909 -0
  159. package/native/gtk/camera.h +69 -0
  160. package/native/gtk/capture.cpp +46 -0
  161. package/native/gtk/capture.h +19 -0
  162. package/native/gtk/clock-format.cpp +151 -0
  163. package/native/gtk/clock-format.h +36 -0
  164. package/native/gtk/crypto.cpp +75 -0
  165. package/native/gtk/crypto.h +14 -0
  166. package/native/gtk/dbus-properties.cpp +131 -0
  167. package/native/gtk/dbus-properties.h +61 -0
  168. package/native/gtk/drag-and-drop.cpp +339 -0
  169. package/native/gtk/drag-and-drop.h +30 -0
  170. package/native/gtk/file-dialogs.cpp +239 -0
  171. package/native/gtk/file-dialogs.h +21 -0
  172. package/native/gtk/file-system.cpp +212 -0
  173. package/native/gtk/file-system.h +25 -0
  174. package/native/gtk/focus.cpp +282 -0
  175. package/native/gtk/focus.h +37 -0
  176. package/native/gtk/fonts.cpp +89 -0
  177. package/native/gtk/fonts.h +22 -0
  178. package/native/gtk/gst-frames.cpp +150 -0
  179. package/native/gtk/gst-frames.h +47 -0
  180. package/native/gtk/gst-playback.cpp +496 -0
  181. package/native/gtk/gst-playback.h +81 -0
  182. package/native/gtk/gtk-backend.cpp +690 -0
  183. package/native/gtk/gtk-backend.h +134 -0
  184. package/native/gtk/host-sources.cpp +354 -0
  185. package/native/gtk/host-sources.h +46 -0
  186. package/native/gtk/image-manipulator.cpp +254 -0
  187. package/native/gtk/image-manipulator.h +30 -0
  188. package/native/gtk/image-view.cpp +256 -0
  189. package/native/gtk/image-view.h +54 -0
  190. package/native/gtk/input-replay.cpp +299 -0
  191. package/native/gtk/input-replay.h +36 -0
  192. package/native/gtk/launcher-badge.cpp +29 -0
  193. package/native/gtk/launcher-badge.h +21 -0
  194. package/native/gtk/locales.cpp +131 -0
  195. package/native/gtk/locales.h +23 -0
  196. package/native/gtk/location.cpp +274 -0
  197. package/native/gtk/location.h +19 -0
  198. package/native/gtk/main.cpp +1092 -0
  199. package/native/gtk/menus.cpp +447 -0
  200. package/native/gtk/menus.h +100 -0
  201. package/native/gtk/native-controls.cpp +831 -0
  202. package/native/gtk/native-controls.h +58 -0
  203. package/native/gtk/network-state.cpp +72 -0
  204. package/native/gtk/network-state.h +24 -0
  205. package/native/gtk/notifications.cpp +235 -0
  206. package/native/gtk/notifications.h +30 -0
  207. package/native/gtk/pango-text.cpp +274 -0
  208. package/native/gtk/pango-text.h +73 -0
  209. package/native/gtk/portal.cpp +451 -0
  210. package/native/gtk/portal.h +71 -0
  211. package/native/gtk/printing.cpp +338 -0
  212. package/native/gtk/printing.h +34 -0
  213. package/native/gtk/proxy-resolver.cpp +74 -0
  214. package/native/gtk/proxy-resolver.h +20 -0
  215. package/native/gtk/screens.cpp +1461 -0
  216. package/native/gtk/screens.h +274 -0
  217. package/native/gtk/scroll-view.cpp +414 -0
  218. package/native/gtk/scroll-view.h +82 -0
  219. package/native/gtk/secret-store.cpp +120 -0
  220. package/native/gtk/secret-store.h +27 -0
  221. package/native/gtk/settings-portal.cpp +129 -0
  222. package/native/gtk/settings-portal.h +47 -0
  223. package/native/gtk/split-view.cpp +1105 -0
  224. package/native/gtk/split-view.h +195 -0
  225. package/native/gtk/status-notifier.cpp +487 -0
  226. package/native/gtk/status-notifier.h +43 -0
  227. package/native/gtk/surface-input.cpp +251 -0
  228. package/native/gtk/surface-input.h +57 -0
  229. package/native/gtk/system-access.cpp +295 -0
  230. package/native/gtk/system-access.h +37 -0
  231. package/native/gtk/text-field.cpp +827 -0
  232. package/native/gtk/text-field.h +78 -0
  233. package/native/gtk/video.cpp +527 -0
  234. package/native/gtk/video.h +47 -0
  235. package/native/gtk/view-widget.cpp +431 -0
  236. package/native/gtk/view-widget.h +105 -0
  237. package/native/gtk/window-scale.cpp +95 -0
  238. package/native/gtk/window-scale.h +35 -0
  239. package/native/scripts/atspi-check.py +310 -0
  240. package/native/scripts/atspi-check.test.py +48 -0
  241. package/native/scripts/build.sh +20 -3
  242. package/native/scripts/compilers.sh +17 -0
  243. package/native/scripts/deb-depends-check.sh +22 -0
  244. package/native/scripts/fetch.sh +23 -2
  245. package/native/scripts/launch-cell.sh +157 -0
  246. package/native/scripts/launch-probe.sh +14 -3
  247. package/native/scripts/make-prebuilt.mjs +133 -44
  248. package/native/scripts/prebuilt-host-cache.mjs +71 -40
  249. package/native/scripts/reset-for-compilers.sh +44 -0
  250. package/native/scripts/start-xvfb.sh +35 -0
  251. package/native/shim/paragraph-platform/react/renderer/components/text/HostPlatformParagraphProps.h +35 -0
  252. package/native/shim/view-platform/react/renderer/components/view/HostPlatformViewTraitsInitializer.h +5 -2
  253. package/native/shim/worklets/linux-reanimated-props.h +14 -0
  254. package/native/shim/worklets/linux-worklets.h +23 -0
  255. package/package.json +6 -3
  256. package/prebuilt.json +70 -6
@@ -0,0 +1,909 @@
1
+ #include "camera.h"
2
+
3
+ #include "audio.h"
4
+ #include "gst-frames.h"
5
+ #include "gst-playback.h"
6
+ #include "image-manipulator.h"
7
+ #include "portal.h"
8
+
9
+ #include <gdk-pixbuf/gdk-pixbuf.h>
10
+ #include <glib/gstdio.h>
11
+ #include <gst/pbutils/pbutils.h>
12
+ #include <sys/stat.h>
13
+ #include <unistd.h>
14
+
15
+ #include <algorithm>
16
+ #include <atomic>
17
+ #include <thread>
18
+ #include <mutex>
19
+ #include <optional>
20
+
21
+ namespace ngn::gtk {
22
+
23
+ namespace {
24
+
25
+ constexpr const char *kCamera = "org.freedesktop.portal.Camera";
26
+ using Access = CameraHardware::Access;
27
+
28
+ // The first of `names` installed, or empty.
29
+ std::string firstInstalled(std::initializer_list<const char *> names) {
30
+ for (const char *name : names) {
31
+ if (gstreamerHas({name})) {
32
+ return name;
33
+ }
34
+ }
35
+ return {};
36
+ }
37
+
38
+ class GstCameraCapture;
39
+
40
+ // Runs `fn` on the main loop.
41
+ void onMainLoop(std::function<void()> fn) {
42
+ g_idle_add_full(G_PRIORITY_DEFAULT, [](gpointer data) -> gboolean {
43
+ (*static_cast<std::function<void()> *>(data))();
44
+ return G_SOURCE_REMOVE;
45
+ }, new std::function<void()>(std::move(fn)), [](gpointer data) { delete static_cast<std::function<void()> *>(data); });
46
+ }
47
+
48
+ class PortalCamera final : public CameraHardware {
49
+ public:
50
+ explicit PortalCamera(CameraSetup setup) : setup_(std::move(setup)) {}
51
+
52
+ Access access() override { return setup_.source.empty() ? access_.load() : Access::Granted; }
53
+
54
+ void requestAccess(std::function<void(Access)> done) override {
55
+ if (!setup_.source.empty()) {
56
+ done(Access::Granted);
57
+ return;
58
+ }
59
+ auto answer = std::make_shared<std::function<void(Access)>>(std::move(done));
60
+ auto *self = this;
61
+ // On the main loop: the portal helper's requests are made and answered there.
62
+ auto *call = new std::function<void()>([self, answer] {
63
+ portal::request(kCamera, "AccessCamera", g_variant_new("()"), g_variant_builder_new(G_VARIANT_TYPE_VARDICT), nullptr,
64
+ [self, answer](portal::Outcome outcome, GVariant *) {
65
+ Access decided = outcome == portal::Outcome::Done ? Access::Granted
66
+ : outcome == portal::Outcome::Absent ? Access::Restricted
67
+ : Access::Denied;
68
+ self->access_ = decided;
69
+ (*answer)(decided);
70
+ });
71
+ });
72
+ g_idle_add_full(G_PRIORITY_DEFAULT, [](gpointer data) -> gboolean {
73
+ (*static_cast<std::function<void()> *>(data))();
74
+ return G_SOURCE_REMOVE;
75
+ }, call, [](gpointer data) { delete static_cast<std::function<void()> *>(data); });
76
+ }
77
+
78
+ bool hasCamera() override {
79
+ if (!setup_.source.empty()) {
80
+ return true;
81
+ }
82
+ GVariant *present = portal::property(kCamera, "IsCameraPresent");
83
+ bool out = present && g_variant_is_of_type(present, G_VARIANT_TYPE_BOOLEAN) && g_variant_get_boolean(present);
84
+ if (present) {
85
+ g_variant_unref(present);
86
+ }
87
+ return out;
88
+ }
89
+
90
+ bool microphoneAllowed() override {
91
+ return setup_.microphone && setup_.microphone->access() == AudioInput::Access::Granted && setup_.microphone->hasMicrophone();
92
+ }
93
+
94
+ // A new stream from the camera, as a bin with one source pad, and the PipeWire connection's fd it
95
+ // holds (-1 for none), or null with `error` set.
96
+ GstElement *source(int &fd, std::string &error) {
97
+ fd = -1;
98
+ GError *failure = nullptr;
99
+ if (!setup_.source.empty()) {
100
+ GstElement *bin = gst_parse_bin_from_description(setup_.source.c_str(), TRUE, &failure);
101
+ if (!bin) {
102
+ error = failure ? failure->message : "the camera could not be opened";
103
+ g_clear_error(&failure);
104
+ }
105
+ return bin;
106
+ }
107
+ fd = portal::openPipeWireRemote(kCamera);
108
+ if (fd < 0) {
109
+ error = "Camera could not be started - the Camera portal opened no connection to the camera.";
110
+ return nullptr;
111
+ }
112
+ GstElement *src = gst_element_factory_make("pipewiresrc", nullptr);
113
+ if (!src) {
114
+ close(fd);
115
+ fd = -1;
116
+ error = "GStreamer's PipeWire plugin (pipewiresrc) is not installed";
117
+ return nullptr;
118
+ }
119
+ // pipewiresrc connects over a duplicate of the fd: the capture closes this one as it goes.
120
+ g_object_set(src, "fd", fd, nullptr);
121
+ return src;
122
+ }
123
+
124
+ const CameraSetup &setup() const { return setup_; }
125
+
126
+ private:
127
+ CameraSetup setup_;
128
+ std::atomic<Access> access_{Access::NotDetermined};
129
+ };
130
+
131
+ // A recording in a pipeline of its own: a second stream from the camera into a movie.
132
+ struct Recording {
133
+ GstElement *pipeline{nullptr};
134
+ int fd{-1};
135
+ std::string path;
136
+ double maxFileSize{0};
137
+ gint64 started{0};
138
+ std::function<void(const std::string &)> done;
139
+ guint poll{0};
140
+ guint limit{0};
141
+ bool ending{false};
142
+ };
143
+
144
+ class GstCameraCapture final : public CameraCapture, public std::enable_shared_from_this<GstCameraCapture> {
145
+ public:
146
+ GstCameraCapture(std::shared_ptr<PortalCamera> camera, GstElement *pipeline, GstElement *sink, int fd, std::shared_ptr<Frames> frames)
147
+ : camera_(std::move(camera)), pipeline_(pipeline), sink_(sink), fd_(fd), frames_(std::move(frames)) {}
148
+
149
+ ~GstCameraCapture() override {
150
+ if (busWatch_) {
151
+ g_source_remove(busWatch_);
152
+ }
153
+ endRecording(true, "");
154
+ gst_element_set_state(pipeline_, GST_STATE_NULL);
155
+ gst_object_unref(sink_);
156
+ gst_object_unref(pipeline_);
157
+ if (fd_ >= 0) {
158
+ close(fd_);
159
+ }
160
+ }
161
+
162
+ const std::shared_ptr<Frames> &frames() const { return frames_; }
163
+
164
+ void takePicture(const CameraPictureRequest &request, std::function<void(int, int, const std::string &)> done) override {
165
+ GstSample *sample = nullptr;
166
+ g_object_get(sink_, "last-sample", &sample, nullptr);
167
+ GdkTexture *texture = sample ? textureOfSample(sample) : nullptr;
168
+ if (sample) {
169
+ gst_sample_unref(sample);
170
+ }
171
+ if (!texture) {
172
+ done(0, 0, "Camera has not shown a frame yet");
173
+ return;
174
+ }
175
+ int width = gdk_texture_get_width(texture), height = gdk_texture_get_height(texture);
176
+ std::string error;
177
+ gchar *folder = g_path_get_dirname(request.path.c_str());
178
+ g_mkdir_with_parents(folder, 0700);
179
+ g_free(folder);
180
+ if (request.format == "png") {
181
+ if (!gdk_texture_save_to_png(texture, request.path.c_str())) {
182
+ error = "the picture could not be written to " + request.path;
183
+ }
184
+ } else {
185
+ G_GNUC_BEGIN_IGNORE_DEPRECATIONS
186
+ GdkPixbuf *withAlpha = gdk_pixbuf_get_from_texture(texture);
187
+ G_GNUC_END_IGNORE_DEPRECATIONS
188
+ GdkPixbuf *pixbuf = withAlpha ? withoutAlpha(withAlpha) : nullptr;
189
+ g_clear_object(&withAlpha);
190
+ std::string quality = std::to_string(static_cast<int>(std::clamp(request.quality, 0.0, 1.0) * 100));
191
+ GError *failure = nullptr;
192
+ if (!pixbuf || !gdk_pixbuf_save(pixbuf, request.path.c_str(), "jpeg", &failure, "quality", quality.c_str(), nullptr)) {
193
+ error = failure ? failure->message : "the picture could not be written to " + request.path;
194
+ }
195
+ g_clear_error(&failure);
196
+ if (pixbuf) {
197
+ g_object_unref(pixbuf);
198
+ }
199
+ }
200
+ g_object_unref(texture);
201
+ done(error.empty() ? width : 0, error.empty() ? height : 0, error);
202
+ }
203
+
204
+ void startRecording(const CameraRecordingRequest &request, std::function<void(const std::string &)> done) override {
205
+ std::lock_guard lock(mutex_);
206
+ if (recording_) {
207
+ done("Camera is already recording");
208
+ return;
209
+ }
210
+ std::string error;
211
+ int fd = -1;
212
+ GstElement *source = camera_->source(fd, error);
213
+ if (!source) {
214
+ done(error);
215
+ return;
216
+ }
217
+ std::string video = cameraVideoEncoder(request.codec, [](const char *name) { return gstreamerHas({name}); });
218
+ std::string aac = request.sound ? firstInstalled({"fdkaacenc", "avenc_aac", "voaacenc"}) : "";
219
+ const auto &setup = camera_->setup();
220
+ std::string line = "videoconvert name=convert ! video/x-raw,format=I420 ! " + video + " ! queue ! qtmux name=mux ! filesink name=file";
221
+ if (!aac.empty()) {
222
+ line += " " + (setup.microphoneSource.empty() ? std::string("pulsesrc") : setup.microphoneSource) +
223
+ " ! audioconvert ! audioresample ! " + aac + " ! queue ! mux.";
224
+ }
225
+ GError *failure = nullptr;
226
+ GstElement *pipeline = gst_parse_launch(line.c_str(), &failure);
227
+ if (!pipeline || failure) {
228
+ done(failure ? failure->message : "the recording could not be made");
229
+ g_clear_error(&failure);
230
+ if (pipeline) {
231
+ gst_object_unref(pipeline);
232
+ }
233
+ gst_object_unref(gst_object_ref_sink(source));
234
+ if (fd >= 0) {
235
+ close(fd);
236
+ }
237
+ return;
238
+ }
239
+ // By the name given: an element's default name counts every one made in the process.
240
+ GstElement *convert = gst_bin_get_by_name(GST_BIN(pipeline), "convert");
241
+ gst_bin_add(GST_BIN(pipeline), source);
242
+ bool linked = gst_element_link(source, convert);
243
+ gst_object_unref(convert);
244
+ if (!linked) {
245
+ gst_object_unref(pipeline);
246
+ if (fd >= 0) {
247
+ close(fd);
248
+ }
249
+ done("the camera's stream could not be recorded");
250
+ return;
251
+ }
252
+ GstElement *file = gst_bin_get_by_name(GST_BIN(pipeline), "file");
253
+ gchar *folder = g_path_get_dirname(request.path.c_str());
254
+ g_mkdir_with_parents(folder, 0700);
255
+ g_free(folder);
256
+ g_object_set(file, "location", request.path.c_str(), nullptr);
257
+ gst_object_unref(file);
258
+ auto r = std::make_unique<Recording>();
259
+ r->pipeline = pipeline;
260
+ r->fd = fd;
261
+ r->path = request.path;
262
+ r->maxFileSize = request.maxFileSize;
263
+ r->started = g_get_monotonic_time();
264
+ r->done = std::move(done);
265
+ if (gst_element_set_state(pipeline, GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
266
+ auto answer = std::move(r->done);
267
+ gst_element_set_state(pipeline, GST_STATE_NULL);
268
+ gst_object_unref(pipeline);
269
+ if (fd >= 0) {
270
+ close(fd);
271
+ }
272
+ answer("the camera or the file " + request.path + " could not be opened");
273
+ return;
274
+ }
275
+ auto *weak = new std::weak_ptr<GstCameraCapture>(weak_from_this());
276
+ r->poll = g_timeout_add_full(G_PRIORITY_DEFAULT, 100, [](gpointer data) -> gboolean {
277
+ auto self = static_cast<std::weak_ptr<GstCameraCapture> *>(data)->lock();
278
+ return self && self->pollRecording() ? G_SOURCE_CONTINUE : G_SOURCE_REMOVE;
279
+ }, weak, [](gpointer data) { delete static_cast<std::weak_ptr<GstCameraCapture> *>(data); });
280
+ if (request.maxDuration > 0) {
281
+ auto *limitWeak = new std::weak_ptr<GstCameraCapture>(weak_from_this());
282
+ r->limit = g_timeout_add_full(G_PRIORITY_DEFAULT, static_cast<guint>(request.maxDuration * 1000), [](gpointer data) -> gboolean {
283
+ if (auto self = static_cast<std::weak_ptr<GstCameraCapture> *>(data)->lock()) {
284
+ {
285
+ std::lock_guard lock(self->mutex_);
286
+ if (self->recording_) {
287
+ self->recording_->limit = 0;
288
+ }
289
+ }
290
+ self->stopRecording();
291
+ }
292
+ return G_SOURCE_REMOVE;
293
+ }, limitWeak, [](gpointer data) { delete static_cast<std::weak_ptr<GstCameraCapture> *>(data); });
294
+ }
295
+ recording_ = std::move(r);
296
+ }
297
+
298
+ void stopRecording() override {
299
+ std::lock_guard lock(mutex_);
300
+ if (recording_ && !recording_->ending) {
301
+ recording_->ending = true;
302
+ // The muxer writes its index at the end of the stream: each live source ends it.
303
+ gst_element_send_event(recording_->pipeline, gst_event_new_eos());
304
+ }
305
+ }
306
+
307
+ bool recording() const override {
308
+ std::lock_guard lock(mutex_);
309
+ return recording_ != nullptr;
310
+ }
311
+
312
+ private:
313
+ // On the main loop while recording: whether to keep polling.
314
+ bool pollRecording() {
315
+ std::string error;
316
+ bool ended = false;
317
+ {
318
+ std::lock_guard lock(mutex_);
319
+ if (!recording_) {
320
+ return false;
321
+ }
322
+ GstBus *bus = gst_element_get_bus(recording_->pipeline);
323
+ while (GstMessage *message = gst_bus_pop_filtered(bus, static_cast<GstMessageType>(GST_MESSAGE_EOS | GST_MESSAGE_ERROR))) {
324
+ if (GST_MESSAGE_TYPE(message) == GST_MESSAGE_ERROR) {
325
+ GError *failure = nullptr;
326
+ gst_message_parse_error(message, &failure, nullptr);
327
+ error = failure ? failure->message : "the recording failed";
328
+ g_clear_error(&failure);
329
+ }
330
+ ended = true;
331
+ gst_message_unref(message);
332
+ }
333
+ gst_object_unref(bus);
334
+ struct stat file {};
335
+ if (!ended && recording_->maxFileSize > 0 && !recording_->ending && stat(recording_->path.c_str(), &file) == 0 &&
336
+ file.st_size >= recording_->maxFileSize) {
337
+ recording_->ending = true;
338
+ gst_element_send_event(recording_->pipeline, gst_event_new_eos());
339
+ }
340
+ }
341
+ if (ended) {
342
+ endRecording(false, error);
343
+ }
344
+ return !ended;
345
+ }
346
+
347
+ // Ends the recording: with `wait`, first carries the end of the stream through (bounded).
348
+ void endRecording(bool wait, const std::string &error) {
349
+ std::unique_ptr<Recording> r;
350
+ {
351
+ std::lock_guard lock(mutex_);
352
+ r = std::move(recording_);
353
+ }
354
+ if (!r) {
355
+ return;
356
+ }
357
+ std::string failed = error;
358
+ if (wait) {
359
+ gst_element_send_event(r->pipeline, gst_event_new_eos());
360
+ GstBus *bus = gst_element_get_bus(r->pipeline);
361
+ GstMessage *end = gst_bus_timed_pop_filtered(bus, 3 * GST_SECOND, static_cast<GstMessageType>(GST_MESSAGE_EOS | GST_MESSAGE_ERROR));
362
+ gst_object_unref(bus);
363
+ if (!end) {
364
+ failed = "the recording did not finish writing its file";
365
+ } else if (GST_MESSAGE_TYPE(end) == GST_MESSAGE_ERROR && failed.empty()) {
366
+ GError *why = nullptr;
367
+ gst_message_parse_error(end, &why, nullptr);
368
+ failed = why && why->message ? why->message : "the recording failed";
369
+ g_clear_error(&why);
370
+ }
371
+ if (end) {
372
+ gst_message_unref(end);
373
+ }
374
+ }
375
+ if (r->poll) {
376
+ g_source_remove(r->poll);
377
+ }
378
+ if (r->limit) {
379
+ g_source_remove(r->limit);
380
+ }
381
+ gst_element_set_state(r->pipeline, GST_STATE_NULL);
382
+ gst_object_unref(r->pipeline);
383
+ if (r->fd >= 0) {
384
+ close(r->fd);
385
+ }
386
+ if (r->done) {
387
+ r->done(failed);
388
+ }
389
+ }
390
+
391
+ public:
392
+ // Called on the main loop with the stream's error, once, if it fails after it started.
393
+ void watchErrors(std::function<void(const std::string &)> failed) {
394
+ GstBus *bus = gst_element_get_bus(pipeline_);
395
+ auto *watch = new std::pair<std::weak_ptr<GstCameraCapture>, std::function<void(const std::string &)>>(weak_from_this(), std::move(failed));
396
+ busWatch_ = gst_bus_add_watch_full(bus, G_PRIORITY_DEFAULT, [](GstBus *, GstMessage *message, gpointer data) -> gboolean {
397
+ if (GST_MESSAGE_TYPE(message) != GST_MESSAGE_ERROR) {
398
+ return G_SOURCE_CONTINUE;
399
+ }
400
+ auto &[weak, failed] = *static_cast<std::pair<std::weak_ptr<GstCameraCapture>, std::function<void(const std::string &)>> *>(data);
401
+ if (auto self = weak.lock()) {
402
+ self->busWatch_ = 0;
403
+ GError *why = nullptr;
404
+ gst_message_parse_error(message, &why, nullptr);
405
+ std::string text = why && why->message ? why->message : "the camera's stream failed";
406
+ g_clear_error(&why);
407
+ auto call = failed;
408
+ call("Camera stopped - " + text);
409
+ }
410
+ return G_SOURCE_REMOVE;
411
+ }, watch, [](gpointer data) { delete static_cast<std::pair<std::weak_ptr<GstCameraCapture>, std::function<void(const std::string &)>> *>(data); });
412
+ gst_object_unref(bus);
413
+ }
414
+
415
+ private:
416
+ guint busWatch_{0};
417
+ std::shared_ptr<PortalCamera> camera_;
418
+ GstElement *pipeline_;
419
+ GstElement *sink_;
420
+ int fd_;
421
+ std::shared_ptr<Frames> frames_;
422
+ mutable std::mutex mutex_;
423
+ std::unique_ptr<Recording> recording_;
424
+ };
425
+
426
+ // A running camera from `hardware`, or null with `error` set.
427
+ std::shared_ptr<GstCameraCapture> startCapture(const std::shared_ptr<CameraHardware> &hardware, std::string &error) {
428
+ auto camera = std::dynamic_pointer_cast<PortalCamera>(hardware);
429
+ if (!camera) {
430
+ error = "Camera could not be started";
431
+ return nullptr;
432
+ }
433
+ int fd = -1;
434
+ GstElement *source = camera->source(fd, error);
435
+ if (!source) {
436
+ return nullptr;
437
+ }
438
+ auto frames = std::make_shared<Frames>();
439
+ GstElement *pipeline = GST_ELEMENT(gst_object_ref_sink(gst_pipeline_new(nullptr)));
440
+ GstElement *convert = gst_element_factory_make("videoconvert", nullptr);
441
+ GstElement *made = makeFrameSink(frames, false);
442
+ if (!convert || !made) {
443
+ gst_object_unref(gst_object_ref_sink(source));
444
+ if (convert) {
445
+ gst_object_unref(gst_object_ref_sink(convert));
446
+ }
447
+ gst_object_unref(pipeline);
448
+ if (fd >= 0) {
449
+ close(fd);
450
+ }
451
+ error = "Camera could not be started - GStreamer's videoconvert or appsink is not installed.";
452
+ return nullptr;
453
+ }
454
+ GstElement *sink = GST_ELEMENT(gst_object_ref_sink(made));
455
+ gst_bin_add_many(GST_BIN(pipeline), source, convert, sink, nullptr);
456
+ auto capture = std::make_shared<GstCameraCapture>(camera, pipeline, sink, fd, frames);
457
+ if (!gst_element_link_many(source, convert, sink, nullptr) ||
458
+ gst_element_set_state(pipeline, GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
459
+ error = "Camera could not be started - its stream did not open.";
460
+ return nullptr;
461
+ }
462
+ return capture;
463
+ }
464
+
465
+ // Starts a camera off the main loop, where the portal's call and the stream's start would block
466
+ // it, and answers there. A capture `done` does not keep is stopped on the main loop.
467
+ void startCaptureAsync(std::shared_ptr<CameraHardware> hardware,
468
+ std::function<void(std::shared_ptr<GstCameraCapture>, const std::string &)> done) {
469
+ std::thread([hardware = std::move(hardware), done = std::move(done)]() mutable {
470
+ std::string error;
471
+ auto capture = startCapture(hardware, error);
472
+ onMainLoop([capture = std::move(capture), error, done = std::move(done)]() mutable { done(std::move(capture), error); });
473
+ }).detach();
474
+ }
475
+
476
+ std::shared_ptr<CameraHardware> gHardware;
477
+ std::shared_ptr<CameraViews> gViews;
478
+ bool gNoPrompts = false;
479
+
480
+ } // namespace
481
+
482
+ std::string cameraVideoEncoder(const std::string &codec, const std::function<bool(const char *)> &installed) {
483
+ if (codec != "jpeg" && installed("h264parse")) {
484
+ // qtmux takes H.264 in its avc form, which h264parse makes of an encoder's byte stream.
485
+ for (const char *encoder : {"x264enc", "openh264enc"}) {
486
+ if (installed(encoder)) {
487
+ return std::string(encoder) + " ! h264parse";
488
+ }
489
+ }
490
+ }
491
+ return "jpegenc";
492
+ }
493
+
494
+ std::shared_ptr<CameraHardware> makeCameraHardware(CameraSetup setup) {
495
+ if (!gstreamerHas({"videoconvert", "appsink"}) || (setup.source.empty() && !gstreamerHas({"pipewiresrc"}))) {
496
+ return nullptr;
497
+ }
498
+ return std::make_shared<PortalCamera>(std::move(setup));
499
+ }
500
+
501
+ void useCameraHardware(std::shared_ptr<CameraHardware> hardware, std::shared_ptr<CameraViews> views, bool noPrompts) {
502
+ gHardware = std::move(hardware);
503
+ gViews = std::move(views);
504
+ gNoPrompts = noPrompts;
505
+ }
506
+
507
+ // --- the view ------------------------------------------------------------------------------------
508
+
509
+ struct CameraSurface : std::enable_shared_from_this<CameraSurface> {
510
+ GtkWidget *picture{nullptr};
511
+ int tag{0};
512
+ std::function<void(const std::string &, folly::dynamic)> send;
513
+ std::shared_ptr<GstCameraCapture> capture;
514
+ int watcher{-1};
515
+ bool active{false};
516
+ bool asking{false};
517
+ bool asked{false};
518
+ bool reported{false};
519
+ // A start in flight, off the main loop.
520
+ bool starting{false};
521
+ // Whether this start has sent cameraReady.
522
+ bool ready{false};
523
+ // Which start a frame belongs to: a stop moves it on.
524
+ uint64_t start{0};
525
+
526
+ ~CameraSurface() {
527
+ stop();
528
+ if (picture) {
529
+ if (gtk_widget_get_parent(picture)) {
530
+ gtk_widget_unparent(picture);
531
+ }
532
+ g_object_unref(picture);
533
+ }
534
+ }
535
+
536
+ void report(const std::string &message) {
537
+ if (!reported) {
538
+ reported = true;
539
+ send("mountError", folly::dynamic::object("message", message));
540
+ }
541
+ }
542
+
543
+ void stop() {
544
+ start++;
545
+ if (gViews) {
546
+ gViews->detach(tag);
547
+ }
548
+ if (capture) {
549
+ capture->frames()->unwatch(watcher);
550
+ watcher = -1;
551
+ capture = nullptr;
552
+ }
553
+ if (picture) {
554
+ gtk_picture_set_paintable(GTK_PICTURE(picture), nullptr);
555
+ }
556
+ }
557
+
558
+ void follow() {
559
+ if (!active) {
560
+ stop();
561
+ return;
562
+ }
563
+ if (!gHardware || capture || asking || starting) {
564
+ return;
565
+ }
566
+ auto mount = cameraMount(gHardware->access(), gHardware->hasCamera(), gNoPrompts, asked);
567
+ if (mount == CameraMount::Ask) {
568
+ asking = true;
569
+ asked = true;
570
+ std::weak_ptr<CameraSurface> weak = weak_from_this();
571
+ gHardware->requestAccess([weak](CameraHardware::Access) {
572
+ auto *later = new std::weak_ptr<CameraSurface>(weak);
573
+ g_idle_add_full(G_PRIORITY_DEFAULT, [](gpointer data) -> gboolean {
574
+ if (auto self = static_cast<std::weak_ptr<CameraSurface> *>(data)->lock()) {
575
+ self->asking = false;
576
+ self->follow();
577
+ }
578
+ return G_SOURCE_REMOVE;
579
+ }, later, [](gpointer data) { delete static_cast<std::weak_ptr<CameraSurface> *>(data); });
580
+ });
581
+ return;
582
+ }
583
+ if (mount != CameraMount::Start) {
584
+ report(cameraMountError(mount));
585
+ return;
586
+ }
587
+ starting = true;
588
+ uint64_t at = ++start;
589
+ std::weak_ptr<CameraSurface> weak = weak_from_this();
590
+ startCaptureAsync(gHardware, [weak, at](std::shared_ptr<GstCameraCapture> started, const std::string &error) {
591
+ auto self = weak.lock();
592
+ if (!self) {
593
+ return;
594
+ }
595
+ self->starting = false;
596
+ if (self->start != at) {
597
+ // Stopped while it started: what it started goes, and the view starts again if it should.
598
+ self->follow();
599
+ return;
600
+ }
601
+ if (!started) {
602
+ self->report(error);
603
+ return;
604
+ }
605
+ self->attach(std::move(started), at);
606
+ });
607
+ }
608
+
609
+ void attach(std::shared_ptr<GstCameraCapture> started, uint64_t at) {
610
+ capture = std::move(started);
611
+ ready = false;
612
+ auto *self = this;
613
+ watcher = capture->frames()->watch([self, at](GdkTexture *texture) {
614
+ gtk_picture_set_paintable(GTK_PICTURE(self->picture), texture ? GDK_PAINTABLE(texture) : nullptr);
615
+ if (texture && !self->ready && self->start == at) {
616
+ self->ready = true;
617
+ self->send("cameraReady", folly::dynamic::object());
618
+ }
619
+ });
620
+ std::weak_ptr<CameraSurface> weak = weak_from_this();
621
+ capture->watchErrors([weak, at](const std::string &error) {
622
+ if (auto self = weak.lock(); self && self->start == at) {
623
+ self->stop();
624
+ self->report(error);
625
+ }
626
+ });
627
+ if (gViews) {
628
+ gViews->attach(tag, capture);
629
+ }
630
+ }
631
+ };
632
+
633
+ std::shared_ptr<CameraSurface> makeCameraSurface(GtkWidget *view, int tag, std::function<void(const std::string &, folly::dynamic)> send) {
634
+ auto s = std::make_shared<CameraSurface>();
635
+ s->tag = tag;
636
+ s->send = std::move(send);
637
+ s->picture = GTK_WIDGET(g_object_ref_sink(gtk_picture_new()));
638
+ gtk_picture_set_content_fit(GTK_PICTURE(s->picture), GTK_CONTENT_FIT_COVER);
639
+ gtk_picture_set_can_shrink(GTK_PICTURE(s->picture), TRUE);
640
+ gtk_widget_set_parent(s->picture, view);
641
+ return s;
642
+ }
643
+
644
+ void applyCameraSurface(CameraSurface &s, const CameraProps &props) {
645
+ // Set first, so the camera is never attached without it.
646
+ if (gViews) {
647
+ gViews->mute(s.tag, props.mute);
648
+ }
649
+ s.active = props.active;
650
+ s.follow();
651
+ }
652
+
653
+ GtkWidget *cameraWidget(CameraSurface &s) {
654
+ return s.picture;
655
+ }
656
+
657
+ GtkPicture *cameraPicture(CameraSurface &s) {
658
+ return GTK_PICTURE(s.picture);
659
+ }
660
+
661
+ // --- the sheet -----------------------------------------------------------------------------------
662
+
663
+ namespace {
664
+
665
+ std::optional<CameraClip> clipOf(const std::string &path) {
666
+ GstDiscoverer *discoverer = gst_discoverer_new(5 * GST_SECOND, nullptr);
667
+ if (!discoverer) {
668
+ return std::nullopt;
669
+ }
670
+ gchar *uri = g_filename_to_uri(path.c_str(), nullptr, nullptr);
671
+ GstDiscovererInfo *info = uri ? gst_discoverer_discover_uri(discoverer, uri, nullptr) : nullptr;
672
+ g_free(uri);
673
+ std::optional<CameraClip> out;
674
+ if (info) {
675
+ GList *videos = gst_discoverer_info_get_video_streams(info);
676
+ if (videos) {
677
+ auto *video = GST_DISCOVERER_VIDEO_INFO(videos->data);
678
+ out = CameraClip{.width = static_cast<int>(gst_discoverer_video_info_get_width(video)),
679
+ .height = static_cast<int>(gst_discoverer_video_info_get_height(video)),
680
+ .duration = static_cast<double>(gst_discoverer_info_get_duration(info)) / GST_MSECOND};
681
+ }
682
+ gst_discoverer_stream_info_list_free(videos);
683
+ g_object_unref(info);
684
+ }
685
+ g_object_unref(discoverer);
686
+ return out;
687
+ }
688
+
689
+ struct Sheet {
690
+ CameraSheetRequest request;
691
+ std::function<void(CameraTake, const std::string &)> done;
692
+ std::shared_ptr<GstCameraCapture> capture;
693
+ GtkWindow *window{nullptr};
694
+ GtkWidget *shutter{nullptr};
695
+ GtkWidget *cancel{nullptr};
696
+ GtkWidget *photo{nullptr};
697
+ GtkWidget *video{nullptr};
698
+ GtkPicture *preview{nullptr};
699
+ int watcher{-1};
700
+ bool videoMode{false};
701
+ bool recording{false};
702
+ bool answered{false};
703
+ // False once the sheet has answered: a recording that ends after hears nothing.
704
+ std::shared_ptr<bool> alive = std::make_shared<bool>(true);
705
+
706
+ void finish(CameraTake take, const std::string &error);
707
+ };
708
+
709
+ Sheet *gSheet = nullptr;
710
+
711
+ void Sheet::finish(CameraTake take, const std::string &error) {
712
+ if (answered) {
713
+ return;
714
+ }
715
+ answered = true;
716
+ *alive = false;
717
+ auto answer = std::move(done);
718
+ if (capture) {
719
+ capture->frames()->unwatch(watcher);
720
+ // Let go on a later turn: the answer can come from inside the capture's own call.
721
+ g_idle_add_full(G_PRIORITY_DEFAULT, [](gpointer) -> gboolean { return G_SOURCE_REMOVE; },
722
+ new std::shared_ptr<GstCameraCapture>(std::move(capture)),
723
+ [](gpointer data) { delete static_cast<std::shared_ptr<GstCameraCapture> *>(data); });
724
+ }
725
+ if (window) {
726
+ g_signal_handlers_disconnect_by_data(window, this);
727
+ gtk_window_destroy(std::exchange(window, nullptr));
728
+ }
729
+ if (gSheet == this) {
730
+ gSheet = nullptr;
731
+ }
732
+ answer(std::move(take), error);
733
+ delete this;
734
+ }
735
+
736
+ void updateShutter(Sheet &s) {
737
+ gtk_button_set_label(GTK_BUTTON(s.shutter), !s.videoMode ? "Take Photo" : s.recording ? "Stop" : "Record");
738
+ if (s.photo) {
739
+ gtk_widget_set_sensitive(s.photo, !s.recording);
740
+ gtk_widget_set_sensitive(s.video, !s.recording);
741
+ }
742
+ }
743
+
744
+ void pressShutter(Sheet &s) {
745
+ if (!s.capture) {
746
+ return;
747
+ }
748
+ if (!s.videoMode) {
749
+ s.capture->takePicture(s.request.photo, [&s](int width, int height, const std::string &error) {
750
+ if (!error.empty()) {
751
+ s.finish({}, error);
752
+ return;
753
+ }
754
+ s.finish(CameraTake{.photo = CameraShot{.width = width, .height = height}}, "");
755
+ });
756
+ return;
757
+ }
758
+ if (s.recording) {
759
+ s.capture->stopRecording();
760
+ return;
761
+ }
762
+ s.recording = true;
763
+ updateShutter(s);
764
+ auto path = s.request.video.path;
765
+ s.capture->startRecording(s.request.video, [&s, alive = s.alive, path](const std::string &error) {
766
+ if (!*alive) {
767
+ // Cancelled while it recorded: the movie is no one's.
768
+ g_unlink(path.c_str());
769
+ return;
770
+ }
771
+ if (!error.empty()) {
772
+ s.finish({}, error);
773
+ return;
774
+ }
775
+ auto clip = clipOf(path);
776
+ s.finish(clip ? CameraTake{.video = *clip} : CameraTake{}, clip ? "" : "the recording has no video");
777
+ });
778
+ }
779
+
780
+ void showSheet(CameraSheetRequest request, std::function<void(CameraTake, const std::string &)> done) {
781
+ if (gSheet || !gHardware) {
782
+ done({}, "");
783
+ return;
784
+ }
785
+ auto *s = new Sheet{.request = std::move(request), .done = std::move(done)};
786
+ s->videoMode = !s->request.photos && s->request.videos;
787
+ gSheet = s;
788
+ GtkWidget *window = gtk_window_new();
789
+ s->window = GTK_WINDOW(window);
790
+ gtk_window_set_title(s->window, "Camera");
791
+ gtk_window_set_modal(s->window, TRUE);
792
+ gtk_window_set_default_size(s->window, 640, 520);
793
+ if (GtkWindow *front = portal::frontWindow()) {
794
+ gtk_window_set_transient_for(s->window, front);
795
+ }
796
+ GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
797
+ GtkWidget *picture = gtk_picture_new();
798
+ gtk_picture_set_content_fit(GTK_PICTURE(picture), GTK_CONTENT_FIT_CONTAIN);
799
+ gtk_widget_set_vexpand(picture, TRUE);
800
+ gtk_box_append(GTK_BOX(box), picture);
801
+ s->preview = GTK_PICTURE(picture);
802
+ GtkWidget *bar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
803
+ gtk_widget_set_margin_start(bar, 12);
804
+ gtk_widget_set_margin_end(bar, 12);
805
+ gtk_widget_set_margin_top(bar, 12);
806
+ gtk_widget_set_margin_bottom(bar, 12);
807
+ s->cancel = gtk_button_new_with_label("Cancel");
808
+ g_signal_connect(s->cancel, "clicked", G_CALLBACK(+[](GtkButton *, gpointer data) { static_cast<Sheet *>(data)->finish({}, ""); }), s);
809
+ gtk_box_append(GTK_BOX(bar), s->cancel);
810
+ GtkWidget *middle = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
811
+ gtk_widget_set_hexpand(middle, TRUE);
812
+ gtk_widget_set_halign(middle, GTK_ALIGN_CENTER);
813
+ if (s->request.photos && s->request.videos) {
814
+ gtk_widget_add_css_class(middle, "linked");
815
+ s->photo = gtk_toggle_button_new_with_label("Photo");
816
+ s->video = gtk_toggle_button_new_with_label("Video");
817
+ gtk_toggle_button_set_group(GTK_TOGGLE_BUTTON(s->video), GTK_TOGGLE_BUTTON(s->photo));
818
+ gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(s->photo), TRUE);
819
+ g_signal_connect(s->video, "toggled", G_CALLBACK(+[](GtkToggleButton *button, gpointer data) {
820
+ auto &s = *static_cast<Sheet *>(data);
821
+ s.videoMode = gtk_toggle_button_get_active(button);
822
+ updateShutter(s);
823
+ }), s);
824
+ gtk_box_append(GTK_BOX(middle), s->photo);
825
+ gtk_box_append(GTK_BOX(middle), s->video);
826
+ }
827
+ gtk_box_append(GTK_BOX(bar), middle);
828
+ s->shutter = gtk_button_new_with_label("Take Photo");
829
+ // Until the camera shows a frame there is nothing to take.
830
+ gtk_widget_set_sensitive(s->shutter, FALSE);
831
+ gtk_widget_add_css_class(s->shutter, "suggested-action");
832
+ g_signal_connect(s->shutter, "clicked", G_CALLBACK(+[](GtkButton *, gpointer data) { pressShutter(*static_cast<Sheet *>(data)); }), s);
833
+ gtk_box_append(GTK_BOX(bar), s->shutter);
834
+ gtk_box_append(GTK_BOX(box), bar);
835
+ gtk_window_set_child(s->window, box);
836
+ gtk_window_set_default_widget(s->window, s->shutter);
837
+ GtkEventController *keys = gtk_event_controller_key_new();
838
+ g_signal_connect(keys, "key-pressed", G_CALLBACK(+[](GtkEventControllerKey *, guint key, guint, GdkModifierType, gpointer data) -> gboolean {
839
+ if (key == GDK_KEY_Escape) {
840
+ static_cast<Sheet *>(data)->finish({}, "");
841
+ return TRUE;
842
+ }
843
+ return FALSE;
844
+ }), s);
845
+ gtk_widget_add_controller(window, keys);
846
+ g_signal_connect(window, "close-request", G_CALLBACK(+[](GtkWindow *, gpointer data) -> gboolean {
847
+ static_cast<Sheet *>(data)->finish({}, "");
848
+ return TRUE;
849
+ }), s);
850
+ updateShutter(*s);
851
+ gtk_window_present(s->window);
852
+ startCaptureAsync(gHardware, [s, alive = s->alive](std::shared_ptr<GstCameraCapture> capture, const std::string &error) {
853
+ if (!*alive) {
854
+ return;
855
+ }
856
+ if (!capture) {
857
+ s->finish({}, error);
858
+ return;
859
+ }
860
+ s->capture = capture;
861
+ s->watcher = capture->frames()->watch([s](GdkTexture *texture) {
862
+ gtk_picture_set_paintable(s->preview, texture ? GDK_PAINTABLE(texture) : nullptr);
863
+ if (texture) {
864
+ gtk_widget_set_sensitive(s->shutter, TRUE);
865
+ }
866
+ });
867
+ capture->watchErrors([s, alive = s->alive](const std::string &failed) {
868
+ if (*alive) {
869
+ s->finish({}, failed);
870
+ }
871
+ });
872
+ });
873
+ }
874
+
875
+ class GtkCameraSheet final : public CameraSheet {
876
+ public:
877
+ void shoot(const CameraSheetRequest &request, std::function<void(CameraTake, const std::string &)> done) override {
878
+ // On the main loop, whichever thread asks.
879
+ auto *call = new std::function<void()>([request, done = std::move(done)]() mutable { showSheet(std::move(request), std::move(done)); });
880
+ g_idle_add_full(G_PRIORITY_DEFAULT, [](gpointer data) -> gboolean {
881
+ (*static_cast<std::function<void()> *>(data))();
882
+ return G_SOURCE_REMOVE;
883
+ }, call, [](gpointer data) { delete static_cast<std::function<void()> *>(data); });
884
+ }
885
+ };
886
+
887
+ } // namespace
888
+
889
+ std::shared_ptr<CameraSheet> makeCameraSheet() {
890
+ return std::make_shared<GtkCameraSheet>();
891
+ }
892
+
893
+ GtkWindow *cameraSheetWindow() {
894
+ return gSheet ? gSheet->window : nullptr;
895
+ }
896
+
897
+ GtkPicture *cameraSheetPreview() {
898
+ return gSheet ? gSheet->preview : nullptr;
899
+ }
900
+
901
+ GtkWidget *cameraSheetShutter() {
902
+ return gSheet ? gSheet->shutter : nullptr;
903
+ }
904
+
905
+ GtkWidget *cameraSheetCancel() {
906
+ return gSheet ? gSheet->cancel : nullptr;
907
+ }
908
+
909
+ } // namespace ngn::gtk