]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - libs/gtkutil/filechooser.cpp
fixed access() assert when using msvc 8.0 runtime
[xonotic/netradiant.git] / libs / gtkutil / filechooser.cpp
1 /*
2 Copyright (C) 2001-2006, William Joseph.
3 All Rights Reserved.
4
5 This file is part of GtkRadiant.
6
7 GtkRadiant is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 GtkRadiant is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GtkRadiant; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20 */
21
22 #include "filechooser.h"
23
24 #include "ifiletypes.h"
25
26 #include <list>
27 #include <vector>
28 #include <gtk/gtkwidget.h>
29 #include <gtk/gtkwindow.h>
30 #include <gtk/gtkfilechooser.h>
31 #include <gtk/gtkfilechooserdialog.h>
32 #include <gtk/gtkstock.h>
33
34 #include "string/string.h"
35 #include "stream/stringstream.h"
36 #include "container/array.h"
37 #include "os/path.h"
38 #include "os/file.h"
39
40 #include "messagebox.h"
41
42
43 struct filetype_pair_t
44 {
45   filetype_pair_t()
46     : m_moduleName("")
47   {
48   }
49   filetype_pair_t(const char* moduleName, filetype_t type)
50     : m_moduleName(moduleName), m_type(type)
51   {
52   }
53   const char* m_moduleName;
54   filetype_t m_type;
55 };
56
57 class FileTypeList : public IFileTypeList
58 {
59   struct filetype_copy_t
60   {
61     filetype_copy_t(const filetype_pair_t& other)
62       : m_moduleName(other.m_moduleName), m_name(other.m_type.name), m_pattern(other.m_type.pattern)
63     {
64     }
65     CopiedString m_moduleName;
66     CopiedString m_name;
67     CopiedString m_pattern;
68   };
69
70   typedef std::list<filetype_copy_t> Types;
71   Types m_types;
72 public:
73
74   typedef Types::const_iterator const_iterator;
75   const_iterator begin() const
76   {
77     return m_types.begin();
78   }
79   const_iterator end() const
80   {
81     return m_types.end();
82   }
83
84   std::size_t size() const
85   {
86     return m_types.size();
87   }
88
89   void addType(const char* moduleName, filetype_t type)
90   {
91     m_types.push_back(filetype_pair_t(moduleName, type));
92   }
93 };
94
95 #ifdef WIN32
96
97 class Win32Filters
98 {
99   const FileTypeList& m_types;
100   Array<char> m_filters;
101 public:
102   Win32Filters(const FileTypeList& typeList) : m_types(typeList)
103   {
104     std::size_t len = 0;
105     for(FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i)
106     {
107       len = len + strlen((*i).m_name.c_str()) + strlen((*i).m_pattern.c_str()) * 2 + 5;
108     }
109     m_filters.resize(len + 1); // length + null char
110     char *w = m_filters.data();
111     for(FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i)
112     {
113       for(const char *r = (*i).m_name.c_str(); *r!='\0'; r++, w++)
114       {
115         *w = *r;
116       }
117       *w++ = ' ';
118       *w++ = '(';
119       for(const char *r = (*i).m_pattern.c_str(); *r!='\0'; r++, w++)
120       {
121         *w = *r;
122       }
123       *w++ = ')';
124       *w++ = '\0';
125       for(const char *r = (*i).m_pattern.c_str(); *r!='\0'; r++, w++)
126       {
127         *w = (*r == ',') ? ';' : *r;
128       }
129       *w++ = '\0';
130     }
131     m_filters[len] = '\0';
132   }
133   filetype_pair_t getType(const char *filter) const
134   {
135     for(FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i)
136     {
137       if(string_equal((*i).m_pattern.c_str(), filter))
138       {
139         return filetype_pair_t((*i).m_moduleName.c_str(), filetype_t((*i).m_name.c_str(), (*i).m_pattern.c_str()));
140       }
141     }
142     return filetype_pair_t();
143   }
144   const char* getFilters() const
145   {
146     return m_filters.data();
147   }
148 };
149
150 #define WIN32_LEAN_AND_MEAN
151 #include <gdk/gdkwin32.h>
152 #include <commdlg.h>
153
154 static char szFile[MAX_PATH];       /* filename string */
155
156
157 #define FILEDLG_CUSTOM_FILTER_LENGTH 64
158 // to be used with the advanced file selector
159
160 const char* file_dialog_show_win32(GtkWidget* parent, bool open, const char* title, const char* path, const char* pattern)
161 {
162   const char* r;
163   char* w;
164   filetype_t type;
165   FileTypeList typelist;
166
167   if(pattern == 0)
168   {
169     pattern = "*";
170   }
171
172   GlobalFiletypes().getTypeList(pattern, &typelist);
173
174   Win32Filters filters(typelist);
175
176   // win32 dialog stores the selected "save as type" extension in the second null-terminated string
177   char customfilter[FILEDLG_CUSTOM_FILTER_LENGTH];
178
179   static OPENFILENAME ofn;       /* common dialog box structure   */ 
180   static char szDirName[MAX_PATH];    /* directory string              */ 
181   static char szFile[MAX_PATH];       /* filename string               */ 
182   static char szFileTitle[MAX_PATH];  /* file title string             */ 
183   static int i, cbString;        /* integer count variables       */ 
184   static HANDLE hf;              /* file handle                   */ 
185
186   // do that the native way
187   /* Place the terminating null character in the szFile. */  
188   szFile[0] = '\0';
189   customfilter[0] = customfilter[1] = customfilter[2] = '\0';
190   
191   /* Set the members of the OPENFILENAME structure. */     
192   ofn.lStructSize = sizeof(OPENFILENAME); 
193   ofn.hwndOwner = (HWND)GDK_WINDOW_HWND(parent->window);
194   ofn.nFilterIndex = 0;
195   ofn.lpstrFilter = filters.getFilters();
196   ofn.lpstrCustomFilter = customfilter;
197   ofn.nMaxCustFilter = sizeof(customfilter);
198   ofn.lpstrFile = szFile;
199   ofn.nMaxFile = sizeof(szFile); 
200   ofn.lpstrFileTitle = 0; // we don't need to get the name of the file
201   if(path)
202   {
203     // szDirName: Radiant uses unix convention for paths internally
204     //   Win32 (of course) and Gtk (who would have thought) expect the '\\' convention
205     // copy path, replacing dir separators as appropriate
206     for(r=path, w=szDirName; *r!='\0'; r++)
207       *w++ = (*r=='/') ? '\\' : *r;
208     // terminate string
209     *w = '\0';
210     ofn.lpstrInitialDir = szDirName;
211   }
212   else ofn.lpstrInitialDir = 0;
213   ofn.lpstrTitle = title;
214   ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; 
215
216   /* Display the Open dialog box. */
217   // it's open or close depending on 'open' parameter
218   if (open)
219   {
220     if (!GetOpenFileName(&ofn))
221       return 0; // canceled
222   }
223   else
224   {
225     if (!GetSaveFileName(&ofn))
226       return 0; // canceled
227   }
228
229   if(!string_equal(pattern, "*"))
230   {
231     type = filters.getType(customfilter+1).m_type;
232   }
233
234   // don't return an empty filename
235   if(szFile[0] == '\0') return 0;
236
237   // convert back to unix format
238   for(w=szFile; *w!='\0'; w++)
239   {
240     if(*w=='\\')
241     {
242       *w = '/';
243     }
244   }
245   // when saving, force an extension depending on filetype
246   /* \todo SPoG - file_dialog should return filetype information separately.. not force file extension.. */
247   if(!open && !string_equal(pattern, "*"))
248   {
249     // last ext separator
250     const char* extension = path_get_extension(szFile);
251     // no extension
252     if(string_empty(extension))
253     {
254       strcat(szFile, type.pattern+1);
255     }
256     else
257     {
258       strcpy(szFile + (extension - szFile), type.pattern+2);
259     }
260   }
261
262   return szFile;
263 }
264
265 #endif
266
267
268 class GTKMasks
269 {
270   const FileTypeList& m_types;
271 public:
272   std::vector<CopiedString> m_filters;
273   std::vector<CopiedString> m_masks;
274
275   GTKMasks(const FileTypeList& types) : m_types(types)
276   {
277     m_masks.reserve(m_types.size());
278     for(FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i)
279     {
280       std::size_t len = strlen((*i).m_name.c_str()) + strlen((*i).m_pattern.c_str()) + 3;
281       StringOutputStream buffer(len + 1); // length + null char
282
283       buffer << (*i).m_name.c_str() << " <" << (*i).m_pattern.c_str() << ">";
284
285       m_masks.push_back(buffer.c_str());
286     }
287
288     m_filters.reserve(m_types.size());
289     for(FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i)
290     {
291       m_filters.push_back((*i).m_pattern);
292     }
293   }
294
295   filetype_pair_t GetTypeForGTKMask(const char *mask) const
296   {
297     std::vector<CopiedString>::const_iterator j = m_masks.begin();
298     for(FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i, ++j)
299     {
300       if(string_equal((*j).c_str(), mask))
301       {
302         return filetype_pair_t((*i).m_moduleName.c_str(), filetype_t((*i).m_name.c_str(), (*i).m_pattern.c_str()));
303       }
304     }
305     return filetype_pair_t();
306   }
307
308 };
309
310 static char g_file_dialog_file[1024];
311
312 const char* file_dialog_show(GtkWidget* parent, bool open, const char* title, const char* path, const char* pattern)
313 {
314   filetype_t type;
315
316   if(pattern == 0)
317   {
318     pattern = "*";
319   }
320
321   FileTypeList typelist;
322   GlobalFiletypes().getTypeList(pattern, &typelist);
323
324   GTKMasks masks(typelist);
325
326   if (title == 0)
327     title = open ? "Open File" : "Save File";
328     
329   GtkWidget* dialog;
330   if (open)
331   {
332     dialog = gtk_file_chooser_dialog_new(title,
333                                         GTK_WINDOW(parent),
334                                         GTK_FILE_CHOOSER_ACTION_OPEN,
335                                         GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
336                                         GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
337                                         NULL);
338   }
339   else
340   {
341     dialog = gtk_file_chooser_dialog_new(title,
342                                         GTK_WINDOW(parent),
343                                         GTK_FILE_CHOOSER_ACTION_SAVE,
344                                         GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
345                                         GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
346                                         NULL);
347     gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), "unnamed");
348   }
349
350   gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
351   gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER_ON_PARENT);
352
353   // we expect an actual path below, if the path is 0 we might crash
354   if (path != 0 && !string_empty(path))
355   {
356     ASSERT_MESSAGE(path_is_absolute(path), "file_dialog_show: path not absolute: " << makeQuoted(path));
357
358     Array<char> new_path(strlen(path)+1);
359
360     // copy path, replacing dir separators as appropriate
361     Array<char>::iterator w = new_path.begin();
362     for(const char* r = path; *r != '\0'; ++r)
363     {
364       *w++ = (*r == '/') ? G_DIR_SEPARATOR : *r;
365     }
366     // remove separator from end of path if required
367     if(*(w-1) == G_DIR_SEPARATOR)
368     {
369       --w;
370     }
371     // terminate string
372     *w = '\0';
373
374     gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), new_path.data());
375   }
376
377   // we should add all important paths as shortcut folder...
378   // gtk_file_chooser_add_shortcut_folder(GTK_FILE_CHOOSER(dialog), "/tmp/", NULL);
379
380   
381   for(std::size_t i = 0; i < masks.m_filters.size(); ++i)
382   {
383     GtkFileFilter* filter = gtk_file_filter_new();
384     gtk_file_filter_add_pattern(filter, masks.m_filters[i].c_str());
385     gtk_file_filter_set_name(filter, masks.m_masks[i].c_str());
386     gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter);
387   }
388
389   if(gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT)
390   {
391     strcpy(g_file_dialog_file, gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)));
392
393     if(!string_equal(pattern, "*"))
394     {
395       GtkFileFilter* filter = gtk_file_chooser_get_filter(GTK_FILE_CHOOSER(dialog));
396       if(filter != 0) // no filter set? some file-chooser implementations may allow the user to set no filter, which we treat as 'all files'
397       {
398         type = masks.GetTypeForGTKMask(gtk_file_filter_get_name(filter)).m_type;
399         // last ext separator
400         const char* extension = path_get_extension(g_file_dialog_file);
401         // no extension
402         if(string_empty(extension))
403         {
404           strcat(g_file_dialog_file, type.pattern+1);
405         }
406         else
407         {
408           strcpy(g_file_dialog_file + (extension - g_file_dialog_file), type.pattern+2);
409         }
410       }
411     }
412
413     // convert back to unix format
414     for(char* w = g_file_dialog_file; *w!='\0'; w++)
415     {
416       if(*w=='\\') 
417       {
418         *w = '/';
419       }
420     }
421   }
422   else
423   {
424     g_file_dialog_file[0] = '\0';
425   }
426
427   gtk_widget_destroy(dialog);
428
429   // don't return an empty filename
430   if(g_file_dialog_file[0] == '\0') return NULL;
431
432   return g_file_dialog_file;
433 }
434
435 char* dir_dialog(GtkWidget* parent, const char* title, const char* path)
436 {
437   GtkWidget* dialog = gtk_file_chooser_dialog_new(title,
438                                         GTK_WINDOW(parent),
439                                         GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,
440                                         GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
441                                         GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
442                                         NULL);
443
444   gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
445   gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER_ON_PARENT);
446
447   if(!string_empty(path))
448   {
449     gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), path);
450   }
451
452   char* filename = 0;
453   if(gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT)
454   {
455     filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
456   }
457
458   gtk_widget_destroy(dialog);
459
460   return filename;
461 }
462
463
464 #ifdef WIN32
465 bool g_FileChooser_nativeGUI = true;
466 #endif
467
468 const char* file_dialog(GtkWidget* parent, bool open, const char* title, const char* path, const char* pattern)
469 {
470   for(;;)
471   {
472     const char* file =
473 #ifdef WIN32
474                         g_FileChooser_nativeGUI
475       ? file_dialog_show_win32(parent, open, title, path, pattern) :
476 #endif
477         file_dialog_show(parent, open, title, path, pattern);
478
479     if(open
480       || file == 0
481       || !file_exists(file)
482       || gtk_MessageBox(parent, "The file specified already exists.\nDo you want to replace it?", title, eMB_NOYES, eMB_ICONQUESTION) == eIDYES)
483     {
484       return file;
485     }
486   }
487 }