11using System . Buffers ;
2+ using System . Diagnostics ;
23using System . Runtime . CompilerServices ;
34using System . Runtime . Versioning ;
45using TerraFX . Interop . Windows ;
@@ -73,9 +74,28 @@ public static class OpenFileDialog
7374 {
7475 if ( Gtk . Global . IsSupported )
7576 {
76- string ? result ;
77- GtkHelper . EnsureInitialized ( ) ;
77+ return OpenFileLinuxGtk ( ) ;
78+ }
79+ else
80+ {
81+ // Fallback
82+ return Task . FromResult < string ? > ( null ) ;
83+ }
84+ }
85+
86+ [ SupportedOSPlatform ( "linux" ) ]
87+ private static async Task < string ? > OpenFileLinuxGtk ( )
88+ {
89+ Debug . Assert ( Gtk . Global . IsSupported ) ;
7890
91+ string ? result ;
92+ while ( ! GtkHelper . TryInitialize ( ) )
93+ {
94+ await GtkHelper . Delay ( ) ; // Wait for the GTK initialization to complete
95+ }
96+
97+ try
98+ {
7999 using Gtk . FileChooserNative dlg = new (
80100 "Open a file" , null ,
81101 Gtk . FileChooserAction . Open , "Open" , "Cancel" ) ;
@@ -88,14 +108,13 @@ public static class OpenFileDialog
88108 {
89109 result = null ; // User canceled the dialog
90110 }
91-
92- return Task . FromResult ( result ) ;
93111 }
94- else
112+ finally
95113 {
96- // Fallback
97- return Task . FromResult < string ? > ( null ) ;
114+ GtkHelper . Shutdown ( ) ; // Ensure GTK is properly shut down after use
98115 }
116+
117+ return result ;
99118 }
100119
101120 public static Task < string [ ] ? > OpenFiles ( )
@@ -196,9 +215,28 @@ public static class OpenFileDialog
196215 {
197216 if ( Gtk . Global . IsSupported )
198217 {
199- string [ ] ? result ;
200- GtkHelper . EnsureInitialized ( ) ;
218+ return OpenFilesLinuxGtk ( ) ;
219+ }
220+ else
221+ {
222+ // Fallback
223+ return Task . FromResult < string [ ] ? > ( null ) ;
224+ }
225+ }
226+
227+ [ SupportedOSPlatform ( "linux" ) ]
228+ private static async Task < string [ ] ? > OpenFilesLinuxGtk ( )
229+ {
230+ Debug . Assert ( Gtk . Global . IsSupported ) ;
201231
232+ string [ ] ? result ;
233+ while ( ! GtkHelper . TryInitialize ( ) )
234+ {
235+ await GtkHelper . Delay ( ) ; // Wait for the GTK initialization to complete
236+ }
237+
238+ try
239+ {
202240 using Gtk . FileChooserNative dlg = new (
203241 "Open files" , null ,
204242 Gtk . FileChooserAction . Open , "Open" , "Cancel" ) ;
@@ -213,13 +251,12 @@ public static class OpenFileDialog
213251 {
214252 result = null ; // User canceled the dialog
215253 }
216-
217- return Task . FromResult ( result ) ;
218254 }
219- else
255+ finally
220256 {
221- // Fallback
222- return Task . FromResult < string [ ] ? > ( null ) ;
257+ GtkHelper . Shutdown ( ) ; // Ensure GTK is properly shut down after use
223258 }
259+
260+ return result ;
224261 }
225262}
0 commit comments