Debian Codegraph @

portal-test/gtk4/window.js

raw
1 const { GdkPixbuf, Gio, GLib, GObject, Gst,
2 Gtk, Pango, PangoCairo, Xdp, XdpGtk4 } = imports.gi;
3
4 var PortalTestWindow = GObject.registerClass({
5 GTypeName: 'PortalTestWin',
6 Template: 'resource:///org/gnome/PortalTest/Gtk4/window.ui',
7 InternalChildren: [
8 'sandboxStatus',
9 'networkStatus',
10 'monitorName',
11 'proxies',
12 'resolverName',
13 'image',
14 'interactive',
15 'encoding',
16 'ackImage',
17 'inhibitIdle',
18 'inhibitLogout',
19 'inhibitSuspend',
20 'inhibitSwitch',
21 'username',
22 'realname',
23 'avatar',
24 'saveHow',
25 'screencastLabel',
26 'screencastToggle',
27 'updateDialog',
28 'updateDialog2',
29 'updateProgressbar',
30 'updateLabel',
31 'ok2',
32 'openLocalDir',
33 'openLocalAsk',
34 ],
35 }, class PortalTestWindow extends Gtk.ApplicationWindow {
36 _init(application) {
37 super._init({ application });
38
39 this._app = application;
40 this._portal = new Xdp.Portal();
41
42 this._restoreToken = null;
43
44 // Sandbox status
45 const path = GLib.build_filenamev([GLib.get_user_runtime_dir(), 'flatpak-info']);
46 this._sandboxStatus.label =
47 GLib.file_test(path, GLib.FileTest.EXISTS) ? 'confined' : 'unconfined';
48
49 // Network monitor
50 this._monitor = Gio.NetworkMonitor.get_default();
51 this._monitorName.label = this._monitor.constructor.$gtype.name;
52 this._monitor.connect('notify', () => this._updateNetworkStatus());
53 this._updateNetworkStatus();
54
55 // Proxy resolver
56 this._resolver = Gio.ProxyResolver.get_default();
57 this._resolverName.label = this._resolver.constructor.$gtype.name;
58
59 try {
60 const proxies = this._resolver.lookup('http://www.flatpak.org', null);
61 this._proxies.label = proxies.join(', ');
62 } catch(e) {
63 logError(e);
64 }
65
66 // Updates
67 const file = Gio.File.new_for_path('/app/.updated');
68 this._updateMonitor = file.monitor_file(Gio.FileMonitorFlags.NONE, null);
69 this._updateMonitor.connect('changed', (monitor, file, other, event) => {
70 if (event !== Gio.FileMonitorEvent.CREATED)
71 return;
72
73 GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 5, () => {
74 if (this._updateDialog2.visible)
75 return GLib.SOURCE_CONTINUE;
76 this._updateDialog2.present();
77 return GLib.SOURCE_REMOVE;
78 });
79 });
80
81 this._portal.update_monitor_start(Xdp.UpdateMonitorFlags.NONE, null, null);
82 this._portal.connect('update-available', (portal, running, local, remote) => {
83 log('Update available');
84 this._updateLabel.label = 'Update available';
85 this._updateProgressbar.fraction = 0.0;
86 this._updateDialog2.present();
87 });
88 }
89
90 _updateNetworkStatus() {
91 const networkStatus = [];
92
93 if (this._monitor.networkAvailable)
94 networkStatus.push('available');
95
96 if (this._monitor.networkMetered)
97 networkStatus.push('metered');
98
99 switch (this._monitor.connectivity) {
100 case Gio.NetworkConnectivity.LOCAL:
101 networkStatus.push('local');
102 break;
103 case Gio.NetworkConnectivity.LIMITED:
104 networkStatus.push('limited');
105 break;
106 case Gio.NetworkConnectivity.PORTAL:
107 networkStatus.push('portal');
108 break;
109 case Gio.NetworkConnectivity.FULL:
110 networkStatus.push('full');
111 break;
112 }
113 this._networkStatus.label = networkStatus.join(', ');
114 }
115
116 _updateDialogResponse(dialog, response) {
117 if (response === Gtk.ResponseType.OK)
118 this.get_application().restart();
119
120 dialog.hide();
121 }
122
123 _updateDialog2Response(dialog, response) {
124 if (response === Gtk.ResponseType.OK) {
125 const parent = XdpGtk4.parent_new_gtk(this);
126 this._portal.update_install(
127 parent,
128 Xdp.UpdateInstallFlags.NONE,
129 (portal, result) => {
130 try {
131 this._portal.update_install_finish(result);
132 } catch(e) {
133 logError(e);
134 this._updateDialog2.hide();
135 }
136
137 this._updateLabel.label = 'Installing…';
138 this._ok2.sensitive = false;
139 const updateProgressId = this._portal.connect(
140 'update-progress',
141 (portal, nOps, op, progress, status, error, message) => {
142 log('Progress!');
143 this._updateProgressbar.fraction = progress / 100.0;
144 if (status === Xdp.UpdateStatus.FAILED) {
145 this._updateLabel.label = 'Something went wrong';
146 this._updateProgressbar.hide();
147 } else if (status === Xdp.UpdateStatus.DONE) {
148 this._updateLabel.label = 'Installed';
149 }
150
151 if (status !== Xdp.UpdateStatus.RUNNING)
152 this._portal.disconnect(updateProgressId);
153 });
154 });
155 }
156
157 dialog.hide();
158 }
159
160 _composeEmail() {
161 const parent = XdpGtk4.parent_new_gtk(this);
162
163 this._portal.compose_email(
164 parent,
165 ['[email protected]'],
166 ['[email protected]', '[email protected]'],
167 null,
168 'Test subject',
169 'Test body',
170 null,
171 Xdp.EmailFlags.NONE,
172 null,
173 (source, result) => {
174 try {
175 this._portal.compose_email_finish(result);
176 log('Email sent');
177 } catch (e) {
178 logError(e);
179 }
180 }
181 );
182 }
183
184 _getUserInformation() {
185 const parent = XdpGtk4.parent_new_gtk(this);
186
187 this._portal.get_user_information(
188 parent,
189 'Allows portal-test to test the Account portal.',
190 Xdp.UserInformationFlags.NONE,
191 null,
192 (portal, result) => {
193 let info = null;
194
195 try {
196 info = this._portal.get_user_information_finish(result);
197 } catch(e) {
198 log(e);
199 return;
200 }
201
202 if (!info) {
203 log('Account cancelled');
204 return;
205 }
206
207 info = info.deepUnpack();
208 this._username.label = info['id'].deepUnpack();
209 this._realname.label = info['name'].deepUnpack();
210
211 const uri = info['uri'] ? info['uri'].deepUnpack() : null;
212 log(uri);
213 if (uri && uri !== '') {
214 try {
215 const [path] = GLib.filename_from_uri(uri);
216 const pixbuf =
217 GdkPixbuf.Pixbuf.new_from_file_at_scale(path, 60, 40, true);
218 this._avatar.set_from_pixbuf(pixbuf);
219 } catch(e) {
220 logError(e);
221 }
222 }
223 }
224 );
225 }
226
227 _inhibitChanged() {
228 let inhibitFlags = 0;
229
230 if (this._inhibitLogout.active)
231 inhibitFlags |= Xdp.InhibitFlags.LOGOUT;
232 if (this._inhibitSwitch.active)
233 inhibitFlags |= Xdp.InhibitFlags.USER_SWITCH;
234 if (this._inhibitSuspend.active)
235 inhibitFlags |= Xdp.InhibitFlags.SUSPEND;
236 if (this._inhibitIdle.active)
237 inhibitFlags |= Xdp.InhibitFlags.IDLE;
238
239 if (this._inhibitFlags === inhibitFlags)
240 return;
241
242 if (this._inhibitCookie) {
243 this._portal.session_uninhibit(this._inhibitCookie);
244 delete this._inhibitCookie;
245 }
246
247 if (inhibitFlags !== 0) {
248 this._inhibitFlags = inhibitFlags;
249
250 const parent = XdpGtk4.parent_new_gtk(this);
251 this._portal.session_inhibit(
252 parent,
253 'Portal Testing',
254 inhibitFlags,
255 null,
256 (portal, result) => {
257 try {
258 this._inhibitCookie = this._portal.session_inhibit_finish(result);
259 } catch(e) {
260 logError(e);
261 }
262 });
263 } else {
264 delete this._inhibitFlags;
265 }
266
267 }
268
269 _notifyMe() {
270 this._ackImage.hide();
271
272 const notification = new GLib.Variant('a{sv}', {
273 'title': new GLib.Variant('s', 'Notify me'),
274 'body': new GLib.Variant('s', 'Really important information would ordinarily appear here'),
275 'buttons': new GLib.Variant('aa{sv}', [{
276 'label': new GLib.Variant('s', 'Yup'),
277 'action': new GLib.Variant('s', 'app.ack'),
278 }]),
279 });
280
281 this._portal.add_notification(
282 'notification',
283 notification,
284 Xdp.NotificationFlags.NONE,
285 null, (portal, result) => {
286 try {
287 this._portal.add_notification_finish(result);
288 } catch(e) {
289 logError(e);
290 }
291 });
292 }
293
294 _openLocal() {
295 let flags = Xdp.OpenUriFlags.NONE;
296
297 if (this._openLocalAsk.active)
298 flags |= Xdp.OpenUriFlags.ASK;
299
300 const filename = GLib.build_filenamev([GLib.get_user_data_dir(), 'test.txt']);
301 const file = Gio.File.new_for_path(filename);
302 const uri = file.get_uri();
303
304 log(`Opening ${uri}`);
305
306 const openDir = this._openLocalDir.active;
307 const parent = XdpGtk4.parent_new_gtk(this);
308
309 const callback = (portal, result) => {
310 try {
311 if (openDir)
312 this._portal.open_directory_finish(result);
313 else
314 this._portal.open_uri_finish(result);
315 } catch(e) {
316 logError(e);
317 }
318
319 };
320 if (openDir)
321 this._portal.open_directory(parent, uri, flags, null, callback);
322 else
323 this._portal.open_uri(parent, uri, flags, null, callback);
324 }
325
326 _playClicked() {
327 const pipeline = new Gst.Pipeline({ name: 'note' });
328
329 const source = Gst.ElementFactory.make('audiotestsrc', 'source');
330 const sink = Gst.ElementFactory.make('autoaudiosink', 'output');
331
332 source.freq = 440.0;
333
334 pipeline.add(source);
335 pipeline.add(sink);
336
337 source.link(sink);
338
339 const bus = pipeline.get_bus();
340 bus.add_watch(GLib.PRIORITY_DEFAULT, (bus, message) => {
341 log(`message ${message.type}`);
342
343 if (message.type === Gst.MessageType.STATE_CHANGED) {
344 const [change, state, pending] = pipeline.get_state(Gst.MSECOND);
345
346 if (change === Gst.StateChangeReturn.SUCCESS)
347 log(`Pipeline state now ${state}`);
348 else if (change === Gst.StateChangeReturn.ASYNC)
349 log(`Pipeline state now ${state}, pending ${pending}`);
350 else
351 log(`Pipeline state change failed, now ${state}`);
352
353 if (state === Gst.State.PLAYING) {
354 GLib.timeout_add(GLib.PRIORITY_DEFAULT, 500, () => {
355 pipeline.set_state(Gst.State.NULL);
356 return GLib.SOURCE_REMOVE;
357 })
358 }
359
360 } else if (message.type === Gst.MessageType.ERROR) {
361 pipeline.set_state(Gst.State.NULL);
362 const [error, string] = Gst.Message.parse_error(message);
363 log(error.message);
364 return GLib.SOURCE_REMOVE;
365 }
366
367 return GLib.SOURCE_CONTINUE;
368 });
369
370 log('Set pipeline state to playing');
371 pipeline.set_state(Gst.State.PLAYING);
372 }
373
374 _printCb() {
375 const printData = {
376 text: 'Test',
377 font: 'Sans 12',
378 layout: null,
379 pageBreaks: [],
380 };
381
382 const print = new Gtk.PrintOperation();
383 print.connect('begin-print', (operation, context) => {
384 const width = context.get_width();
385 const height = context.get_height();
386
387 printData.layout = context.create_pango_layout();
388
389 const desc = Pango.FontDescription.from_string(printData.font);
390 printData.layout.set_font_description(desc);
391 printData.layout.set_width(width * Pango.SCALE);
392 printData.layout.set_text(printData.text, -1);
393
394 const nLines = printData.layout.get_line_count();
395
396 let pageHeight = 0;
397 for (let line = 0; line < nLines; line++) {
398 const layoutLine = printData.layout.get_line(line);
399 const [inkRect, logicalRect] = layoutLine.get_extents();
400 const lineHeight = logicalRect.height / 1024.0;
401
402 if (pageHeight + lineHeight > 0) {
403 printData.pageBreaks.push(line);
404 pageHeight = 0;
405 }
406
407 pageHeight += lineHeight;
408 }
409
410 printData.pageBreaks.reverse();
411 print.set_n_pages(printData.pageBreaks.length + 1);
412 });
413 print.connect('draw-page', (operation, context, pageNumber) => {
414 let start = 0;
415 if (pageNumber > 0)
416 start = printData.pageBreaks[pageNumber - 1];
417
418 let end;
419 if (printData.pageBreaks[pageNumber])
420 end = printData.layout.get_line_count();
421 else
422 end = printData.pageBreaks[pageNumber];
423
424 const cr = context.get_cairo_context();
425 cr.setSourceRGB(0, 0, 0);
426
427 const iter = printData.layout.get_iter();
428 let i = 0;
429
430 do {
431 if (i >= start) {
432 const baseline = iter.get_baseline();
433 const [, logicalRect] = iter.get_line_extents();
434
435 let startPos = 0;
436 if (i === start)
437 startPos = logicalRect.y / 1024.0;
438
439 cr.moveTo(logicalRect.x / 1024.0, baseline / 1024.0 - startPos);
440
441 const line = iter.get_line();
442 PangoCairo.show_layout_line(cr, line);
443 }
444
445 i++;
446 } while (i < end && iter.next_line());
447 });
448 print.connect('done', () => {
449 });
450
451 print.run(Gtk.PrintOperationAction.PRINT_DIALOG, this);
452 }
453
454 _requestBackground() {
455 const parent = XdpGtk4.parent_new_gtk(this);
456 this._portal.request_background(
457 parent,
458 'Test reason',
459 ['/bin/true'],
460 Xdp.BackgroundFlags.AUTOSTART,
461 null,
462 (portal, result) => {
463 try {
464 this._portal.request_background_finish(result);
465 } catch(e) {
466 logError(e);
467 }
468 });
469 }
470
471 _setBackgroundStatus() {
472 this._app.mark_busy();
473 this.hide();
474
475 this._portal.set_background_status(
476 'Updating 3 out of 5 files',
477 null,
478 (portal, result) => {
479 try {
480 this._portal.set_background_status_finish(result);
481
482 GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 20, () => {
483 this.show();
484 this._app.unmark_busy();
485
486 this._portal.set_background_status(null, null, (portal, result) => {
487 try {
488 this._portal.set_background_status_finish(result);
489 } catch(e) {
490 logError(e);
491 }
492 });
493
494 return GLib.SOURCE_REMOVE;
495 });
496
497 } catch(e) {
498 logError(e);
499 this.show();
500 this._app.unmark_busy();
501 }
502 });
503 }
504
505 _saveDialog() {
506 const dialog = Gtk.FileChooserNative.new(
507 'File Chooser Portal',
508 this.get_native(),
509 Gtk.FileChooserAction.SAVE,
510 'Save', 'Cancel');
511
512 const encodingOptions = [
513 'current',
514 'iso8859-15',
515 'utf-16',
516 ];
517 const encodingLabels = [
518 'Current Locale (UTF-8)',
519 'Western (ISO-8859-15)',
520 'Unicode (UTF-16)',
521 ];
522
523 dialog.add_choice('encoding', 'Character Encoding', encodingOptions,
524 encodingLabels);
525 dialog.set_choice('encoding', 'current');
526
527 dialog.add_choice('canonicalize', 'Canonicalize', null, null);
528 dialog.set_choice('canonicalize', 'true');
529
530 dialog.connect('response', (dialog, response) => {
531 if (response === Gtk.ResponseType.ACCEPT) {
532 const path = dialog.get_file().get_path();
533 const method = this._saveHow.activeId;
534 let result = false;
535
536 log(method);
537 if (method === 'atomically') {
538 try {
539 result = GLib.file_set_contents(path, 'test');
540 } catch(e) {
541 logError(e);
542 }
543 } else if (method === 'gio') {
544 const file = Gio.File.new_for_path(path);
545
546 try {
547 const stream = file.create(Gio.FileCreateFlags.NONE, null);
548 stream.write('test', null);
549 stream.close(null);
550 result = true;
551 } catch(e) {
552 logError(e);
553 }
554 } else {
555 log('Not writing');
556 }
557
558 if (!result)
559 log('Failed to write');
560 }
561
562 const encoding = dialog.get_choice('encoding');
563 const canonicalize = dialog.get_choice('canonicalize') === 'true';
564 this._encoding.label =
565 `${encodingLabels[encodingOptions.indexOf(encoding)]}${canonicalize ? '(canon) ' : ''}`;
566 });
567 dialog.show();
568 }
569
570 _screencastToggled() {
571 if (this._screencastToggle.active) {
572 delete this._session;
573
574 // Create screencast session
575 this._portal.create_screencast_session(
576 Xdp.OutputType.WINDOW | Xdp.OutputType.MONITOR,
577 Xdp.ScreencastFlags.NONE,
578 Xdp.CursorMode.HIDDEN,
579 Xdp.PersistMode.TRANSIENT,
580 this._restoreToken,
581 null,
582 (portal, result) => {
583 try {
584 this._session = this._portal.create_screencast_session_finish(result);
585 } catch (e) {
586 logError(e);
587 return;
588 }
589
590 // Start screencast
591 const parent = XdpGtk4.parent_new_gtk(this);
592 this._session.start(parent, null, (session, startResult) => {
593 try {
594 this._session.start_finish(startResult);
595 } catch (e) {
596 logError(e);
597
598 delete this._session;
599 this._screencastToggle.active = false;
600 this._screencastLabel.label = '';
601 return;
602 }
603
604 let label = '';
605 const streams =this._session.get_streams().deepUnpack();
606 for (const [streamId, streamData] of streams) {
607 let x = 0, y = 0;
608 if (streamData['position'])
609 [x, y] = streamData['position'].deepUnpack();
610
611 let w = 0, h = 0;
612 if (streamData['size'])
613 [w, h] = streamData['size'].deepUnpack();
614
615 if (label !== '')
616 label += '\n';
617
618 label += `Stream ${streamId}: ${w}x${h} @ ${x},${y}`;
619 }
620
621 this._restoreToken = session.get_restore_token();
622 if (this._restoreToken)
623 label += `\nRestore token: ${this._restoreToken}`;
624
625 this._screencastLabel.label = label;
626 });
627 });
628 } else if (this._session) {
629 this._session.close();
630 delete this._session;
631 this._screencastLabel.label = '';
632 }
633 }
634
635 _setWallpaper() {
636 const parent = XdpGtk4.parent_new_gtk(this);
637 this._portal.set_wallpaper(
638 parent,
639 'file:///usr/share/backgrounds/gnome/adwaita-morning.png',
640 Xdp.WallpaperFlags.BACKGROUND | Xdp.WallpaperFlags.PREVIEW,
641 null,
642 (portal, result) => {
643 try {
644 this._portal.set_wallpaper_finish(result);
645 } catch(e) {
646 logError(e);
647 }
648 });
649 }
650
651 _takeScreenshot() {
652 let flags = Xdp.ScreenshotFlags.NONE;
653
654 if (this._interactive.active)
655 flags |= Xdp.ScreenshotFlags.INTERACTIVE;
656
657 const parent = XdpGtk4.parent_new_gtk(this);
658 this._portal.take_screenshot(
659 parent,
660 flags,
661 null,
662 (portal, result) => {
663 let path = null;
664
665 try {
666 const uri = this._portal.take_screenshot_finish(result);
667 const [path] = GLib.filename_from_uri(uri);
668 const pixbuf =
669 GdkPixbuf.Pixbuf.new_from_file_at_scale(path, 60, 40, true);
670 this._image.set_from_pixbuf(pixbuf);
671 } catch(e) {
672 logError(e);
673 return;
674 }
675
676 });
677 }
678 });