An open-source cross-platform alternative to AirDrop
feat(linux): add software rendering toggle with automatic fallback after a rendering crash (#3731)
Tien Nam Dob1b9abc7201b
diff --git a/app/assets/i18n/en.json b/app/assets/i18n/en.jsonindex 2b762dde..06e521b4 100644--- a/app/assets/i18n/en.json+++ b/app/assets/i18n/en.json@@ -112,6 +112,8 @@"launchAtStartup": "Autostart after login","launchMinimized": "Autostart: Start hidden","showInContextMenu": "Show LocalSend in context menu",+ "softwareRendering": "Software rendering",+ "softwareRenderingDescription": "Use if the window stays blank, glitches or closes on start. Takes effect after a restart.","animations": "Animations"},"receive": {diff --git a/app/lib/config/init.dart b/app/lib/config/init.dartindex 188f6b49..1b6a3ed5 100644--- a/app/lib/config/init.dart+++ b/app/lib/config/init.dart@@ -1,5 +1,4 @@import 'dart:async';-import 'dart:io';import 'package:dart_mappable/dart_mappable.dart';import 'package:flutter/foundation.dart';@@ -33,6 +32,7 @@ import 'package:localsend_app/util/native/channel/android_channel.dart';import 'package:localsend_app/util/native/context_menu_helper.dart';import 'package:localsend_app/util/native/cross_file_converters.dart';import 'package:localsend_app/util/native/device_info_helper.dart';+import 'package:localsend_app/util/native/exit_helper.dart';import 'package:localsend_app/util/native/macos_channel.dart';import 'package:localsend_app/util/native/platform_check.dart';import 'package:localsend_app/util/native/tray_helper.dart';@@ -116,7 +116,7 @@ Future<RefenaContainer> preInit(List<String> args) async {args: args,);if (handedOver) {- exit(0); // Another instance does exist+ await exitApp(); // Another instance does exist}// initialize tray AFTER i18n has been initializeddiff --git a/app/lib/gen/strings.g.dart b/app/lib/gen/strings.g.dartindex 11373769..cdff43de 100644--- a/app/lib/gen/strings.g.dart+++ b/app/lib/gen/strings.g.dart@@ -4,7 +4,7 @@/// To regenerate, run: `dart run slang`////// Locales: 59-/// Strings: 21374 (362 per locale)+/// Strings: 21376 (362 per locale)// coverage:ignore-file// ignore_for_file: type=lint, unused_importdiff --git a/app/lib/gen/strings_en.g.dart b/app/lib/gen/strings_en.g.dartindex 364052b9..efecd412 100644--- a/app/lib/gen/strings_en.g.dart+++ b/app/lib/gen/strings_en.g.dart@@ -1101,6 +1101,12 @@ class Translations$settingsTab$general$en {/// en: 'Show LocalSend in context menu'String get showInContextMenu => 'Show LocalSend in context menu';+ /// en: 'Software rendering'+ String get softwareRendering => 'Software rendering';++ /// en: 'Use if the window stays blank, glitches or closes on start. Takes effect after a restart.'+ String get softwareRenderingDescription => 'Use if the window stays blank, glitches or closes on start. Takes effect after a restart.';+/// en: 'Animations'String get animations => 'Animations';}diff --git a/app/lib/pages/tabs/settings_tab.dart b/app/lib/pages/tabs/settings_tab.dartindex dd16c516..d511b7f8 100644--- a/app/lib/pages/tabs/settings_tab.dart+++ b/app/lib/pages/tabs/settings_tab.dart@@ -147,6 +147,14 @@ class SettingsTab extends StatelessWidget {onChanged: (_) => vm.onToggleShowInContextMenu(context),),],+ if (vm.advanced && checkPlatform([TargetPlatform.linux])) ...[+ _BooleanEntry(+ label: t.settingsTab.general.softwareRendering,+ description: t.settingsTab.general.softwareRenderingDescription,+ value: vm.softwareRendering,+ onChanged: (_) => vm.onToggleSoftwareRendering(context),+ ),+ ],],_BooleanEntry(label: t.settingsTab.general.animations,diff --git a/app/lib/pages/tabs/settings_tab_controller.dart b/app/lib/pages/tabs/settings_tab_controller.dartindex 3e36f242..70987586 100644--- a/app/lib/pages/tabs/settings_tab_controller.dart+++ b/app/lib/pages/tabs/settings_tab_controller.dart@@ -9,6 +9,7 @@ import 'package:localsend_app/provider/network/server/server_provider.dart';import 'package:localsend_app/provider/settings_provider.dart';import 'package:localsend_app/util/native/autostart_helper.dart';import 'package:localsend_app/util/native/context_menu_helper.dart';+import 'package:localsend_app/util/native/software_rendering_helper.dart';import 'package:localsend_app/util/ui/dynamic_colors.dart';import 'package:localsend_app/util/ui/snackbar.dart';import 'package:localsend_app/widget/dialogs/custom_color_dialog.dart';@@ -74,6 +75,7 @@ class SettingsTabController extends ReduxNotifier<SettingsTabVm> {autoStart: false,autoStartLaunchHidden: false,showInContextMenu: false,+ softwareRendering: false,onChangeTheme: (context, theme) async {await _settingsService.setTheme(theme);await sleepAsync(500); // workaround: brightness takes some time to be updated@@ -132,6 +134,12 @@ class SettingsTabController extends ReduxNotifier<SettingsTabVm> {redux.dispatch(_SetShowInContextMenuAction(!state.showInContextMenu));}},+ onToggleSoftwareRendering: (context) async {+ final enabled = !state.softwareRendering;+ if (await setSoftwareRenderingEnabled(enabled)) {+ redux.dispatch(_SetSoftwareRenderingAction(enabled));+ }+ },onTapRestartServer: (context) async {try {final newServerState = await _serverService.restartServer(@@ -188,10 +196,12 @@ class _SettingsTabInitAction extends AsyncReduxAction<SettingsTabController, Setfinal autoStartEnabled = await isAutoStartEnabled();final autoStartHidden = await isAutoStartHidden();final showInContextMenu = await isContextMenuEnabled();+ final softwareRendering = await isSoftwareRenderingEnabled();return state.copyWith(autoStart: autoStartEnabled,autoStartLaunchHidden: autoStartHidden,showInContextMenu: showInContextMenu,+ softwareRendering: softwareRendering,);}}@@ -250,3 +260,14 @@ class _SetShowInContextMenuAction extends ReduxAction<SettingsTabController, Setreturn state.copyWith(showInContextMenu: enabled);}}++class _SetSoftwareRenderingAction extends ReduxAction<SettingsTabController, SettingsTabVm> {+ final bool enabled;++ _SetSoftwareRenderingAction(this.enabled);++ @override+ SettingsTabVm reduce() {+ return state.copyWith(softwareRendering: enabled);+ }+}diff --git a/app/lib/pages/tabs/settings_tab_vm.dart b/app/lib/pages/tabs/settings_tab_vm.dartindex 1ee73525..345886e9 100644--- a/app/lib/pages/tabs/settings_tab_vm.dart+++ b/app/lib/pages/tabs/settings_tab_vm.dart@@ -24,12 +24,14 @@ class SettingsTabVm with SettingsTabVmMappable {final bool autoStart;final bool autoStartLaunchHidden;final bool showInContextMenu;+ final bool softwareRendering;final void Function(BuildContext context, ThemeMode mode) onChangeTheme;final void Function(BuildContext context, ColorMode mode) onChangeColorMode;final void Function(BuildContext context) onTapLanguage;final void Function(BuildContext context) onToggleAutoStart;final void Function(BuildContext context) onToggleAutoStartLaunchHidden;final void Function(BuildContext context) onToggleShowInContextMenu;+ final void Function(BuildContext context) onToggleSoftwareRendering;final void Function(BuildContext context) onTapRestartServer;final void Function(BuildContext context) onTapStartServer;final void Function() onTapStopServer;@@ -49,12 +51,14 @@ class SettingsTabVm with SettingsTabVmMappable {required this.autoStart,required this.autoStartLaunchHidden,required this.showInContextMenu,+ required this.softwareRendering,required this.onChangeTheme,required this.onChangeColorMode,required this.onTapLanguage,required this.onToggleAutoStart,required this.onToggleAutoStartLaunchHidden,required this.onToggleShowInContextMenu,+ required this.onToggleSoftwareRendering,required this.onTapRestartServer,required this.onTapStartServer,required this.onTapStopServer,diff --git a/app/lib/pages/tabs/settings_tab_vm.mapper.dart b/app/lib/pages/tabs/settings_tab_vm.mapper.dartindex f156522a..96e710a9 100644--- a/app/lib/pages/tabs/settings_tab_vm.mapper.dart+++ b/app/lib/pages/tabs/settings_tab_vm.mapper.dart@@ -88,6 +88,11 @@ class SettingsTabVmMapper extends ClassMapperBase<SettingsTabVm> {'showInContextMenu',_$showInContextMenu,);+ static bool _$softwareRendering(SettingsTabVm v) => v.softwareRendering;+ static const Field<SettingsTabVm, bool> _f$softwareRendering = Field(+ 'softwareRendering',+ _$softwareRendering,+ );static Function _$onChangeTheme(SettingsTabVm v) =>(v as dynamic).onChangeTheme as Function;static dynamic _arg$onChangeTheme(f) =>@@ -142,6 +147,16 @@ class SettingsTabVmMapper extends ClassMapperBase<SettingsTabVm> {_$onToggleShowInContextMenu,arg: _arg$onToggleShowInContextMenu,);+ static Function _$onToggleSoftwareRendering(SettingsTabVm v) =>+ (v as dynamic).onToggleSoftwareRendering as Function;+ static dynamic _arg$onToggleSoftwareRendering(f) =>+ f<void Function(BuildContext)>();+ static const Field<SettingsTabVm, Function> _f$onToggleSoftwareRendering =+ Field(+ 'onToggleSoftwareRendering',+ _$onToggleSoftwareRendering,+ arg: _arg$onToggleSoftwareRendering,+ );static Function _$onTapRestartServer(SettingsTabVm v) =>(v as dynamic).onTapRestartServer as Function;static dynamic _arg$onTapRestartServer(f) => f<void Function(BuildContext)>();@@ -196,12 +211,14 @@ class SettingsTabVmMapper extends ClassMapperBase<SettingsTabVm> {#autoStart: _f$autoStart,#autoStartLaunchHidden: _f$autoStartLaunchHidden,#showInContextMenu: _f$showInContextMenu,+ #softwareRendering: _f$softwareRendering,#onChangeTheme: _f$onChangeTheme,#onChangeColorMode: _f$onChangeColorMode,#onTapLanguage: _f$onTapLanguage,#onToggleAutoStart: _f$onToggleAutoStart,#onToggleAutoStartLaunchHidden: _f$onToggleAutoStartLaunchHidden,#onToggleShowInContextMenu: _f$onToggleShowInContextMenu,+ #onToggleSoftwareRendering: _f$onToggleSoftwareRendering,#onTapRestartServer: _f$onTapRestartServer,#onTapStartServer: _f$onTapStartServer,#onTapStopServer: _f$onTapStopServer,@@ -224,12 +241,14 @@ class SettingsTabVmMapper extends ClassMapperBase<SettingsTabVm> {autoStart: data.dec(_f$autoStart),autoStartLaunchHidden: data.dec(_f$autoStartLaunchHidden),showInContextMenu: data.dec(_f$showInContextMenu),+ softwareRendering: data.dec(_f$softwareRendering),onChangeTheme: data.dec(_f$onChangeTheme),onChangeColorMode: data.dec(_f$onChangeColorMode),onTapLanguage: data.dec(_f$onTapLanguage),onToggleAutoStart: data.dec(_f$onToggleAutoStart),onToggleAutoStartLaunchHidden: data.dec(_f$onToggleAutoStartLaunchHidden),onToggleShowInContextMenu: data.dec(_f$onToggleShowInContextMenu),+ onToggleSoftwareRendering: data.dec(_f$onToggleSoftwareRendering),onTapRestartServer: data.dec(_f$onTapRestartServer),onTapStartServer: data.dec(_f$onTapStartServer),onTapStopServer: data.dec(_f$onTapStopServer),@@ -317,12 +336,14 @@ abstract class SettingsTabVmCopyWith<$R, $In extends SettingsTabVm, $Out>bool? autoStart,bool? autoStartLaunchHidden,bool? showInContextMenu,+ bool? softwareRendering,void Function(BuildContext, ThemeMode)? onChangeTheme,void Function(BuildContext, ColorMode)? onChangeColorMode,void Function(BuildContext)? onTapLanguage,void Function(BuildContext)? onToggleAutoStart,void Function(BuildContext)? onToggleAutoStartLaunchHidden,void Function(BuildContext)? onToggleShowInContextMenu,+ void Function(BuildContext)? onToggleSoftwareRendering,void Function(BuildContext)? onTapRestartServer,void Function(BuildContext)? onTapStartServer,void Function()? onTapStopServer,@@ -367,12 +388,14 @@ class _SettingsTabVmCopyWithImpl<$R, $Out>bool? autoStart,bool? autoStartLaunchHidden,bool? showInContextMenu,+ bool? softwareRendering,void Function(BuildContext, ThemeMode)? onChangeTheme,void Function(BuildContext, ColorMode)? onChangeColorMode,void Function(BuildContext)? onTapLanguage,void Function(BuildContext)? onToggleAutoStart,void Function(BuildContext)? onToggleAutoStartLaunchHidden,void Function(BuildContext)? onToggleShowInContextMenu,+ void Function(BuildContext)? onToggleSoftwareRendering,void Function(BuildContext)? onTapRestartServer,void Function(BuildContext)? onTapStartServer,void Function()? onTapStopServer,@@ -395,6 +418,7 @@ class _SettingsTabVmCopyWithImpl<$R, $Out>if (autoStartLaunchHidden != null)#autoStartLaunchHidden: autoStartLaunchHidden,if (showInContextMenu != null) #showInContextMenu: showInContextMenu,+ if (softwareRendering != null) #softwareRendering: softwareRendering,if (onChangeTheme != null) #onChangeTheme: onChangeTheme,if (onChangeColorMode != null) #onChangeColorMode: onChangeColorMode,if (onTapLanguage != null) #onTapLanguage: onTapLanguage,@@ -403,6 +427,8 @@ class _SettingsTabVmCopyWithImpl<$R, $Out>#onToggleAutoStartLaunchHidden: onToggleAutoStartLaunchHidden,if (onToggleShowInContextMenu != null)#onToggleShowInContextMenu: onToggleShowInContextMenu,+ if (onToggleSoftwareRendering != null)+ #onToggleSoftwareRendering: onToggleSoftwareRendering,if (onTapRestartServer != null) #onTapRestartServer: onTapRestartServer,if (onTapStartServer != null) #onTapStartServer: onTapStartServer,if (onTapStopServer != null) #onTapStopServer: onTapStopServer,@@ -439,6 +465,10 @@ class _SettingsTabVmCopyWithImpl<$R, $Out>#showInContextMenu,or: $value.showInContextMenu,),+ softwareRendering: data.get(+ #softwareRendering,+ or: $value.softwareRendering,+ ),onChangeTheme: data.get(#onChangeTheme, or: $value.onChangeTheme),onChangeColorMode: data.get(#onChangeColorMode,@@ -457,6 +487,10 @@ class _SettingsTabVmCopyWithImpl<$R, $Out>#onToggleShowInContextMenu,or: $value.onToggleShowInContextMenu,),+ onToggleSoftwareRendering: data.get(+ #onToggleSoftwareRendering,+ or: $value.onToggleSoftwareRendering,+ ),onTapRestartServer: data.get(#onTapRestartServer,or: $value.onTapRestartServer,diff --git a/app/lib/util/native/exit_helper.dart b/app/lib/util/native/exit_helper.dartnew file mode 100644index 00000000..137e2483--- /dev/null+++ b/app/lib/util/native/exit_helper.dart@@ -0,0 +1,9 @@+import 'dart:io';++import 'package:localsend_app/util/native/software_rendering_helper.dart';++/// Quits the app. Use this instead of [exit] so that platform-specific cleanup runs first.+Future<Never> exitApp() async {+ await releaseRenderCheck();+ exit(0);+}diff --git a/app/lib/util/native/software_rendering_helper.dart b/app/lib/util/native/software_rendering_helper.dartnew file mode 100644index 00000000..fc9902e0--- /dev/null+++ b/app/lib/util/native/software_rendering_helper.dart@@ -0,0 +1,52 @@+import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:logging/logging.dart';++final _logger = Logger('SoftwareRenderingHelper');++/// Implemented in linux/my_application.cc.+const _platformChannel = MethodChannel('org.localsend.localsend_app/platform');++/// Whether the next launch uses Flutter's software renderer (Linux only).+Future<bool> isSoftwareRenderingEnabled() async {+ if (defaultTargetPlatform != TargetPlatform.linux) {+ return false;+ }++ try {+ return await _platformChannel.invokeMethod<bool>('isSoftwareRenderingEnabled') ?? false;+ } catch (e) {+ _logger.warning('Failed to read software rendering setting', e);+ return false;+ }+}++/// Enables or disables software rendering for the next launch (Linux only).+/// Returns true on success.+Future<bool> setSoftwareRenderingEnabled(bool enabled) async {+ if (defaultTargetPlatform != TargetPlatform.linux) {+ return false;+ }++ try {+ return await _platformChannel.invokeMethod<bool>('setSoftwareRenderingEnabled', enabled) ?? false;+ } catch (e) {+ _logger.warning('Failed to write software rendering setting', e);+ return false;+ }+}++/// Tells the runner that the app quits on purpose, otherwise a quit shortly after the start looks like a rendering+/// crash to the next launch, which then falls back to software rendering (Linux only).+/// Needed because `exit` ends the process without running native exit handlers, so the runner can't tell on its own.+Future<void> releaseRenderCheck() async {+ if (defaultTargetPlatform != TargetPlatform.linux) {+ return;+ }++ try {+ await _platformChannel.invokeMethod<void>('releaseRenderCheck');+ } catch (e) {+ _logger.warning('Failed to release render check', e);+ }+}diff --git a/app/lib/widget/watcher/shortcut_watcher.dart b/app/lib/widget/watcher/shortcut_watcher.dartindex 5eb64e72..7d2e7b83 100644--- a/app/lib/widget/watcher/shortcut_watcher.dart+++ b/app/lib/widget/watcher/shortcut_watcher.dart@@ -1,9 +1,8 @@-import 'dart:io';-import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:localsend_app/pages/home_page.dart';import 'package:localsend_app/pages/home_page_controller.dart';+import 'package:localsend_app/util/native/exit_helper.dart';import 'package:localsend_app/util/native/file_picker.dart';import 'package:localsend_app/util/native/platform_check.dart';import 'package:refena_flutter/refena_flutter.dart';@@ -37,7 +36,7 @@ class ShortcutWatcher extends StatelessWidget {},child: Actions(actions: {- _ExitAppIntent: CallbackAction(onInvoke: (_) => exit(0)),+ _ExitAppIntent: CallbackAction(onInvoke: (_) => exitApp()),_PopPageIntent: CallbackAction(onInvoke: (_) async => Navigator.of(Routerino.context).maybePop()),_PasteIntent: CallbackAction(onInvoke: (_) async {diff --git a/app/lib/widget/watcher/tray_watcher.dart b/app/lib/widget/watcher/tray_watcher.dartindex d0982e1d..13d4c0cd 100644--- a/app/lib/widget/watcher/tray_watcher.dart+++ b/app/lib/widget/watcher/tray_watcher.dart@@ -1,7 +1,6 @@-import 'dart:io';-import 'package:collection/collection.dart';import 'package:flutter/material.dart';+import 'package:localsend_app/util/native/exit_helper.dart';import 'package:localsend_app/util/native/platform_check.dart';import 'package:localsend_app/util/native/tray_helper.dart';import 'package:tray_manager/tray_manager.dart';@@ -55,7 +54,7 @@ class _TrayWatcherState extends State<TrayWatcher> with TrayListener {await showFromTray();break;case TrayEntry.close:- exit(0);+ await exitApp();default:}}diff --git a/app/lib/widget/watcher/window_watcher.dart b/app/lib/widget/watcher/window_watcher.dartindex 5615cf17..315ee286 100644--- a/app/lib/widget/watcher/window_watcher.dart+++ b/app/lib/widget/watcher/window_watcher.dart@@ -1,9 +1,9 @@import 'dart:async';-import 'dart:io';import 'package:flutter/material.dart';import 'package:localsend_app/provider/animation_provider.dart';import 'package:localsend_app/provider/settings_provider.dart';import 'package:localsend_app/provider/window_dimensions_provider.dart';+import 'package:localsend_app/util/native/exit_helper.dart';import 'package:localsend_app/util/native/platform_check.dart';import 'package:localsend_app/util/native/tray_helper.dart';import 'package:logging/logging.dart';@@ -102,7 +102,7 @@ class _WindowWatcherState extends State<WindowWatcher> with WindowListener, Refeawait hideToTray();} else {await destroyTray();- exit(0);+ await exitApp();}} catch (e) {_logger.warning('Failed to close window', e);diff --git a/app/linux/my_application.cc b/app/linux/my_application.ccindex 9fb8a3ea..2eb29256 100644--- a/app/linux/my_application.cc+++ b/app/linux/my_application.cc@@ -11,23 +11,248 @@#include "flutter/generated_plugin_registrant.h"+#include <errno.h>+#include <fcntl.h>+#include <glib/gstdio.h>#include <stdlib.h>#include <string.h>+#include <sys/file.h>+#include <sys/stat.h>+#include <unistd.h>struct _MyApplication {GtkApplication parent_instance;char** dart_entrypoint_arguments;+ bool is_wayland;+ // Directory holding the software rendering files, see get_state_dir().+ gchar* state_dir;+ // Path of kRenderCheckFile.+ gchar* render_check_path;+ // Locked file descriptor of the render check while this launch owns it.+ int render_check_fd;};G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)+// Software rendering (https://github.com/localsend/localsend/issues/3233).+//+// The Flutter engine reads FLUTTER_LINUX_RENDERER when it is created, so the+// renderer has to be chosen here, before the FlView exists.+// - kSoftwareRenderingFile: exists while software rendering is enabled.+// Written by the settings toggle and by the crash fallback below.+// - kRenderCheckFile: written before an OpenGL launch and deleted shortly+// after the first frame or when the app quits on purpose (exitApp() in+// exit_helper.dart). If it still exists on the next launch,+// the previous one died before it could render (e.g. "No provider of+// glBlitFramebuffer found" aborts the process), so we switch to software+// rendering. The owning launch holds an flock on it, so a launch that starts+// while another one is still checking (e.g. a double click on the launcher)+// can tell a running check from a crashed one.+static const char kSoftwareRenderingFile[] = "software_rendering";+static const char kRenderCheckFile[] = "render_check";+static const guint kRenderCheckSeconds = 3;++// Returns the directory next to the executable in portable mode (settings.json+// next to the executable, see shared_preferences_portable.dart), otherwise the+// app's data directory (~/.local/share/org.localsend.localsend_app).+static gchar* get_state_dir() {+ g_autofree gchar* exe = g_file_read_link("/proc/self/exe", nullptr);+ if (exe != nullptr) {+ gchar* exe_dir = g_path_get_dirname(exe);+ g_autofree gchar* portable_settings =+ g_build_filename(exe_dir, "settings.json", nullptr);+ if (g_file_test(portable_settings, G_FILE_TEST_EXISTS)) {+ return exe_dir;+ }+ g_free(exe_dir);+ }+ return g_build_filename(g_get_user_data_dir(), APPLICATION_ID, nullptr);+}++static bool state_file_exists(MyApplication* self, const char* name) {+ g_autofree gchar* path = g_build_filename(self->state_dir, name, nullptr);+ return g_file_test(path, G_FILE_TEST_EXISTS);+}++static bool write_state_file(MyApplication* self, const char* name) {+ g_autoptr(GError) error = nullptr;+ if (g_mkdir_with_parents(self->state_dir, 0700) != 0) {+ g_warning("Failed to create %s", self->state_dir);+ return false;+ }+ g_autofree gchar* path = g_build_filename(self->state_dir, name, nullptr);+ if (!g_file_set_contents(path, "", 0, &error)) {+ g_warning("Failed to write %s: %s", path, error->message);+ return false;+ }+ return true;+}++static bool delete_state_file(MyApplication* self, const char* name) {+ g_autofree gchar* path = g_build_filename(self->state_dir, name, nullptr);+ if (g_unlink(path) != 0 && errno != ENOENT) {+ g_warning("Failed to delete %s: %s", path, g_strerror(errno));+ return false;+ }+ return true;+}++static bool software_rendering_requested() {+ return g_strcmp0(g_getenv("FLUTTER_LINUX_RENDERER"), "software") == 0;+}++// Whether fd is still the file at path (and not deleted or replaced).+static bool fd_matches_path(int fd, const char* path) {+ struct stat fd_stat, path_stat;+ return fstat(fd, &fd_stat) == 0 && stat(path, &path_stat) == 0 &&+ fd_stat.st_dev == path_stat.st_dev &&+ fd_stat.st_ino == path_stat.st_ino;+}++enum class RenderCheck { kNone, kRunning, kCrashed };++// Inspects the render check left by another launch.+static RenderCheck read_render_check(MyApplication* self) {+ int fd = open(self->render_check_path, O_RDONLY | O_CLOEXEC);+ if (fd < 0) {+ return RenderCheck::kNone;+ }+ RenderCheck result;+ if (flock(fd, LOCK_EX | LOCK_NB) != 0) {+ // Its launch is still running and holds the lock.+ result = RenderCheck::kRunning;+ } else if (!fd_matches_path(fd, self->render_check_path)) {+ // Its launch passed the check and deleted it in the meantime.+ result = RenderCheck::kNone;+ } else {+ // Nobody holds the lock anymore: its launch died during the check.+ result = RenderCheck::kCrashed;+ }+ close(fd);+ return result;+}++// Deletes the render check if this launch owns it.+static void release_render_check(MyApplication* self) {+ int fd = self->render_check_fd;+ if (fd < 0) {+ return;+ }+ self->render_check_fd = -1;+ if (fd_matches_path(fd, self->render_check_path)) {+ unlink(self->render_check_path);+ }+ close(fd);+}++static bool arm_render_check(MyApplication* self) {+ if (g_mkdir_with_parents(self->state_dir, 0700) != 0) {+ g_warning("Failed to create %s", self->state_dir);+ return false;+ }++ // Lock a temporary file and move it into place, so other launches never see+ // an unlocked check.+ g_autofree gchar* tmp_path =+ g_strdup_printf("%s.%d", self->render_check_path, (int)getpid());+ int fd = open(tmp_path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);+ if (fd < 0) {+ g_warning("Failed to write %s: %s", tmp_path, g_strerror(errno));+ return false;+ }+ if (flock(fd, LOCK_EX | LOCK_NB) != 0 ||+ rename(tmp_path, self->render_check_path) != 0) {+ g_warning("Failed to arm %s: %s", self->render_check_path,+ g_strerror(errno));+ close(fd);+ unlink(tmp_path);+ return false;+ }++ self->render_check_fd = fd;+ return true;+}++// Decides the renderer for this launch. Must run before the FlView is created.+// Returns true if the render check was armed.+static bool setup_renderer(MyApplication* self, bool start_hidden) {+ if (software_rendering_requested()) {+ // Set by the user, nothing to decide.+ return false;+ }++ if (state_file_exists(self, kSoftwareRenderingFile)) {+ g_setenv("FLUTTER_LINUX_RENDERER", "software", TRUE);+ return false;+ }++ switch (read_render_check(self)) {+ case RenderCheck::kCrashed:+ g_warning(+ "The previous launch exited before rendering its first frame. "+ "Enabling software rendering, it can be disabled in the settings.");+ write_state_file(self, kSoftwareRenderingFile);+ delete_state_file(self, kRenderCheckFile);+ g_setenv("FLUTTER_LINUX_RENDERER", "software", TRUE);+ return false;+ case RenderCheck::kRunning:+ // Another launch is still checking this renderer. This one most likely+ // hands over to it, and only one check fits into the file anyway.+ return false;+ case RenderCheck::kNone:+ break;+ }++ if (start_hidden) {+ // A hidden window may never render, which would look like a crash.+ return false;+ }++ return arm_render_check(self);+}++static gboolean render_check_passed_cb(gpointer user_data) {+ MyApplication* self = MY_APPLICATION(user_data);+ release_render_check(self);+ g_object_unref(self);+ return G_SOURCE_REMOVE;+}++static void first_frame_cb(MyApplication* self, FlView* view) {+ // The first frame is drawn right after this signal, so give the renderer a+ // moment before declaring it working.+ g_timeout_add_seconds(kRenderCheckSeconds, render_check_passed_cb,+ g_object_ref(self));+}+static void platform_method_call_cb(FlMethodChannel* channel,FlMethodCall* method_call,gpointer user_data) {+ MyApplication* self = MY_APPLICATION(user_data);+ const gchar* method = fl_method_call_get_name(method_call);g_autoptr(FlMethodResponse) response = nullptr;- if (strcmp(fl_method_call_get_name(method_call), "isWayland") == 0) {+ if (strcmp(method, "isWayland") == 0) {+ response = FL_METHOD_RESPONSE(+ fl_method_success_response_new(fl_value_new_bool(self->is_wayland)));+ } else if (strcmp(method, "isSoftwareRenderingEnabled") == 0) {response = FL_METHOD_RESPONSE(fl_method_success_response_new(- fl_value_new_bool(GPOINTER_TO_INT(user_data))));+ fl_value_new_bool(state_file_exists(self, kSoftwareRenderingFile))));+ } else if (strcmp(method, "setSoftwareRenderingEnabled") == 0) {+ FlValue* args = fl_method_call_get_args(method_call);+ if (fl_value_get_type(args) != FL_VALUE_TYPE_BOOL) {+ response = FL_METHOD_RESPONSE(fl_method_error_response_new(+ "INVALID_ARGUMENTS", "Expected a bool", nullptr));+ } else {+ bool success = fl_value_get_bool(args)+ ? write_state_file(self, kSoftwareRenderingFile)+ : delete_state_file(self, kSoftwareRenderingFile);+ response = FL_METHOD_RESPONSE(+ fl_method_success_response_new(fl_value_new_bool(success)));+ }+ } else if (strcmp(method, "releaseRenderCheck") == 0) {+ // Called before quitting on purpose, which is not a rendering crash.+ release_render_check(self);+ response = FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr));} else {response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());}@@ -77,20 +302,25 @@ static void my_application_activate(GApplication* application) {g_autoptr(FlDartProject) project = fl_dart_project_new();fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments);+ bool render_check = setup_renderer(self, start_hidden);+FlView* view = fl_view_new(project);+ if (render_check) {+ g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb),+ self);+ }+g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();g_autoptr(FlMethodChannel) platform_channel = fl_method_channel_new(fl_engine_get_binary_messenger(fl_view_get_engine(view)),"org.localsend.localsend_app/platform", FL_METHOD_CODEC(codec));- bool is_wayland = false;#ifdef GDK_WINDOWING_WAYLAND- is_wayland = GDK_IS_WAYLAND_DISPLAY(+ self->is_wayland = GDK_IS_WAYLAND_DISPLAY(gtk_widget_get_display(GTK_WIDGET(window)));#endiffl_method_channel_set_method_call_handler(- platform_channel, platform_method_call_cb, GINT_TO_POINTER(is_wayland),- nullptr);+ platform_channel, platform_method_call_cb, self, nullptr);gtk_widget_show(GTK_WIDGET(view));gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));@@ -125,6 +355,10 @@ static gboolean my_application_local_command_line(GApplication* application, gchstatic void my_application_dispose(GObject* object) {MyApplication* self = MY_APPLICATION(object);g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);+ // Returning from main() is a regular quit.+ release_render_check(self);+ g_clear_pointer(&self->state_dir, g_free);+ g_clear_pointer(&self->render_check_path, g_free);G_OBJECT_CLASS(my_application_parent_class)->dispose(object);}@@ -134,7 +368,12 @@ static void my_application_class_init(MyApplicationClass* klass) {G_OBJECT_CLASS(klass)->dispose = my_application_dispose;}-static void my_application_init(MyApplication* self) {}+static void my_application_init(MyApplication* self) {+ self->state_dir = get_state_dir();+ self->render_check_path =+ g_build_filename(self->state_dir, kRenderCheckFile, nullptr);+ self->render_check_fd = -1;+}MyApplication* my_application_new() {// Set the program name to the application ID, which helps various systems