1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/gtk/filedlg.cpp
3 // Purpose:     native implementation of wxFileDialog
4 // Author:      Robert Roebling, Zbigniew Zagorski, Mart Raudsepp
5 // Copyright:   (c) 1998 Robert Roebling, 2004 Zbigniew Zagorski, 2005 Mart Raudsepp
6 // Licence:     wxWindows licence
7 /////////////////////////////////////////////////////////////////////////////
8 
9 // For compilers that support precompilation, includes "wx.h".
10 #include "wx/wxprec.h"
11 
12 #if wxUSE_FILEDLG
13 
14 #include "wx/filedlg.h"
15 
16 #ifndef WX_PRECOMP
17     #include "wx/intl.h"
18     #include "wx/log.h"
19     #include "wx/msgdlg.h"
20 #endif
21 
22 #include "wx/gtk/private.h"
23 #include "wx/gtk/private/mnemonics.h"
24 
25 #ifdef __UNIX__
26 #include <unistd.h> // chdir
27 #endif
28 
29 #include "wx/filename.h" // wxFilename
30 #include "wx/tokenzr.h" // wxStringTokenizer
31 #include "wx/filefn.h" // ::wxGetCwd
32 #include "wx/modalhook.h"
33 
34 //-----------------------------------------------------------------------------
35 // "clicked" for OK-button
36 //-----------------------------------------------------------------------------
37 
38 extern "C" {
gtk_filedialog_ok_callback(GtkWidget * widget,wxFileDialog * dialog)39 static void gtk_filedialog_ok_callback(GtkWidget *widget, wxFileDialog *dialog)
40 {
41     int style = dialog->GetWindowStyle();
42     wxGtkString filename(gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(widget)));
43 
44     // gtk version numbers must be identical with the one in ctor (that calls set_do_overwrite_confirmation)
45 #ifndef __WXGTK3__
46 #if GTK_CHECK_VERSION(2,7,3)
47     if (!wx_is_at_least_gtk2(8))
48 #endif
49     {
50         if ((style & wxFD_SAVE) && (style & wxFD_OVERWRITE_PROMPT))
51         {
52             if ( g_file_test(filename, G_FILE_TEST_EXISTS) )
53             {
54                 wxString msg;
55 
56                 msg.Printf(
57                     _("File '%s' already exists, do you really want to overwrite it?"),
58                     wxString::FromUTF8(filename));
59 
60                 wxMessageDialog dlg(dialog, msg, _("Confirm"),
61                                    wxYES_NO | wxICON_QUESTION);
62                 if (dlg.ShowModal() != wxID_YES)
63                     return;
64             }
65         }
66     }
67 #endif
68 
69     if (style & wxFD_FILE_MUST_EXIST)
70     {
71         if ( !g_file_test(filename, G_FILE_TEST_EXISTS) )
72         {
73             wxMessageDialog dlg( dialog, _("Please choose an existing file."),
74                                  _("Error"), wxOK| wxICON_ERROR);
75             dlg.ShowModal();
76             return;
77         }
78     }
79 
80     // change to the directory where the user went if asked
81     if (style & wxFD_CHANGE_DIR)
82     {
83         // Use chdir to not care about filename encodings
84         wxGtkString folder(g_path_get_dirname(filename));
85         if ( chdir(folder) != 0 )
86         {
87             wxLogSysError(_("Changing current directory to \"%s\" failed"),
88                           wxString::FromUTF8(folder));
89         }
90     }
91 
92     wxCommandEvent event(wxEVT_BUTTON, wxID_OK);
93     event.SetEventObject(dialog);
94     dialog->HandleWindowEvent(event);
95 }
96 }
97 
98 //-----------------------------------------------------------------------------
99 // "clicked" for Cancel-button
100 //-----------------------------------------------------------------------------
101 
102 extern "C"
103 {
104 
105 static void
gtk_filedialog_cancel_callback(GtkWidget * WXUNUSED (w),wxFileDialog * dialog)106 gtk_filedialog_cancel_callback(GtkWidget * WXUNUSED(w), wxFileDialog *dialog)
107 {
108     wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, wxID_CANCEL);
109     event.SetEventObject(dialog);
110     dialog->HandleWindowEvent(event);
111 }
112 
gtk_filedialog_response_callback(GtkWidget * w,gint response,wxFileDialog * dialog)113 static void gtk_filedialog_response_callback(GtkWidget *w,
114                                              gint response,
115                                              wxFileDialog *dialog)
116 {
117     if (response == GTK_RESPONSE_ACCEPT)
118         gtk_filedialog_ok_callback(w, dialog);
119     else    // GTK_RESPONSE_CANCEL or GTK_RESPONSE_NONE
120         gtk_filedialog_cancel_callback(w, dialog);
121 }
122 
gtk_filedialog_selchanged_callback(GtkFileChooser * chooser,wxFileDialog * dialog)123 static void gtk_filedialog_selchanged_callback(GtkFileChooser *chooser,
124                                                wxFileDialog *dialog)
125 {
126     wxGtkString filename(gtk_file_chooser_get_preview_filename(chooser));
127 
128     dialog->GTKSelectionChanged(wxString::FromUTF8(filename));
129 }
130 
131 
gtk_filedialog_update_preview_callback(GtkFileChooser * chooser,gpointer user_data)132 static void gtk_filedialog_update_preview_callback(GtkFileChooser *chooser,
133                                                    gpointer user_data)
134 {
135     GtkWidget *preview = GTK_WIDGET(user_data);
136 
137     wxGtkString filename(gtk_file_chooser_get_preview_filename(chooser));
138 
139     if ( !filename )
140         return;
141 
142     GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file_at_size(filename, 128, 128, NULL);
143     gboolean have_preview = pixbuf != NULL;
144 
145     gtk_image_set_from_pixbuf(GTK_IMAGE(preview), pixbuf);
146     if ( pixbuf )
147         g_object_unref (pixbuf);
148 
149     gtk_file_chooser_set_preview_widget_active(chooser, have_preview);
150 }
151 
152 } // extern "C"
153 
AddChildGTK(wxWindowGTK * child)154 void wxFileDialog::AddChildGTK(wxWindowGTK* child)
155 {
156     // allow dialog to be resized smaller horizontally
157     gtk_widget_set_size_request(
158         child->m_widget, child->GetMinWidth(), child->m_height);
159 
160     gtk_file_chooser_set_extra_widget(
161         GTK_FILE_CHOOSER(m_widget), child->m_widget);
162 }
163 
164 //-----------------------------------------------------------------------------
165 // wxFileDialog
166 //-----------------------------------------------------------------------------
167 
168 wxIMPLEMENT_DYNAMIC_CLASS(wxFileDialog, wxFileDialogBase);
169 
wxBEGIN_EVENT_TABLE(wxFileDialog,wxFileDialogBase)170 wxBEGIN_EVENT_TABLE(wxFileDialog,wxFileDialogBase)
171     EVT_BUTTON(wxID_OK, wxFileDialog::OnFakeOk)
172     EVT_SIZE(wxFileDialog::OnSize)
173 wxEND_EVENT_TABLE()
174 
175 wxFileDialog::wxFileDialog(wxWindow *parent, const wxString& message,
176                            const wxString& defaultDir,
177                            const wxString& defaultFileName,
178                            const wxString& wildCard,
179                            long style, const wxPoint& pos,
180                            const wxSize& sz,
181                            const wxString& name)
182     : wxFileDialogBase()
183 {
184     Create(parent, message, defaultDir, defaultFileName, wildCard, style, pos, sz, name);
185 }
186 
Create(wxWindow * parent,const wxString & message,const wxString & defaultDir,const wxString & defaultFileName,const wxString & wildCard,long style,const wxPoint & pos,const wxSize & sz,const wxString & name)187 bool wxFileDialog::Create(wxWindow *parent, const wxString& message,
188                            const wxString& defaultDir,
189                            const wxString& defaultFileName,
190                            const wxString& wildCard,
191                            long style, const wxPoint& pos,
192                            const wxSize& sz,
193                            const wxString& name)
194 {
195     parent = GetParentForModalDialog(parent, style);
196 
197     if (!wxFileDialogBase::Create(parent, message, defaultDir, defaultFileName,
198                                   wildCard, style, pos, sz, name))
199     {
200         return false;
201     }
202 
203     if (!PreCreation(parent, pos, wxDefaultSize) ||
204         !CreateBase(parent, wxID_ANY, pos, wxDefaultSize, style,
205                 wxDefaultValidator, wxT("filedialog")))
206     {
207         wxFAIL_MSG( wxT("wxFileDialog creation failed") );
208         return false;
209     }
210 
211     GtkFileChooserAction gtk_action;
212     GtkWindow* gtk_parent = NULL;
213     if (parent)
214         gtk_parent = GTK_WINDOW( gtk_widget_get_toplevel(parent->m_widget) );
215 
216     wxString ok_btn_stock;
217     if ( style & wxFD_SAVE )
218     {
219         gtk_action = GTK_FILE_CHOOSER_ACTION_SAVE;
220 #ifdef __WXGTK4__
221         ok_btn_stock = wxConvertMnemonicsToGTK(wxGetStockLabel(wxID_SAVE));
222 #else
223         ok_btn_stock = "gtk-save";
224 #endif
225     }
226     else
227     {
228         gtk_action = GTK_FILE_CHOOSER_ACTION_OPEN;
229 #ifdef __WXGTK4__
230         ok_btn_stock = wxConvertMnemonicsToGTK(wxGetStockLabel(wxID_OPEN));
231 #else
232         ok_btn_stock = "gtk-open";
233 #endif
234     }
235 
236     m_widget = gtk_file_chooser_dialog_new(
237                    wxGTK_CONV(m_message),
238                    gtk_parent,
239                    gtk_action,
240 #ifdef __WXGTK4__
241                    static_cast<const gchar*>(wxGTK_CONV(wxConvertMnemonicsToGTK(wxGetStockLabel(wxID_CANCEL)))),
242 #else
243                    "gtk-cancel",
244 #endif
245                    GTK_RESPONSE_CANCEL,
246                    static_cast<const gchar*>(wxGTK_CONV(ok_btn_stock)), GTK_RESPONSE_ACCEPT,
247                    NULL);
248 
249     g_object_ref(m_widget);
250     GtkFileChooser* file_chooser = GTK_FILE_CHOOSER(m_widget);
251 
252     m_fc.SetWidget(file_chooser);
253 
254     gtk_dialog_set_default_response(GTK_DIALOG(m_widget), GTK_RESPONSE_ACCEPT);
255 
256     if ( style & wxFD_MULTIPLE )
257         gtk_file_chooser_set_select_multiple(file_chooser, true);
258 
259     // local-only property could be set to false to allow non-local files to be
260     // loaded. In that case get/set_uri(s) should be used instead of
261     // get/set_filename(s) everywhere and the GtkFileChooserDialog should
262     // probably also be created with a backend, e.g. "gnome-vfs", "default", ...
263     // (gtk_file_chooser_dialog_new_with_backend). Currently local-only is kept
264     // as the default - true:
265     // gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(m_widget), true);
266 
267     g_signal_connect (m_widget, "response",
268         G_CALLBACK (gtk_filedialog_response_callback), this);
269 
270     g_signal_connect (m_widget, "selection-changed",
271         G_CALLBACK (gtk_filedialog_selchanged_callback), this);
272 
273      // deal with extensions/filters
274     SetWildcard(wildCard);
275 
276     wxString defaultFileNameWithExt = defaultFileName;
277     if ( !wildCard.empty() && !defaultFileName.empty() &&
278             !wxFileName(defaultFileName).HasExt() )
279     {
280         // append the default extension, if any, to the initial file name: GTK
281         // won't do it for us by default (unlike e.g. MSW)
282         const wxFileName fnWC(m_fc.GetCurrentWildCard());
283         if ( fnWC.HasExt() )
284         {
285             // Notice that we shouldn't append the extension if it's a wildcard
286             // because this is not useful: the user would need to change it to use
287             // some fixed extension anyhow.
288             const wxString& ext = fnWC.GetExt();
289             if ( ext.find_first_of("?*") == wxString::npos )
290                 defaultFileNameWithExt << "." << ext;
291         }
292     }
293 
294 
295     // if defaultDir is specified it should contain the directory and
296     // defaultFileName should contain the default name of the file, however if
297     // directory is not given, defaultFileName contains both
298     wxFileName fn;
299     if ( defaultDir.empty() )
300         fn.Assign(defaultFileNameWithExt);
301     else if ( !defaultFileNameWithExt.empty() )
302         fn.Assign(defaultDir, defaultFileNameWithExt);
303     else
304         fn.AssignDir(defaultDir);
305 
306     // set the initial file name and/or directory
307     fn.MakeAbsolute(); // GTK+ needs absolute path
308     const wxString dir = fn.GetPath();
309     if ( !dir.empty() )
310     {
311         gtk_file_chooser_set_current_folder(file_chooser, wxGTK_CONV_FN(dir));
312     }
313 
314     const wxString fname = fn.GetFullName();
315     if ( style & wxFD_SAVE )
316     {
317         if ( !fname.empty() )
318         {
319             gtk_file_chooser_set_current_name(file_chooser, wxGTK_CONV_FN(fname));
320         }
321 
322 #if GTK_CHECK_VERSION(2,7,3)
323         if ((style & wxFD_OVERWRITE_PROMPT) && wx_is_at_least_gtk2(8))
324         {
325             gtk_file_chooser_set_do_overwrite_confirmation(file_chooser, true);
326         }
327 #endif
328     }
329     else // wxFD_OPEN
330     {
331         if ( !fname.empty() )
332         {
333             gtk_file_chooser_set_filename(file_chooser,
334                                           wxGTK_CONV_FN(fn.GetFullPath()));
335         }
336     }
337 
338     if ( style & wxFD_PREVIEW )
339     {
340         GtkWidget *previewImage = gtk_image_new();
341 
342         gtk_file_chooser_set_preview_widget(file_chooser, previewImage);
343         g_signal_connect(m_widget, "update-preview",
344                          G_CALLBACK(gtk_filedialog_update_preview_callback),
345                          previewImage);
346     }
347 
348     gtk_file_chooser_set_show_hidden(file_chooser,
349                                      style & wxFD_SHOW_HIDDEN ? TRUE : FALSE);
350 
351     return true;
352 }
353 
~wxFileDialog()354 wxFileDialog::~wxFileDialog()
355 {
356     if (m_extraControl)
357     {
358         // get chooser to drop its reference right now, allowing wxWindow dtor
359         // to verify that ref count drops to zero
360         gtk_file_chooser_set_extra_widget(
361             GTK_FILE_CHOOSER(m_widget), NULL);
362     }
363 }
364 
OnFakeOk(wxCommandEvent & WXUNUSED (event))365 void wxFileDialog::OnFakeOk(wxCommandEvent& WXUNUSED(event))
366 {
367     // Update the current directory from here, accessing it later may not work
368     // due to the strange way GtkFileChooser works.
369     wxGtkString
370         str(gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(m_widget)));
371     m_dir = wxString::FromUTF8(str);
372 
373     EndDialog(wxID_OK);
374 }
375 
ShowModal()376 int wxFileDialog::ShowModal()
377 {
378     WX_HOOK_MODAL_DIALOG();
379 
380     CreateExtraControl();
381 
382     return wxDialog::ShowModal();
383 }
384 
DoSetSize(int WXUNUSED (x),int WXUNUSED (y),int WXUNUSED (width),int WXUNUSED (height),int WXUNUSED (sizeFlags))385 void wxFileDialog::DoSetSize(int WXUNUSED(x), int WXUNUSED(y),
386                              int WXUNUSED(width), int WXUNUSED(height),
387                              int WXUNUSED(sizeFlags))
388 {
389 }
390 
OnSize(wxSizeEvent &)391 void wxFileDialog::OnSize(wxSizeEvent&)
392 {
393     // avoid calling DoLayout(), which will set the (wrong) size of
394     // m_extraControl, its size is managed by GtkFileChooser
395 }
396 
GetPath() const397 wxString wxFileDialog::GetPath() const
398 {
399     wxCHECK_MSG( !HasFlag(wxFD_MULTIPLE), wxString(), "When using wxFD_MULTIPLE, must call GetPaths() instead" );
400     return m_fc.GetPath();
401 }
402 
GetFilenames(wxArrayString & files) const403 void wxFileDialog::GetFilenames(wxArrayString& files) const
404 {
405     m_fc.GetFilenames( files );
406 }
407 
GetPaths(wxArrayString & paths) const408 void wxFileDialog::GetPaths(wxArrayString& paths) const
409 {
410     m_fc.GetPaths( paths );
411 }
412 
SetMessage(const wxString & message)413 void wxFileDialog::SetMessage(const wxString& message)
414 {
415     m_message = message;
416     SetTitle(message);
417 }
418 
SetPath(const wxString & path)419 void wxFileDialog::SetPath(const wxString& path)
420 {
421     wxFileDialogBase::SetPath(path);
422 
423     // Don't do anything if no path is specified, in particular don't set the
424     // path to m_dir below as this would result in opening the dialog in the
425     // parent directory of this one instead of m_dir itself.
426     if ( path.empty() )
427         return;
428 
429     // we need an absolute path for GTK native chooser so ensure that we have
430     // it: use the initial directory if it was set or just CWD otherwise (this
431     // is the default behaviour if m_dir is empty)
432     wxFileName fn(path);
433     fn.MakeAbsolute(m_dir);
434     m_fc.SetPath(fn.GetFullPath());
435 }
436 
SetDirectory(const wxString & dir)437 void wxFileDialog::SetDirectory(const wxString& dir)
438 {
439     wxFileDialogBase::SetDirectory(dir);
440 
441     m_fc.SetDirectory(dir);
442 }
443 
SetFilename(const wxString & name)444 void wxFileDialog::SetFilename(const wxString& name)
445 {
446     wxFileDialogBase::SetFilename(name);
447 
448     if (HasFdFlag(wxFD_SAVE))
449     {
450         gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(m_widget), wxGTK_CONV(name));
451     }
452 
453     else
454     {
455         wxString path( GetDirectory() );
456         if (path.empty())
457         {
458             // SetPath() fires an assert if fed other than filepaths
459             return;
460         }
461         SetPath(wxFileName(path, name).GetFullPath());
462     }
463 }
464 
GetFilename() const465 wxString wxFileDialog::GetFilename() const
466 {
467     wxCHECK_MSG( !HasFlag(wxFD_MULTIPLE), wxString(), "When using wxFD_MULTIPLE, must call GetFilenames() instead" );
468 
469     wxString currentFilename( m_fc.GetFilename() );
470     if (currentFilename.empty())
471     {
472         // m_fc.GetFilename() will return empty until the dialog has been shown
473         // in which case use any previously provided value
474         currentFilename = m_fileName;
475     }
476     return currentFilename;
477 }
478 
SetWildcard(const wxString & wildCard)479 void wxFileDialog::SetWildcard(const wxString& wildCard)
480 {
481     wxFileDialogBase::SetWildcard(wildCard);
482     m_fc.SetWildcard( GetWildcard() );
483 }
484 
SetFilterIndex(int filterIndex)485 void wxFileDialog::SetFilterIndex(int filterIndex)
486 {
487     m_fc.SetFilterIndex( filterIndex);
488 }
489 
GetFilterIndex() const490 int wxFileDialog::GetFilterIndex() const
491 {
492     return m_fc.GetFilterIndex();
493 }
494 
GTKSelectionChanged(const wxString & filename)495 void wxFileDialog::GTKSelectionChanged(const wxString& filename)
496 {
497     m_currentlySelectedFilename = filename;
498 
499     UpdateExtraControlUI();
500 }
501 
502 #endif // wxUSE_FILEDLG
503