Updates to MIME-types and wxFileDialog code for better
[wxWidgets.git] / src / unix / mimetype.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: unix/mimetype.cpp
3 // Purpose: classes and functions to manage MIME types
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 23.09.98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows licence (part of wxExtra library)
10 /////////////////////////////////////////////////////////////////////////////
11
12 // known bugs; there may be others!! chris elliott, biol75@york.ac.uk 27 Mar 01
13
14 // 1) .mailcap and .mimetypes can be either in a netscape or metamail format
15 // and entries may get confused during writing (I've tried to fix this; please let me know
16 // any files that fail)
17 // 2) KDE and Gnome do not yet fully support international read/write
18 // 3) Gnome key lines like open.latex."LaTeX this file"=latex %f will have odd results
19 // 4) writing to files comments out the existing data; I hope this avoids losing
20 // any data which we could not read, and data which we did not store like test=
21 // 5) results from reading files with multiple entries (especially matches with type/* )
22 // may (or may not) work for getXXX commands
23 // 6) Loading the png icons in Gnome doesn't work for me...
24 // 7) In Gnome, if keys.mime exists but keys.users does not, there is
25 // an error message in debug mode, but the file is still written OK
26 // 8) Deleting entries is only allowed from the user file; sytem wide entries
27 // will be preserved during unassociate
28 // 9) KDE does not yet handle multiple actions; Netscape mode never will
29
30 /*
31 TODO: this file is a mess, we need to split it and reformet/review
32 everything (VZ)
33 */
34
35 // ============================================================================
36 // declarations
37 // ============================================================================
38
39 // ----------------------------------------------------------------------------
40 // headers
41 // ----------------------------------------------------------------------------
42
43 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
44 #pragma implementation "mimetype.h"
45 #endif
46
47 // for compilers that support precompilation, includes "wx.h".
48 #include "wx/wxprec.h"
49
50 #ifdef __BORLANDC__
51 #pragma hdrstop
52 #endif
53
54 #ifndef WX_PRECOMP
55 #include "wx/defs.h"
56 #endif
57
58 #if wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE
59
60 #ifndef WX_PRECOMP
61 #include "wx/string.h"
62 #endif //WX_PRECOMP
63
64
65 #include "wx/log.h"
66 #include "wx/file.h"
67 #include "wx/intl.h"
68 #include "wx/dynarray.h"
69 #include "wx/confbase.h"
70
71 #include "wx/ffile.h"
72 #include "wx/textfile.h"
73 #include "wx/dir.h"
74 #include "wx/utils.h"
75 #include "wx/tokenzr.h"
76 #include "wx/iconloc.h"
77 #include "wx/filename.h"
78 #include "wx/fileconf.h"
79
80 #include "wx/unix/mimetype.h"
81
82 // other standard headers
83 #include <ctype.h>
84
85 #ifdef __VMS
86 /* silence warnings for comparing unsigned int's <0 */
87 # pragma message disable unscomzer
88 #endif
89
90 // wxMimeTypeCommands stores the verbs defined for the given MIME type with
91 // their values
92 class wxMimeTypeCommands
93 {
94 public:
95 wxMimeTypeCommands() { }
96
97 wxMimeTypeCommands(const wxArrayString& verbs,
98 const wxArrayString& commands)
99 : m_verbs(verbs),
100 m_commands(commands)
101 {
102 }
103
104 // add a new verb with the command or replace the old value
105 void AddOrReplaceVerb(const wxString& verb, const wxString& cmd)
106 {
107 int n = m_verbs.Index(verb, FALSE /* ignore case */);
108 if ( n == wxNOT_FOUND )
109 {
110 m_verbs.Add(verb);
111 m_commands.Add(cmd);
112 }
113 else
114 {
115 m_commands[n] = cmd;
116 }
117 }
118
119 void Add(const wxString& s)
120 {
121 m_verbs.Add(s.BeforeFirst(_T('=')));
122 m_commands.Add(s.AfterFirst(_T('=')));
123 }
124
125 // access the commands
126 size_t GetCount() const { return m_verbs.GetCount(); }
127 const wxString& GetVerb(size_t n) const { return m_verbs[n]; }
128 const wxString& GetCmd(size_t n) const { return m_commands[n]; }
129
130 bool HasVerb(const wxString& verb) const
131 { return m_verbs.Index(verb) != wxNOT_FOUND; }
132
133 wxString GetCommandForVerb(const wxString& verb, size_t *idx = NULL) const
134 {
135 wxString s;
136
137 int n = m_verbs.Index(verb);
138 if ( n != wxNOT_FOUND )
139 {
140 s = m_commands[(size_t)n];
141 if ( idx )
142 *idx = n;
143 }
144
145 return s;
146 }
147
148 // get a "verb=command" string
149 wxString GetVerbCmd(size_t n) const
150 {
151 return m_verbs[n] + _T('=') + m_commands[n];
152 }
153
154 private:
155 wxArrayString m_verbs,
156 m_commands;
157 };
158
159 // this class extends wxTextFile
160 //
161 // VZ: ???
162 class wxMimeTextFile : public wxTextFile
163 {
164 public:
165 // constructors
166 wxMimeTextFile () : wxTextFile () {};
167 wxMimeTextFile (const wxString& strFile) : wxTextFile (strFile) { };
168
169 int pIndexOf(const wxString & sSearch, bool bIncludeComments = FALSE, int iStart = 0)
170 {
171 size_t i = iStart;
172 int nResult = wxNOT_FOUND;
173 if (i>=GetLineCount()) return wxNOT_FOUND;
174
175 wxString sTest = sSearch;
176 sTest.MakeLower();
177 wxString sLine;
178
179 if (bIncludeComments)
180 {
181 while ( (i < GetLineCount()) )
182 {
183 sLine = GetLine (i);
184 sLine.MakeLower();
185 if (sLine.Contains(sTest)) nResult = (int) i;
186 i++;
187 }
188 }
189 else
190 {
191 while ( (i < GetLineCount()) )
192 {
193 sLine = GetLine (i);
194 sLine.MakeLower();
195 if ( ! sLine.StartsWith(wxT("#")))
196 {
197 if (sLine.Contains(sTest)) nResult = (int) i;
198 }
199 i++;
200 }
201 }
202 return nResult;
203 }
204
205 bool CommentLine(int nIndex)
206 {
207 if (nIndex <0) return FALSE;
208 if (nIndex >= (int)GetLineCount() ) return FALSE;
209 GetLine(nIndex) = GetLine(nIndex).Prepend(wxT("#"));
210 return TRUE;
211 }
212
213 bool CommentLine(const wxString & sTest)
214 {
215 int nIndex = pIndexOf(sTest);
216 if (nIndex <0) return FALSE;
217 if (nIndex >= (int)GetLineCount() ) return FALSE;
218 GetLine(nIndex) = GetLine(nIndex).Prepend(wxT("#"));
219 return TRUE;
220 }
221
222 wxString GetVerb (size_t i)
223 {
224 if (i > GetLineCount() ) return wxEmptyString;
225 wxString sTmp = GetLine(i).BeforeFirst(wxT('='));
226 return sTmp;
227 }
228
229 wxString GetCmd (size_t i)
230 {
231 if (i > GetLineCount() ) return wxEmptyString;
232 wxString sTmp = GetLine(i).AfterFirst(wxT('='));
233 return sTmp;
234 }
235 };
236
237 // in case we're compiling in non-GUI mode
238 class WXDLLEXPORT wxIcon;
239
240 // ----------------------------------------------------------------------------
241 // constants
242 // ----------------------------------------------------------------------------
243
244 // MIME code tracing mask
245 #define TRACE_MIME _T("mime")
246
247 // give trace messages about the results of mailcap tests
248 #define TRACE_MIME_TEST _T("mimetest")
249
250 // ----------------------------------------------------------------------------
251 // private functions
252 // ----------------------------------------------------------------------------
253
254 // there are some fields which we don't understand but for which we don't give
255 // warnings as we know that they're not important - this function is used to
256 // test for them
257 static bool IsKnownUnimportantField(const wxString& field);
258
259 // ----------------------------------------------------------------------------
260 // private classes
261 // ----------------------------------------------------------------------------
262
263
264 // This class uses both mailcap and mime.types to gather information about file
265 // types.
266 //
267 // The information about mailcap file was extracted from metamail(1) sources
268 // and documentation and subsequently revised when I found the RFC 1524
269 // describing it.
270 //
271 // Format of mailcap file: spaces are ignored, each line is either a comment
272 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
273 // A backslash can be used to quote semicolons and newlines (and, in fact,
274 // anything else including itself).
275 //
276 // The first field is always the MIME type in the form of type/subtype (see RFC
277 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
278 // "type" which means the same as "type/*", although I'm not sure whether this
279 // is standard.
280 //
281 // The second field is always the command to run. It is subject to
282 // parameter/filename expansion described below.
283 //
284 // All the following fields are optional and may not be present at all. If
285 // they're present they may appear in any order, although each of them should
286 // appear only once. The optional fields are the following:
287 // * notes=xxx is an uninterpreted string which is silently ignored
288 // * test=xxx is the command to be used to determine whether this mailcap line
289 // applies to our data or not. The RHS of this field goes through the
290 // parameter/filename expansion (as the 2nd field) and the resulting string
291 // is executed. The line applies only if the command succeeds, i.e. returns 0
292 // exit code.
293 // * print=xxx is the command to be used to print (and not view) the data of
294 // this type (parameter/filename expansion is done here too)
295 // * edit=xxx is the command to open/edit the data of this type
296 // * needsterminal means that a new interactive console must be created for
297 // the viewer
298 // * copiousoutput means that the viewer doesn't interact with the user but
299 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
300 // good example), thus it might be a good idea to use some kind of paging
301 // mechanism.
302 // * textualnewlines means not to perform CR/LF translation (not honored)
303 // * compose and composetyped fields are used to determine the program to be
304 // called to create a new message pert in the specified format (unused).
305 //
306 // Parameter/filename expansion:
307 // * %s is replaced with the (full) file name
308 // * %t is replaced with MIME type/subtype of the entry
309 // * for multipart type only %n is replaced with the nnumber of parts and %F is
310 // replaced by an array of (content-type, temporary file name) pairs for all
311 // message parts (TODO)
312 // * %{parameter} is replaced with the value of parameter taken from
313 // Content-type header line of the message.
314 //
315 //
316 // There are 2 possible formats for mime.types file, one entry per line (used
317 // for global mime.types and called Mosaic format) and "expanded" format where
318 // an entry takes multiple lines (used for users mime.types and called
319 // Netscape format).
320 //
321 // For both formats spaces are ignored and lines starting with a '#' are
322 // comments. Each record has one of two following forms:
323 // a) for "brief" format:
324 // <mime type> <space separated list of extensions>
325 // b) for "expanded" format:
326 // type=<mime type> BACKSLASH
327 // desc="<description>" BACKSLASH
328 // exts="<comma separated list of extensions>"
329 //
330 // (where BACKSLASH is a literal '\\' which we can't put here because cpp
331 // misinterprets it)
332 //
333 // We try to autodetect the format of mime.types: if a non-comment line starts
334 // with "type=" we assume the second format, otherwise the first one.
335
336 // there may be more than one entry for one and the same mime type, to
337 // choose the right one we have to run the command specified in the test
338 // field on our data.
339
340 // ----------------------------------------------------------------------------
341 // wxGNOME
342 // ----------------------------------------------------------------------------
343
344 // GNOME stores the info we're interested in in several locations:
345 // 1. xxx.keys files under /usr/share/mime-info
346 // 2. xxx.keys files under ~/.gnome/mime-info
347 //
348 // The format of xxx.keys file is the following:
349 //
350 // mimetype/subtype:
351 // field=value
352 //
353 // with blank lines separating the entries and indented lines starting with
354 // TABs. We're interested in the field icon-filename whose value is the path
355 // containing the icon.
356 //
357 // Update (Chris Elliott): apparently there may be an optional "[lang]" prefix
358 // just before the field name.
359
360
361 bool wxMimeTypesManagerImpl::CheckGnomeDirsExist ()
362 {
363 wxString gnomedir;
364 wxGetHomeDir( &gnomedir );
365 wxString sTmp = gnomedir;
366 sTmp = sTmp + wxT("/.gnome");
367 if (! wxDir::Exists ( sTmp ) )
368 {
369 if (!wxMkdir ( sTmp ))
370 {
371 wxLogError(_("Failed to create directory %s/.gnome."), sTmp.c_str());
372 return FALSE;
373 }
374 }
375 sTmp = sTmp + wxT("/mime-info");
376 if (! wxDir::Exists ( sTmp ) )
377 {
378 if (!wxMkdir ( sTmp ))
379 {
380 wxLogError(_("Failed to create directory %s/mime-info."), sTmp.c_str());
381 return FALSE;
382 }
383 }
384 return TRUE;
385
386 }
387
388
389
390 bool wxMimeTypesManagerImpl::WriteGnomeKeyFile(int index, bool delete_index)
391 {
392 wxString gnomedir;
393 wxGetHomeDir( &gnomedir );
394
395 wxMimeTextFile outfile ( gnomedir + wxT("/.gnome/mime-info/user.keys"));
396 // if this fails probably Gnome is not installed ??
397 // create it anyway as a private mime store
398
399 #if defined(__WXGTK20__) && wxUSE_UNICODE
400 if (! outfile.Open ( wxConvUTF8) )
401 #else
402 if (! outfile.Open () )
403 #endif
404 {
405 if (delete_index) return FALSE;
406 if (!CheckGnomeDirsExist() ) return FALSE;
407 outfile.Create ();
408 }
409
410 wxString sTmp, strType = m_aTypes[index];
411 int nIndex = outfile.pIndexOf(strType);
412 if ( nIndex == wxNOT_FOUND )
413 {
414 outfile.AddLine ( strType + wxT(':') );
415 // see file:/usr/doc/gnome-libs-devel-1.0.40/devel-docs/mime-type-handling.txt
416 // as this does not deal with internationalisation
417 // wxT( "\t[en_US]") + verb + wxT ('=') + cmd + wxT(" %f");
418 wxMimeTypeCommands * entries = m_aEntries[index];
419 size_t count = entries->GetCount();
420 for ( size_t i = 0; i < count; i++ )
421 {
422 sTmp = entries->GetVerbCmd(i);
423 sTmp.Replace( wxT("%s"), wxT("%f") );
424 sTmp = wxT ( "\t") + sTmp;
425 outfile.AddLine ( sTmp );
426 }
427 //for international use do something like this
428 //outfile.AddLine ( wxString( "\t[en_US]icon-filename=") + cmd );
429 outfile.AddLine ( wxT( "\ticon-filename=") + m_aIcons[index] );
430 }
431 else
432 {
433 if (delete_index)
434 outfile.CommentLine(nIndex);
435
436 wxMimeTypeCommands sOld;
437 size_t nOld = nIndex + 1;
438 bool oldEntryEnd = FALSE;
439 while ( (nOld < outfile.GetLineCount() )&& (oldEntryEnd == FALSE ))
440 {
441 sTmp = outfile.GetLine(nOld);
442 if ( (sTmp[0u] == wxT('\t')) || (sTmp[0u] == wxT('#')) )
443 {
444 // we have another line to deal with
445 outfile.CommentLine(nOld);
446 nOld ++;
447 // add the line to our store
448 if ((!delete_index) && (sTmp[0u] == wxT('\t')))
449 sOld.Add(sTmp);
450 }
451 // next mimetpye ??or blank line
452 else
453 oldEntryEnd = TRUE;
454 }
455 // list of entries in our data; these should all be in sOld,
456 // though sOld may also contain other entries , eg flags
457 if (!delete_index)
458 {
459 wxMimeTypeCommands * entries = m_aEntries[index];
460 size_t i;
461 for (i=0; i < entries->GetCount(); i++)
462 {
463 // replace any entries in sold that match verbs we know
464 sOld.AddOrReplaceVerb ( entries->GetVerb(i), entries->GetCmd (i) );
465 }
466 //sOld should also contain the icon
467 if ( !m_aIcons[index].empty() )
468 sOld.AddOrReplaceVerb ( wxT("icon-filename"), m_aIcons[index] );
469
470 for (i=0; i < sOld.GetCount(); i++)
471 {
472 sTmp = sOld.GetVerbCmd(i);
473 sTmp.Replace( wxT("%s"), wxT("%f") );
474 sTmp = wxT("\t") + sTmp;
475 nIndex ++;
476 outfile.InsertLine ( sTmp, nIndex );
477 }
478 }
479 }
480 bool bTmp = outfile.Write ();
481 return bTmp;
482 }
483
484
485 bool wxMimeTypesManagerImpl::WriteGnomeMimeFile(int index, bool delete_index)
486 {
487 wxString gnomedir;
488 wxGetHomeDir( &gnomedir );
489
490 wxMimeTextFile outfile ( gnomedir + wxT("/.gnome/mime-info/user.mime"));
491 // if this fails probably Gnome is not installed ??
492 // create it anyway as a private mime store
493 if (! outfile.Open () )
494 {
495 if (delete_index) return FALSE;
496 if (!CheckGnomeDirsExist() ) return FALSE;
497 outfile.Create ();
498 }
499 wxString strType = m_aTypes[index];
500 int nIndex = outfile.pIndexOf(strType);
501 if ( nIndex == wxNOT_FOUND )
502 {
503 outfile.AddLine ( strType );
504 outfile.AddLine ( wxT("\text:") + m_aExtensions.Item(index) );
505 }
506 else
507 {
508 if (delete_index)
509 {
510 outfile.CommentLine(nIndex);
511 outfile.CommentLine(nIndex+1);
512 }
513 else
514 {// check for next line being the right one to replace ??
515 wxString sOld = outfile.GetLine(nIndex+1);
516 if (sOld.Contains( wxT("\text: ")))
517 {
518 outfile.GetLine(nIndex+1) = wxT("\text: ") + m_aExtensions.Item(index);
519 }
520 else
521 {
522 outfile.InsertLine( wxT("\text: ") + m_aExtensions.Item(index), nIndex + 1 );
523 }
524 }
525 }
526 bool bTmp = outfile.Write ();
527 return bTmp;
528 }
529
530
531 void wxMimeTypesManagerImpl::LoadGnomeDataFromKeyFile(const wxString& filename,
532 const wxArrayString& dirs)
533 {
534 wxTextFile textfile(filename);
535 #if defined(__WXGTK20__) && wxUSE_UNICODE
536 if ( !textfile.Open( wxConvUTF8) )
537 #else
538 if ( !textfile.Open() )
539 #endif
540 return;
541 wxLogTrace(TRACE_MIME, wxT("--- Opened Gnome file %s ---"),
542 filename.c_str());
543
544 // values for the entry being parsed
545 wxString curMimeType, curIconFile;
546 wxMimeTypeCommands * entry = new wxMimeTypeCommands;
547
548 // these are always empty in this file
549 wxArrayString strExtensions;
550 wxString strDesc;
551
552 const wxChar *pc;
553 size_t nLineCount = textfile.GetLineCount();
554 size_t nLine = 0;
555 while ( nLine < nLineCount)
556 {
557 pc = textfile[nLine].c_str();
558 if ( *pc != _T('#') )
559 {
560
561 wxLogTrace(TRACE_MIME, wxT("--- Reading from Gnome file %s '%s' ---"),
562 filename.c_str(),pc);
563
564 wxString sTmp(pc);
565 if (sTmp.Contains(wxT("=")) )
566 {
567 // GNOME 1:
568 if (sTmp.Contains( wxT("icon-filename=") ) )
569 {
570 curIconFile = sTmp.AfterFirst(wxT('='));
571 }
572 // GNOME 2:
573 else if (sTmp.Contains( wxT("icon_filename=") ) )
574 {
575 curIconFile = sTmp.AfterFirst(wxT('='));
576
577 if (!wxFileExists(curIconFile))
578 {
579 size_t nDirs = dirs.GetCount();
580 for (size_t nDir = 0; nDir < nDirs; nDir++)
581 {
582 wxFileName newFile( curIconFile );
583 newFile.SetPath( dirs[nDir] );
584 newFile.AppendDir( wxT("pixmaps") );
585 newFile.AppendDir( wxT("document-icons") );
586 newFile.SetExt( wxT("png") );
587 if (newFile.FileExists())
588 curIconFile = newFile.GetFullPath();
589 }
590 }
591 }
592 else //: some other field,
593 {
594 //may contain lines like this (RH7)
595 // \t[lang]open.tex."TeX this file"=tex %f
596 // \tflags.tex.flags=needsterminal
597 // \topen.latex."LaTeX this file"=latex %f
598 // \tflags.latex.flags=needsterminal
599
600 // \topen=xdvi %f
601 // \tview=xdvi %f
602 // \topen.convert.Convert file to Postscript=dvips %f -o `basename %f .dvi`.ps
603
604 // for now ignore lines with flags in...FIX
605 sTmp = sTmp.AfterLast(wxT(']'));
606 sTmp = sTmp.AfterLast(wxT('\t'));
607 sTmp.Trim(FALSE).Trim();
608 if (0 == sTmp.Replace ( wxT("%f"), wxT("%s") )) sTmp = sTmp + wxT(" %s");
609 entry->Add(sTmp);
610
611 }
612
613 } // emd of has an equals sign
614 else
615 {
616 // not a comment and not an equals sign
617 if (sTmp.Contains(wxT('/')))
618 {
619 // this is the start of the new mimetype
620 // overwrite any existing data
621 if (! curMimeType.empty())
622 {
623 AddToMimeData ( curMimeType, curIconFile, entry, strExtensions, strDesc);
624
625 // now get ready for next bit
626 entry = new wxMimeTypeCommands;
627 }
628 curMimeType = sTmp.BeforeFirst(wxT(':'));
629 }
630 }
631 } // end of not a comment
632 // ignore blank lines
633 nLine ++;
634 } // end of while, save any data
635
636 if (! curMimeType.empty())
637 AddToMimeData ( curMimeType, curIconFile, entry, strExtensions, strDesc);
638 }
639
640
641
642 void wxMimeTypesManagerImpl::LoadGnomeMimeTypesFromMimeFile(const wxString& filename)
643 {
644 wxTextFile textfile(filename);
645 if ( !textfile.Open() )
646 return;
647
648 wxLogTrace(TRACE_MIME,
649 wxT("--- Opened Gnome file %s ---"),
650 filename.c_str());
651
652 // values for the entry being parsed
653 wxString curMimeType, curExtList;
654
655 const wxChar *pc;
656 size_t nLineCount = textfile.GetLineCount();
657 for ( size_t nLine = 0;; nLine++ )
658 {
659 if ( nLine < nLineCount )
660 {
661 pc = textfile[nLine].c_str();
662 if ( *pc == wxT('#') )
663 {
664 // skip comments
665 continue;
666 }
667 }
668 else
669 {
670 // so that we will fall into the "if" below
671 pc = NULL;
672 }
673
674 if ( !pc || !*pc )
675 {
676 // end of the entry
677 if ( !!curMimeType && !!curExtList )
678 {
679 wxLogTrace(TRACE_MIME,
680 wxT("--- At end of Gnome file finding mimetype %s ---"),
681 curMimeType.c_str());
682
683 AddMimeTypeInfo(curMimeType, curExtList, wxEmptyString);
684 }
685
686 if ( !pc )
687 {
688 // the end - this can only happen if nLine == nLineCount
689 break;
690 }
691
692 curExtList.Empty();
693
694 continue;
695 }
696
697 // what do we have here?
698 if ( *pc == wxT('\t') )
699 {
700 // this is a field=value ling
701 pc++; // skip leading TAB
702
703 static const int lenField = 5; // strlen("ext: ")
704 if ( wxStrncmp(pc, wxT("ext: "), lenField) == 0 )
705 {
706 // skip it and take everything left until the end of line
707 curExtList = pc + lenField;
708 }
709 //else: some other field, we don't care
710 }
711 else
712 {
713 // this is the start of the new section
714 wxLogTrace(TRACE_MIME,
715 wxT("--- In Gnome file finding mimetype %s ---"),
716 curMimeType.c_str());
717
718 if (! curMimeType.empty())
719 AddMimeTypeInfo(curMimeType, curExtList, wxEmptyString);
720
721 curMimeType.Empty();
722
723 while ( *pc != wxT(':') && *pc != wxT('\0') )
724 {
725 curMimeType += *pc++;
726 }
727 }
728 }
729 }
730
731
732 void wxMimeTypesManagerImpl::LoadGnomeMimeFilesFromDir(
733 const wxString& dirbase, const wxArrayString& dirs)
734 {
735 wxASSERT_MSG( !!dirbase && !wxEndsWithPathSeparator(dirbase),
736 _T("base directory shouldn't end with a slash") );
737
738 wxString dirname = dirbase;
739 dirname << wxT("/mime-info");
740
741 if ( !wxDir::Exists(dirname) )
742 return;
743
744 wxDir dir(dirname);
745 if ( !dir.IsOpened() )
746 return;
747
748 // we will concatenate it with filename to get the full path below
749 dirname += wxT('/');
750
751 wxString filename;
752 bool cont;
753 cont = dir.GetFirst(&filename, _T("*.mime"), wxDIR_FILES);
754 while ( cont )
755 {
756 LoadGnomeMimeTypesFromMimeFile(dirname + filename);
757
758 cont = dir.GetNext(&filename);
759 }
760
761 cont = dir.GetFirst(&filename, _T("*.keys"), wxDIR_FILES);
762 while ( cont )
763 {
764 LoadGnomeDataFromKeyFile(dirname + filename, dirs);
765
766 cont = dir.GetNext(&filename);
767 }
768
769 // Hack alert: We scan all icons and deduce the
770 // mime-type from the file name.
771 dirname = dirbase;
772 dirname << wxT("/pixmaps/document-icons");
773
774 // these are always empty in this file
775 wxArrayString strExtensions;
776 wxString strDesc;
777
778 if ( !wxDir::Exists(dirname) )
779 return;
780
781 wxDir dir2( dirname );
782
783 cont = dir2.GetFirst(&filename, wxT("gnome-*.png"), wxDIR_FILES);
784 while ( cont )
785 {
786 wxString mimeType = filename;
787 mimeType.Remove( 0, 6 ); // remove "gnome-"
788 mimeType.Remove( mimeType.Len()-4, 4 ); // remove ".png"
789 int pos = mimeType.Find( wxT("-") );
790 if (pos != wxNOT_FOUND)
791 {
792 mimeType.SetChar( pos, wxT('/') );
793 wxString iconFile = dirname;
794 iconFile << wxT("/");
795 iconFile << filename;
796 AddToMimeData ( mimeType, iconFile, NULL, strExtensions, strDesc, TRUE );
797 }
798
799 cont = dir2.GetNext(&filename);
800 }
801 }
802
803 void wxMimeTypesManagerImpl::GetGnomeMimeInfo(const wxString& sExtraDir)
804 {
805 wxArrayString dirs;
806 dirs.Add(wxT("/opt/gnome/share"));
807 dirs.Add(wxT("/usr/share"));
808 dirs.Add(wxT("/usr/local/share"));
809
810 wxString gnomedir;
811 wxGetHomeDir( &gnomedir );
812 gnomedir += wxT("/.gnome");
813 dirs.Add( gnomedir );
814 if (!sExtraDir.empty()) dirs.Add( sExtraDir );
815
816 size_t nDirs = dirs.GetCount();
817 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
818 {
819 LoadGnomeMimeFilesFromDir(dirs[nDir], dirs);
820 }
821 }
822
823 // ----------------------------------------------------------------------------
824 // KDE
825 // ----------------------------------------------------------------------------
826
827
828 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
829 // may be found in either of the following locations
830 //
831 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
832 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
833 //
834 // The format of a .kdelnk file is almost the same as the one used by
835 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
836 // value for the entry "Type"
837
838 // kde writing; see http://webcvs.kde.org/cgi-bin/cvsweb.cgi/~checkout~/kdelibs/kio/DESKTOP_ENTRY_STANDARD
839 // for now write to .kdelnk but should eventually do .desktop instead (in preference??)
840
841 bool wxMimeTypesManagerImpl::CheckKDEDirsExist ( const wxString & sOK, const wxString & sTest )
842
843 {
844 if (sTest.empty())
845 {
846 if (wxDir::Exists(sOK)) return TRUE;
847 else return FALSE;
848 }
849 else
850 {
851 wxString sStart = sOK + wxT("/") + sTest.BeforeFirst(wxT('/'));
852 if (!wxDir::Exists(sStart)) wxMkdir(sStart);
853 wxString sEnd = sTest.AfterFirst(wxT('/'));
854 return CheckKDEDirsExist(sStart, sEnd);
855 }
856 }
857
858 bool wxMimeTypesManagerImpl::WriteKDEMimeFile(int index, bool delete_index)
859 {
860 wxMimeTextFile appoutfile, mimeoutfile;
861 wxString sHome = wxGetHomeDir();
862 wxString sTmp = wxT(".kde/share/mimelnk/");
863 wxString sMime = m_aTypes[index];
864 CheckKDEDirsExist (sHome, sTmp + sMime.BeforeFirst(wxT('/')) );
865 sTmp = sHome + wxT('/') + sTmp + sMime + wxT(".kdelnk");
866
867 bool bTemp;
868 bool bMimeExists = mimeoutfile.Open (sTmp);
869 if (!bMimeExists)
870 {
871 bTemp = mimeoutfile.Create (sTmp);
872 // some unknown error eg out of disk space
873 if (!bTemp) return FALSE;
874 }
875
876 sTmp = wxT(".kde/share/applnk/");
877 CheckKDEDirsExist (sHome, sTmp + sMime.AfterFirst(wxT('/')) );
878 sTmp = sHome + wxT('/') + sTmp + sMime.AfterFirst(wxT('/')) + wxT(".kdelnk");
879
880 bool bAppExists;
881 bAppExists = appoutfile.Open (sTmp);
882 if (!bAppExists)
883 {
884 bTemp = appoutfile.Create (sTmp);
885 // some unknown error eg out of disk space
886 if (!bTemp) return FALSE;
887 }
888
889 // fixed data; write if new file
890 if (!bMimeExists)
891 {
892 mimeoutfile.AddLine(wxT("#KDE Config File"));
893 mimeoutfile.AddLine(wxT("[KDE Desktop Entry]"));
894 mimeoutfile.AddLine(wxT("Version=1.0"));
895 mimeoutfile.AddLine(wxT("Type=MimeType"));
896 mimeoutfile.AddLine(wxT("MimeType=") + sMime);
897 }
898
899 if (!bAppExists)
900 {
901 mimeoutfile.AddLine(wxT("#KDE Config File"));
902 mimeoutfile.AddLine(wxT("[KDE Desktop Entry]"));
903 appoutfile.AddLine(wxT("Version=1.0"));
904 appoutfile.AddLine(wxT("Type=Application"));
905 appoutfile.AddLine(wxT("MimeType=") + sMime + wxT(';'));
906 }
907
908 // variable data
909 // ignore locale
910 mimeoutfile.CommentLine(wxT("Comment="));
911 if (!delete_index)
912 mimeoutfile.AddLine(wxT("Comment=") + m_aDescriptions[index]);
913 appoutfile.CommentLine(wxT("Name="));
914 if (!delete_index)
915 appoutfile.AddLine(wxT("Comment=") + m_aDescriptions[index]);
916
917 sTmp = m_aIcons[index];
918 // we can either give the full path, or the shortfilename if its in
919 // one of the directories we search
920 mimeoutfile.CommentLine(wxT("Icon=") );
921 if (!delete_index) mimeoutfile.AddLine(wxT("Icon=") + sTmp );
922 appoutfile.CommentLine(wxT("Icon=") );
923 if (!delete_index) appoutfile.AddLine(wxT("Icon=") + sTmp );
924
925 sTmp = wxT(" ") + m_aExtensions[index];
926
927 wxStringTokenizer tokenizer(sTmp, _T(" "));
928 sTmp = wxT("Patterns=");
929 mimeoutfile.CommentLine(sTmp);
930 while ( tokenizer.HasMoreTokens() )
931 {
932 // holds an extension; need to change it to *.ext;
933 wxString e = wxT("*.") + tokenizer.GetNextToken() + wxT(";");
934 sTmp = sTmp + e;
935 }
936 if (!delete_index) mimeoutfile.AddLine(sTmp);
937
938 wxMimeTypeCommands * entries = m_aEntries[index];
939 // if we don't find open just have an empty string ... FIX this
940 sTmp = entries->GetCommandForVerb(_T("open"));
941 sTmp.Replace( wxT("%s"), wxT("%f") );
942
943 mimeoutfile.CommentLine(wxT("DefaultApp=") );
944 if (!delete_index) mimeoutfile.AddLine(wxT("DefaultApp=") + sTmp);
945
946 sTmp.Replace( wxT("%f"), wxT("") );
947 appoutfile.CommentLine(wxT("Exec="));
948 if (!delete_index) appoutfile.AddLine(wxT("Exec=") + sTmp);
949
950 if (entries->GetCount() > 1)
951 {
952 //other actions as well as open
953
954 }
955 bTemp = FALSE;
956 if (mimeoutfile.Write ()) bTemp = TRUE;
957 mimeoutfile.Close ();
958 if (appoutfile.Write ()) bTemp = TRUE;
959 appoutfile.Close ();
960
961 return bTemp;
962
963
964 }
965
966 void wxMimeTypesManagerImpl::LoadKDELinksForMimeSubtype(const wxString& dirbase,
967 const wxString& subdir,
968 const wxString& filename,
969 const wxArrayString& icondirs)
970 {
971 wxMimeTextFile file;
972 if ( !file.Open(dirbase + filename) ) return;
973
974 wxLogTrace(TRACE_MIME, wxT("loading KDE file %s"),
975 (dirbase+filename).c_str());
976
977 wxMimeTypeCommands * entry = new wxMimeTypeCommands;
978 wxArrayString sExts;
979 wxString mimetype, mime_desc, strIcon;
980
981 int nIndex = file.pIndexOf( wxT("MimeType=") );
982 if (nIndex == wxNOT_FOUND)
983 {
984 // construct mimetype from the directory name and the basename of the
985 // file (it always has .kdelnk extension)
986 mimetype << subdir << wxT('/') << filename.BeforeLast( wxT('.') );
987 }
988 else mimetype = file.GetCmd (nIndex);
989
990 // first find the description string: it is the value in either "Comment="
991 // line or "Comment[<locale_name>]=" one
992 nIndex = wxNOT_FOUND;
993
994 wxString comment;
995 #if wxUSE_INTL
996 wxLocale *locale = wxGetLocale();
997 if ( locale )
998 {
999 // try "Comment[locale name]" first
1000 comment << _T("Comment[") + locale->GetName() + _T("]=");
1001 nIndex = file.pIndexOf(comment);
1002 }
1003 #endif // wxUSE_INTL
1004
1005 if ( nIndex == wxNOT_FOUND )
1006 {
1007 comment = _T("Comment=");
1008 nIndex = file.pIndexOf(comment);
1009 }
1010
1011 if ( nIndex != wxNOT_FOUND ) mime_desc = file.GetCmd(nIndex);
1012 //else: no description
1013
1014 // next find the extensions
1015 wxString mime_extension;
1016
1017 nIndex = file.pIndexOf(_T("Patterns="));
1018 if ( nIndex != wxNOT_FOUND )
1019 {
1020 wxString exts = file.GetCmd (nIndex);;
1021
1022 wxStringTokenizer tokenizer(exts, _T(";"));
1023 while ( tokenizer.HasMoreTokens() )
1024 {
1025 wxString e = tokenizer.GetNextToken();
1026 if ( e.Left(2) != _T("*.") )
1027 continue; // don't support too difficult patterns
1028
1029 if ( !mime_extension.empty() )
1030 {
1031 // separate from the previous ext
1032 mime_extension << _T(' ');
1033 }
1034
1035 mime_extension << e.Mid(2);
1036 }
1037 }
1038 sExts.Add(mime_extension);
1039
1040
1041 // ok, now we can take care of icon:
1042
1043 nIndex = file.pIndexOf(_T("Icon="));
1044 if ( nIndex != wxNOT_FOUND )
1045 {
1046 strIcon = file.GetCmd(nIndex);
1047 wxLogTrace(TRACE_MIME, wxT(" icon %s"), strIcon.c_str());
1048 //it could be the real path, but more often a short name
1049
1050
1051 if (!wxFileExists(strIcon))
1052 {
1053 // icon is just the short name
1054 if ( !strIcon.empty() )
1055 {
1056 // we must check if the file exists because it may be stored
1057 // in many locations, at least ~/.kde and $KDEDIR
1058 size_t nDir, nDirs = icondirs.GetCount();
1059 for ( nDir = 0; nDir < nDirs; nDir++ )
1060 {
1061 wxFileName fname( icondirs[nDir], strIcon );
1062 fname.SetExt( wxT("png") );
1063 if (fname.FileExists())
1064 {
1065 strIcon = fname.GetFullPath();
1066 wxLogTrace(TRACE_MIME, wxT(" iconfile %s"), strIcon.c_str());
1067 break;
1068 }
1069 }
1070 }
1071 }
1072 }
1073 // now look for lines which know about the application
1074 // exec= or DefaultApp=
1075
1076 nIndex = file.pIndexOf(wxT("DefaultApp"));
1077
1078 if ( nIndex == wxNOT_FOUND )
1079 {
1080 // no entry try exec
1081 nIndex = file.pIndexOf(wxT("Exec"));
1082 }
1083
1084 if ( nIndex != wxNOT_FOUND )
1085 {
1086 wxString sTmp = file.GetCmd(nIndex);
1087 // we expect %f; others including %F and %U and %u are possible
1088 if (0 == sTmp.Replace ( wxT("%f"), wxT("%s") ))
1089 sTmp = sTmp + wxT(" %s");
1090 entry->AddOrReplaceVerb (wxString(wxT("open")), sTmp );
1091 }
1092
1093 AddToMimeData (mimetype, strIcon, entry, sExts, mime_desc);
1094 }
1095
1096 void wxMimeTypesManagerImpl::LoadKDELinksForMimeType(const wxString& dirbase,
1097 const wxString& subdir,
1098 const wxArrayString& icondirs)
1099 {
1100 wxString dirname = dirbase;
1101 dirname += subdir;
1102 wxDir dir(dirname);
1103 if ( !dir.IsOpened() )
1104 return;
1105
1106 wxLogTrace(TRACE_MIME, wxT("--- Loading from KDE directory %s ---"),
1107 dirname.c_str());
1108
1109 dirname += _T('/');
1110
1111 wxString filename;
1112 bool cont = dir.GetFirst(&filename, _T("*.kdelnk"), wxDIR_FILES);
1113 while ( cont )
1114 {
1115 LoadKDELinksForMimeSubtype(dirname, subdir, filename, icondirs);
1116
1117 cont = dir.GetNext(&filename);
1118 }
1119 // new standard for Gnome and KDE
1120 cont = dir.GetFirst(&filename, _T("*.desktop"), wxDIR_FILES);
1121 while ( cont )
1122 {
1123 LoadKDELinksForMimeSubtype(dirname, subdir, filename, icondirs);
1124
1125 cont = dir.GetNext(&filename);
1126 }
1127 }
1128
1129 void wxMimeTypesManagerImpl::LoadKDELinkFilesFromDir(const wxString& dirbase,
1130 const wxArrayString& icondirs)
1131 {
1132 wxASSERT_MSG( !!dirbase && !wxEndsWithPathSeparator(dirbase),
1133 _T("base directory shouldn't end with a slash") );
1134
1135 wxString dirname = dirbase;
1136 dirname << _T("/mimelnk");
1137
1138 if ( !wxDir::Exists(dirname) )
1139 return;
1140
1141 wxDir dir(dirname);
1142 if ( !dir.IsOpened() )
1143 return;
1144
1145 // we will concatenate it with dir name to get the full path below
1146 dirname += _T('/');
1147
1148 wxString subdir;
1149 bool cont = dir.GetFirst(&subdir, wxEmptyString, wxDIR_DIRS);
1150 while ( cont )
1151 {
1152 LoadKDELinksForMimeType(dirname, subdir, icondirs);
1153
1154 cont = dir.GetNext(&subdir);
1155 }
1156 }
1157
1158 void wxMimeTypesManagerImpl::GetKDEMimeInfo(const wxString& sExtraDir)
1159 {
1160 wxArrayString dirs;
1161 wxArrayString icondirs;
1162
1163 // the variable KDEDIR is set when KDE is running
1164 const wxChar *kdedir = wxGetenv( wxT("KDEDIR") );
1165
1166 if (kdedir)
1167 {
1168 wxFileName configFile( kdedir, wxEmptyString );
1169 configFile.AppendDir( wxT("share") );
1170 #if 0
1171 configFile.AppendDir( wxT("config") );
1172 configFile.SetName( wxT("kdeglobals") );
1173
1174 wxFileConfig config( wxEmptyString, wxEmptyString, configFile.GetFullPath() );
1175 wxString theme;
1176 config.SetPath( wxT("Icons") );
1177 config.Read( wxT("Theme"), theme );
1178
1179 configFile.RemoveDir( configFile.GetDirCount()-1 );
1180 configFile.AppendDir( wxT("icons") );
1181 configFile.AppendDir( theme );
1182 #else
1183 configFile.AppendDir( wxT("icons") );
1184 configFile.AppendDir( wxT("crystalsvg") );
1185 #endif
1186
1187 if (!wxDir::Exists(configFile.GetPath()))
1188 {
1189 configFile.RemoveDir( configFile.GetDirCount()-1 );
1190 configFile.AppendDir( wxT("crystal") );
1191 }
1192
1193 if (!wxDir::Exists(configFile.GetPath()))
1194 {
1195 configFile.RemoveDir( configFile.GetDirCount()-1 );
1196 configFile.AppendDir( wxT("default.kde") );
1197 }
1198
1199 if (wxDir::Exists(configFile.GetPath()))
1200 {
1201 configFile.AppendDir( wxT("32x32") );
1202 configFile.AppendDir( wxT("mimetypes") );
1203 icondirs.Add( configFile.GetFullPath() );
1204 }
1205 }
1206
1207 // settings in ~/.kde have maximal priority
1208 dirs.Add(wxGetHomeDir() + wxT("/.kde/share"));
1209 icondirs.Add(wxGetHomeDir() + wxT("/.kde/share/icons/"));
1210
1211 if ( kdedir )
1212 {
1213 dirs.Add( wxString(kdedir) + wxT("/share") );
1214 icondirs.Add( wxString(kdedir) + wxT("/share/icons/") );
1215 }
1216 else
1217 {
1218 // try to guess KDEDIR
1219 dirs.Add(_T("/usr/share"));
1220 dirs.Add(_T("/opt/kde/share"));
1221 icondirs.Add(_T("/usr/share/icons/"));
1222 icondirs.Add(_T("/usr/X11R6/share/icons/")); // Debian/Corel linux
1223 icondirs.Add(_T("/opt/kde/share/icons/"));
1224 }
1225
1226 if (!sExtraDir.empty()) dirs.Add (sExtraDir);
1227 icondirs.Add(sExtraDir + wxT("/icons"));
1228
1229 size_t nDirs = dirs.GetCount();
1230 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
1231 {
1232 LoadKDELinkFilesFromDir(dirs[nDir], icondirs);
1233 }
1234 }
1235
1236 // ----------------------------------------------------------------------------
1237 // wxFileTypeImpl (Unix)
1238 // ----------------------------------------------------------------------------
1239
1240 wxString wxFileTypeImpl::GetExpandedCommand(const wxString & verb, const wxFileType::MessageParameters& params) const
1241 {
1242 wxString sTmp;
1243 size_t i = 0;
1244 while ( (i < m_index.GetCount() ) && sTmp.empty() )
1245 {
1246 sTmp = m_manager->GetCommand ( verb, m_index[i] );
1247 i ++;
1248 }
1249
1250 return wxFileType::ExpandCommand(sTmp, params);
1251 }
1252
1253 bool wxFileTypeImpl::GetIcon(wxIconLocation *iconLoc) const
1254
1255 {
1256 wxString sTmp;
1257 size_t i = 0;
1258 while ( (i < m_index.GetCount() ) && sTmp.empty() )
1259 {
1260 sTmp = m_manager->m_aIcons[m_index[i]];
1261 i ++;
1262 }
1263 if ( sTmp.empty () )
1264 return FALSE;
1265
1266 if ( iconLoc )
1267 {
1268 iconLoc->SetFileName(sTmp);
1269 }
1270
1271 return TRUE;
1272 }
1273
1274
1275 bool
1276 wxFileTypeImpl::GetMimeTypes(wxArrayString& mimeTypes) const
1277 {
1278 mimeTypes.Clear();
1279 for (size_t i = 0; i < m_index.GetCount(); i++)
1280 mimeTypes.Add(m_manager->m_aTypes[m_index[i]]);
1281 return TRUE;
1282 }
1283
1284
1285 size_t wxFileTypeImpl::GetAllCommands(wxArrayString *verbs,
1286 wxArrayString *commands,
1287 const wxFileType::MessageParameters& params) const
1288 {
1289
1290 wxString vrb, cmd, sTmp;
1291 size_t count = 0;
1292 wxMimeTypeCommands * sPairs;
1293
1294 // verbs and commands have been cleared already in mimecmn.cpp...
1295 // if we find no entries in the exact match, try the inexact match
1296 for (size_t n = 0; ((count ==0) && (n < m_index.GetCount())); n++)
1297 {
1298 // list of verb = command pairs for this mimetype
1299 sPairs = m_manager->m_aEntries [m_index[n]];
1300 size_t i;
1301 for ( i = 0; i < sPairs->GetCount (); i++ )
1302 {
1303 vrb = sPairs->GetVerb(i);
1304 // some gnome entries have . inside
1305 vrb = vrb.AfterLast(wxT('.'));
1306 cmd = sPairs->GetCmd (i);
1307 if (! cmd.empty() )
1308 {
1309 cmd = wxFileType::ExpandCommand(cmd, params);
1310 count ++;
1311 if ( vrb.IsSameAs (wxT("open")))
1312 {
1313 verbs->Insert(vrb,0u);
1314 commands ->Insert(cmd,0u);
1315 }
1316 else
1317 {
1318 verbs->Add (vrb);
1319 commands->Add (cmd);
1320 }
1321 }
1322
1323 }
1324
1325 }
1326 return count;
1327
1328 }
1329
1330 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
1331 {
1332 wxString strExtensions = m_manager->GetExtension(m_index[0]);
1333 extensions.Empty();
1334
1335 // one extension in the space or comma delimitid list
1336 wxString strExt;
1337 for ( const wxChar *p = strExtensions;; p++ ) {
1338 if ( *p == wxT(' ') || *p == wxT(',') || *p == wxT('\0') ) {
1339 if ( !strExt.empty() ) {
1340 extensions.Add(strExt);
1341 strExt.Empty();
1342 }
1343 //else: repeated spaces (shouldn't happen, but it's not that
1344 // important if it does happen)
1345
1346 if ( *p == wxT('\0') )
1347 break;
1348 }
1349 else if ( *p == wxT('.') ) {
1350 // remove the dot from extension (but only if it's the first char)
1351 if ( !strExt.empty() ) {
1352 strExt += wxT('.');
1353 }
1354 //else: no, don't append it
1355 }
1356 else {
1357 strExt += *p;
1358 }
1359 }
1360
1361 return TRUE;
1362 }
1363
1364 // set an arbitrary command,
1365 // could adjust the code to ask confirmation if it already exists and
1366 // overwriteprompt is TRUE, but this is currently ignored as *Associate* has
1367 // no overwrite prompt
1368 bool wxFileTypeImpl::SetCommand(const wxString& cmd, const wxString& verb, bool overwriteprompt /*= TRUE*/)
1369 {
1370 wxArrayString strExtensions;
1371 wxString strDesc, strIcon;
1372
1373 wxMimeTypeCommands *entry = new wxMimeTypeCommands ();
1374 entry->Add(verb + wxT("=") + cmd + wxT(" %s "));
1375
1376 wxArrayString strTypes;
1377 GetMimeTypes (strTypes);
1378 if (strTypes.GetCount() < 1) return FALSE;
1379
1380 size_t i;
1381 bool Ok = TRUE;
1382 for (i = 0; i < strTypes.GetCount(); i++)
1383 {
1384 if (!m_manager->DoAssociation (strTypes[i], strIcon, entry, strExtensions, strDesc))
1385 Ok = FALSE;
1386 }
1387
1388 return Ok;
1389 }
1390
1391 // ignore index on the grouds that we only have one icon in a Unix file
1392 bool wxFileTypeImpl::SetDefaultIcon(const wxString& strIcon /*= wxEmptyString*/, int /*index = 0*/)
1393 {
1394 if (strIcon.empty()) return FALSE;
1395 wxArrayString strExtensions;
1396 wxString strDesc;
1397
1398 wxMimeTypeCommands *entry = new wxMimeTypeCommands ();
1399
1400 wxArrayString strTypes;
1401 GetMimeTypes (strTypes);
1402 if (strTypes.GetCount() < 1) return FALSE;
1403
1404 size_t i;
1405 bool Ok = TRUE;
1406 for (i = 0; i < strTypes.GetCount(); i++)
1407 {
1408 if (!m_manager->DoAssociation (strTypes[i], strIcon, entry, strExtensions, strDesc))
1409 Ok = FALSE;
1410 }
1411
1412 return Ok;
1413 }
1414
1415 // ----------------------------------------------------------------------------
1416 // wxMimeTypesManagerImpl (Unix)
1417 // ----------------------------------------------------------------------------
1418
1419
1420 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1421 {
1422 m_initialized = FALSE;
1423 m_mailcapStylesInited = 0;
1424 }
1425
1426 void wxMimeTypesManagerImpl::InitIfNeeded()
1427 {
1428 if ( !m_initialized )
1429 {
1430 // set the flag first to prevent recursion
1431 m_initialized = TRUE;
1432
1433 #if 0
1434 wxString wm = wxGetenv( wxT("WINDOWMANAGER") );
1435
1436 if (wm.Find( wxT("kde") ) != wxNOT_FOUND)
1437 Initialize( wxMAILCAP_KDE|wxMAILCAP_STANDARD );
1438 else if (wm.Find( wxT("gnome") ) != wxNOT_FOUND)
1439 Initialize( wxMAILCAP_GNOME|wxMAILCAP_STANDARD );
1440 else
1441 #endif
1442 Initialize();
1443 }
1444 }
1445
1446 // read system and user mailcaps and other files
1447 void wxMimeTypesManagerImpl::Initialize(int mailcapStyles,
1448 const wxString& sExtraDir)
1449 {
1450 // read mimecap amd mime.types
1451 if ( (mailcapStyles & wxMAILCAP_NETSCAPE) ||
1452 (mailcapStyles & wxMAILCAP_STANDARD) )
1453 GetMimeInfo(sExtraDir);
1454
1455 // read GNOME tables
1456 if (mailcapStyles & wxMAILCAP_GNOME)
1457 GetGnomeMimeInfo(sExtraDir);
1458
1459 // read KDE tables
1460 if (mailcapStyles & wxMAILCAP_KDE)
1461 GetKDEMimeInfo(sExtraDir);
1462
1463 m_mailcapStylesInited |= mailcapStyles;
1464 }
1465
1466 // clear data so you can read another group of WM files
1467 void wxMimeTypesManagerImpl::ClearData()
1468 {
1469 m_aTypes.Clear ();
1470 m_aIcons.Clear ();
1471 m_aExtensions.Clear ();
1472 m_aDescriptions.Clear ();
1473
1474 WX_CLEAR_ARRAY(m_aEntries);
1475 m_aEntries.Empty();
1476
1477 m_mailcapStylesInited = 0;
1478 }
1479
1480 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
1481 {
1482 ClearData();
1483 }
1484
1485
1486 void wxMimeTypesManagerImpl::GetMimeInfo (const wxString& sExtraDir)
1487 {
1488 // read this for netscape or Metamail formats
1489
1490 // directories where we look for mailcap and mime.types by default
1491 // used by netscape and pine and other mailers, using 2 different formats!
1492
1493 // (taken from metamail(1) sources)
1494 //
1495 // although RFC 1524 specifies the search path of
1496 // /etc/:/usr/etc:/usr/local/etc only, it doesn't hurt to search in more
1497 // places - OTOH, the RFC also says that this path can be changed with
1498 // MAILCAPS environment variable (containing the colon separated full
1499 // filenames to try) which is not done yet (TODO?)
1500
1501 wxString strHome = wxGetenv(wxT("HOME"));
1502
1503 wxArrayString dirs;
1504 dirs.Add ( strHome + wxT("/.") );
1505 dirs.Add ( wxT("/etc/") );
1506 dirs.Add ( wxT("/usr/etc/") );
1507 dirs.Add ( wxT("/usr/local/etc/") );
1508 dirs.Add ( wxT("/etc/mail/") );
1509 dirs.Add ( wxT("/usr/public/lib/") );
1510 if (!sExtraDir.empty()) dirs.Add ( sExtraDir + wxT("/") );
1511
1512 size_t nDirs = dirs.GetCount();
1513 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
1514 {
1515 wxString file = dirs[nDir] + wxT("mailcap");
1516 if ( wxFile::Exists(file) ) {
1517 ReadMailcap(file);
1518 }
1519
1520 file = dirs[nDir] + wxT("mime.types");
1521 if ( wxFile::Exists(file) ) {
1522 ReadMimeTypes(file);
1523 }
1524 }
1525
1526 }
1527
1528 bool wxMimeTypesManagerImpl::WriteToMimeTypes (int index, bool delete_index)
1529 {
1530 // check we have the right manager
1531 if (! ( m_mailcapStylesInited & wxMAILCAP_STANDARD) )
1532 return FALSE;
1533
1534 bool bTemp;
1535 wxString strHome = wxGetenv(wxT("HOME"));
1536
1537 // and now the users mailcap
1538 wxString strUserMailcap = strHome + wxT("/.mime.types");
1539
1540 wxMimeTextFile file;
1541 if ( wxFile::Exists(strUserMailcap) )
1542 {
1543 bTemp = file.Open(strUserMailcap);
1544 }
1545 else
1546 {
1547 if (delete_index) return FALSE;
1548 bTemp = file.Create(strUserMailcap);
1549 }
1550 if (bTemp)
1551 {
1552 int nIndex;
1553 // test for netscape's header and return FALSE if its found
1554 nIndex = file.pIndexOf (wxT("#--Netscape"));
1555 if (nIndex != wxNOT_FOUND)
1556 {
1557 wxASSERT_MSG(FALSE,wxT("Error in .mime.types \nTrying to mix Netscape and Metamail formats\nFile not modiifed"));
1558 return FALSE;
1559 }
1560 // write it in alternative format
1561 // get rid of unwanted entries
1562 wxString strType = m_aTypes[index];
1563 nIndex = file.pIndexOf (strType);
1564 // get rid of all the unwanted entries...
1565 if (nIndex != wxNOT_FOUND) file.CommentLine (nIndex);
1566
1567 if (!delete_index)
1568 {
1569 // add the new entries in
1570 wxString sTmp = strType.Append (wxT(' '), 40-strType.Len() );
1571 sTmp = sTmp + m_aExtensions[index];
1572 file.AddLine (sTmp);
1573 }
1574
1575
1576 bTemp = file.Write ();
1577 file.Close ();
1578 }
1579 return bTemp;
1580 }
1581
1582 bool wxMimeTypesManagerImpl::WriteToNSMimeTypes (int index, bool delete_index)
1583 {
1584 //check we have the right managers
1585 if (! ( m_mailcapStylesInited & wxMAILCAP_NETSCAPE) )
1586 return FALSE;
1587
1588 bool bTemp;
1589 wxString strHome = wxGetenv(wxT("HOME"));
1590
1591 // and now the users mailcap
1592 wxString strUserMailcap = strHome + wxT("/.mime.types");
1593
1594 wxMimeTextFile file;
1595 if ( wxFile::Exists(strUserMailcap) )
1596 {
1597 bTemp = file.Open(strUserMailcap);
1598 }
1599 else
1600 {
1601 if (delete_index) return FALSE;
1602 bTemp = file.Create(strUserMailcap);
1603 }
1604 if (bTemp)
1605 {
1606
1607 // write it in the format that Netscape uses
1608 int nIndex;
1609 // test for netscape's header and insert if required...
1610 // this is a comment so use TRUE
1611 nIndex = file.pIndexOf (wxT("#--Netscape"), TRUE);
1612 if (nIndex == wxNOT_FOUND)
1613 {
1614 // either empty file or metamail format
1615 // at present we can't cope with mixed formats, so exit to preseve
1616 // metamail entreies
1617 if (file.GetLineCount () > 0)
1618 {
1619 wxASSERT_MSG(FALSE, wxT(".mime.types File not in Netscape format\nNo entries written to\n.mime.types or to .mailcap"));
1620 return FALSE;
1621 }
1622 file.InsertLine (wxT( "#--Netscape Communications Corporation MIME Information" ), 0);
1623 nIndex = 0;
1624 }
1625
1626 wxString strType = wxT("type=") + m_aTypes[index];
1627 nIndex = file.pIndexOf (strType);
1628 // get rid of all the unwanted entries...
1629 if (nIndex != wxNOT_FOUND)
1630 {
1631 wxString sOld = file[nIndex];
1632 while ( (sOld.Contains(wxT("\\"))) && (nIndex < (int) file.GetLineCount()) )
1633 {
1634 file.CommentLine(nIndex);
1635 sOld = file[nIndex];
1636 wxLogTrace(TRACE_MIME, wxT("--- Deleting from mime.types line '%d %s' ---"), nIndex, sOld.c_str());
1637 nIndex ++;
1638 }
1639 if (nIndex < (int) file.GetLineCount()) file.CommentLine (nIndex);
1640 }
1641 else nIndex = (int) file.GetLineCount();
1642
1643 wxString sTmp = strType + wxT(" \\");
1644 if (!delete_index) file.InsertLine (sTmp, nIndex);
1645 if ( ! m_aDescriptions.Item(index).empty() )
1646 {
1647 sTmp = wxT("desc=\"") + m_aDescriptions[index]+ wxT("\" \\"); //.trim ??
1648 if (!delete_index)
1649 {
1650 nIndex ++;
1651 file.InsertLine (sTmp, nIndex);
1652 }
1653 }
1654 wxString sExts = m_aExtensions.Item(index);
1655 sTmp = wxT("exts=\"") + sExts.Trim(FALSE).Trim() + wxT("\"");
1656 if (!delete_index)
1657 {
1658 nIndex ++;
1659 file.InsertLine (sTmp, nIndex);
1660 }
1661
1662 bTemp = file.Write ();
1663 file.Close ();
1664 }
1665 return bTemp;
1666 }
1667
1668
1669 bool wxMimeTypesManagerImpl::WriteToMailCap (int index, bool delete_index)
1670 {
1671 //check we have the right managers
1672 if ( !( ( m_mailcapStylesInited & wxMAILCAP_NETSCAPE) ||
1673 ( m_mailcapStylesInited & wxMAILCAP_STANDARD) ) )
1674 return FALSE;
1675
1676 bool bTemp;
1677 wxString strHome = wxGetenv(wxT("HOME"));
1678
1679 // and now the users mailcap
1680 wxString strUserMailcap = strHome + wxT("/.mailcap");
1681
1682 wxMimeTextFile file;
1683 if ( wxFile::Exists(strUserMailcap) )
1684 {
1685 bTemp = file.Open(strUserMailcap);
1686 }
1687 else
1688 {
1689 if (delete_index) return FALSE;
1690 bTemp = file.Create(strUserMailcap);
1691 }
1692 if (bTemp)
1693 {
1694 // now got a file we can write to ....
1695 wxMimeTypeCommands * entries = m_aEntries[index];
1696 size_t iOpen;
1697 wxString sCmd = entries->GetCommandForVerb(_T("open"), &iOpen);
1698 wxString sTmp;
1699
1700 sTmp = m_aTypes[index];
1701 wxString sOld;
1702 int nIndex = file.pIndexOf(sTmp);
1703 // get rid of all the unwanted entries...
1704 if (nIndex == wxNOT_FOUND)
1705 {
1706 nIndex = (int) file.GetLineCount();
1707 }
1708 else
1709 {
1710 sOld = file[nIndex];
1711 wxLogTrace(TRACE_MIME, wxT("--- Deleting from mailcap line '%d' ---"), nIndex);
1712
1713 while ( (sOld.Contains(wxT("\\"))) && (nIndex < (int) file.GetLineCount()) )
1714 {
1715 file.CommentLine(nIndex);
1716 if (nIndex < (int) file.GetLineCount()) sOld = sOld + file[nIndex];
1717 }
1718 if (nIndex < (int) file.GetLineCount()) file.CommentLine (nIndex);
1719 }
1720
1721 sTmp = sTmp + wxT(";") + sCmd; //includes wxT(" %s ");
1722
1723 // write it in the format that Netscape uses (default)
1724 if (! ( m_mailcapStylesInited & wxMAILCAP_STANDARD ) )
1725 {
1726 if (! delete_index) file.InsertLine (sTmp, nIndex);
1727 nIndex ++;
1728 }
1729
1730 // write extended format
1731 else
1732 {
1733 // todo FIX this code;
1734 // ii) lost entries
1735 // sOld holds all the entries, but our data store only has some
1736 // eg test= is not stored
1737
1738 // so far we have written the mimetype and command out
1739 wxStringTokenizer sT (sOld, wxT(";\\"));
1740 if (sT.CountTokens () > 2)
1741 {
1742 // first one mimetype; second one command, rest unknown...
1743 wxString s;
1744 s = sT.GetNextToken();
1745 s = sT.GetNextToken();
1746
1747 // first unknown
1748 s = sT.GetNextToken();
1749 while ( ! s.empty() )
1750 {
1751 bool bKnownToken = FALSE;
1752 if (s.Contains(wxT("description="))) bKnownToken = TRUE;
1753 if (s.Contains(wxT("x11-bitmap="))) bKnownToken = TRUE;
1754 size_t i;
1755 for (i=0; i < entries->GetCount(); i++)
1756 {
1757 if (s.Contains(entries->GetVerb(i))) bKnownToken = TRUE;
1758 }
1759 if (!bKnownToken)
1760 {
1761 sTmp = sTmp + wxT("; \\");
1762 file.InsertLine (sTmp, nIndex);
1763 sTmp = s;
1764 }
1765 s = sT.GetNextToken ();
1766 }
1767
1768 }
1769
1770 if (! m_aDescriptions[index].empty() )
1771 {
1772 sTmp = sTmp + wxT("; \\");
1773 file.InsertLine (sTmp, nIndex);
1774 nIndex ++;
1775 sTmp = wxT(" description=\"") + m_aDescriptions[index] + wxT("\"");
1776 }
1777
1778 if (! m_aIcons[index].empty() )
1779 {
1780 sTmp = sTmp + wxT("; \\");
1781 file.InsertLine (sTmp, nIndex);
1782 nIndex ++;
1783 sTmp = wxT(" x11-bitmap=\"") + m_aIcons[index] + wxT("\"");
1784 }
1785 if ( entries->GetCount() > 1 )
1786
1787 {
1788 size_t i;
1789 for (i=0; i < entries->GetCount(); i++)
1790 if ( i != iOpen )
1791 {
1792 sTmp = sTmp + wxT("; \\");
1793 file.InsertLine (sTmp, nIndex);
1794 nIndex ++;
1795 sTmp = wxT(" ") + entries->GetVerbCmd(i);
1796 }
1797 }
1798
1799 file.InsertLine (sTmp, nIndex);
1800 nIndex ++;
1801
1802 }
1803 bTemp = file.Write ();
1804 file.Close ();
1805 }
1806 return bTemp;
1807 }
1808
1809 wxFileType *
1810 wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo& ftInfo)
1811 {
1812 InitIfNeeded();
1813
1814 wxString strType = ftInfo.GetMimeType ();
1815 wxString strDesc = ftInfo.GetDescription ();
1816 wxString strIcon = ftInfo.GetIconFile ();
1817
1818 wxMimeTypeCommands *entry = new wxMimeTypeCommands ();
1819
1820 if ( ! ftInfo.GetOpenCommand().empty())
1821 entry->Add(wxT("open=") + ftInfo.GetOpenCommand () + wxT(" %s "));
1822 if ( ! ftInfo.GetPrintCommand ().empty())
1823 entry->Add(wxT("print=") + ftInfo.GetPrintCommand () + wxT(" %s "));
1824
1825 // now find where these extensions are in the data store and remove them
1826 wxArrayString sA_Exts = ftInfo.GetExtensions ();
1827 wxString sExt, sExtStore;
1828 size_t i, nIndex;
1829 for (i=0; i < sA_Exts.GetCount(); i++)
1830 {
1831 sExt = sA_Exts.Item(i);
1832 //clean up to just a space before and after
1833 sExt.Trim().Trim(FALSE);
1834 sExt = wxT(' ') + sExt + wxT(' ');
1835 for (nIndex = 0; nIndex < m_aExtensions.GetCount(); nIndex ++)
1836 {
1837 sExtStore = m_aExtensions.Item(nIndex);
1838 if (sExtStore.Replace(sExt, wxT(" ") ) > 0) m_aExtensions.Item(nIndex) = sExtStore;
1839 }
1840
1841 }
1842
1843 if ( !DoAssociation (strType, strIcon, entry, sA_Exts, strDesc) )
1844 return NULL;
1845
1846 return GetFileTypeFromMimeType(strType);
1847 }
1848
1849
1850 bool wxMimeTypesManagerImpl::DoAssociation(const wxString& strType,
1851 const wxString& strIcon,
1852 wxMimeTypeCommands *entry,
1853 const wxArrayString& strExtensions,
1854 const wxString& strDesc)
1855 {
1856 int nIndex = AddToMimeData(strType, strIcon, entry, strExtensions, strDesc, TRUE);
1857
1858 if ( nIndex == wxNOT_FOUND )
1859 return FALSE;
1860
1861 return WriteMimeInfo (nIndex, FALSE);
1862 }
1863
1864 bool wxMimeTypesManagerImpl::WriteMimeInfo(int nIndex, bool delete_mime )
1865 {
1866 bool ok = TRUE;
1867
1868 if ( m_mailcapStylesInited & wxMAILCAP_STANDARD )
1869 {
1870 // write in metamail format;
1871 if (WriteToMimeTypes (nIndex, delete_mime) )
1872 if ( WriteToMailCap (nIndex, delete_mime) )
1873 ok = FALSE;
1874 }
1875 if ( m_mailcapStylesInited & wxMAILCAP_NETSCAPE )
1876 {
1877 // write in netsacpe format;
1878 if (WriteToNSMimeTypes (nIndex, delete_mime) )
1879 if ( WriteToMailCap (nIndex, delete_mime) )
1880 ok = FALSE;
1881 }
1882 if (m_mailcapStylesInited & wxMAILCAP_GNOME)
1883 {
1884 // write in Gnome format;
1885 if (WriteGnomeMimeFile (nIndex, delete_mime) )
1886 if (WriteGnomeKeyFile (nIndex, delete_mime) )
1887 ok = FALSE;
1888 }
1889 if (m_mailcapStylesInited & wxMAILCAP_KDE)
1890 {
1891 // write in KDE format;
1892 if (WriteKDEMimeFile (nIndex, delete_mime) )
1893 ok = FALSE;
1894 }
1895
1896 return ok;
1897 }
1898
1899 int wxMimeTypesManagerImpl::AddToMimeData(const wxString& strType,
1900 const wxString& strIcon,
1901 wxMimeTypeCommands *entry,
1902 const wxArrayString& strExtensions,
1903 const wxString& strDesc,
1904 bool replaceExisting)
1905 {
1906 InitIfNeeded();
1907
1908 // ensure mimetype is always lower case
1909 wxString mimeType = strType.Lower();
1910
1911 // is this a known MIME type?
1912 int nIndex = m_aTypes.Index(mimeType);
1913 if ( nIndex == wxNOT_FOUND )
1914 {
1915 // new file type
1916 m_aTypes.Add(mimeType);
1917 m_aIcons.Add(strIcon);
1918 m_aEntries.Add(entry ? entry : new wxMimeTypeCommands);
1919
1920 // change nIndex so we can use it below to add the extensions
1921 m_aExtensions.Add(wxEmptyString);
1922 nIndex = m_aExtensions.size() - 1;
1923
1924 m_aDescriptions.Add(strDesc);
1925 }
1926 else // yes, we already have it
1927 {
1928 if ( replaceExisting )
1929 {
1930 // if new description change it
1931 if ( !strDesc.empty())
1932 m_aDescriptions[nIndex] = strDesc;
1933
1934 // if new icon change it
1935 if ( !strIcon.empty())
1936 m_aIcons[nIndex] = strIcon;
1937
1938 if ( entry )
1939 {
1940 delete m_aEntries[nIndex];
1941 m_aEntries[nIndex] = entry;
1942 }
1943 }
1944 else // add data we don't already have ...
1945 {
1946 // if new description add only if none
1947 if ( m_aDescriptions[nIndex].empty() )
1948 m_aDescriptions[nIndex] = strDesc;
1949
1950 // if new icon and no existing icon
1951 if ( m_aIcons[nIndex].empty () )
1952 m_aIcons[nIndex] = strIcon;
1953
1954 // add any new entries...
1955 if ( entry )
1956 {
1957 wxMimeTypeCommands *entryOld = m_aEntries[nIndex];
1958
1959 size_t count = entry->GetCount();
1960 for ( size_t i = 0; i < count; i++ )
1961 {
1962 const wxString& verb = entry->GetVerb(i);
1963 if ( !entryOld->HasVerb(verb) )
1964 {
1965 entryOld->AddOrReplaceVerb(verb, entry->GetCmd(i));
1966 }
1967 }
1968
1969 // as we don't store it anywhere, it won't be deleted later as
1970 // usual -- do it immediately instead
1971 delete entry;
1972 }
1973 }
1974 }
1975
1976 // always add the extensions to this mimetype
1977 wxString& exts = m_aExtensions[nIndex];
1978
1979 // add all extensions we don't have yet
1980 size_t count = strExtensions.GetCount();
1981 for ( size_t i = 0; i < count; i++ )
1982 {
1983 wxString ext = strExtensions[i] + _T(' ');
1984
1985 if ( exts.Find(ext) == wxNOT_FOUND )
1986 {
1987 exts += ext;
1988 }
1989 }
1990
1991 // check data integrity
1992 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
1993 m_aTypes.Count() == m_aExtensions.Count() &&
1994 m_aTypes.Count() == m_aIcons.Count() &&
1995 m_aTypes.Count() == m_aDescriptions.Count() );
1996
1997 return nIndex;
1998 }
1999
2000
2001 wxFileType *
2002 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
2003 {
2004 if (ext.empty() )
2005 return NULL;
2006
2007 InitIfNeeded();
2008
2009 size_t count = m_aExtensions.GetCount();
2010 for ( size_t n = 0; n < count; n++ )
2011 {
2012 wxStringTokenizer tk(m_aExtensions[n], _T(' '));
2013
2014 while ( tk.HasMoreTokens() )
2015 {
2016 // consider extensions as not being case-sensitive
2017 if ( tk.GetNextToken().IsSameAs(ext, FALSE /* no case */) )
2018 {
2019 // found
2020 wxFileType *fileType = new wxFileType;
2021 fileType->m_impl->Init(this, n);
2022
2023 return fileType;
2024 }
2025 }
2026 }
2027
2028 return NULL;
2029 }
2030
2031 wxFileType *
2032 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
2033 {
2034 InitIfNeeded();
2035
2036 wxFileType * fileType = NULL;
2037 // mime types are not case-sensitive
2038 wxString mimetype(mimeType);
2039 mimetype.MakeLower();
2040
2041 // first look for an exact match
2042 int index = m_aTypes.Index(mimetype);
2043 if ( index != wxNOT_FOUND )
2044 {
2045 fileType = new wxFileType;
2046 fileType->m_impl->Init(this, index);
2047 }
2048
2049 // then try to find "text/*" as match for "text/plain" (for example)
2050 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
2051 // the whole string - ok.
2052
2053 index = wxNOT_FOUND;
2054 wxString strCategory = mimetype.BeforeFirst(wxT('/'));
2055
2056 size_t nCount = m_aTypes.Count();
2057 for ( size_t n = 0; n < nCount; n++ ) {
2058 if ( (m_aTypes[n].BeforeFirst(wxT('/')) == strCategory ) &&
2059 m_aTypes[n].AfterFirst(wxT('/')) == wxT("*") ) {
2060 index = n;
2061 break;
2062 }
2063
2064 }
2065
2066 if ( index != wxNOT_FOUND )
2067 {
2068 fileType = new wxFileType;
2069 fileType->m_impl->Init(this, index);
2070 }
2071 return fileType;
2072 }
2073
2074
2075 wxString wxMimeTypesManagerImpl::GetCommand(const wxString & verb, size_t nIndex) const
2076 {
2077 wxString command, testcmd, sV, sTmp;
2078 sV = verb + wxT("=");
2079 // list of verb = command pairs for this mimetype
2080 wxMimeTypeCommands * sPairs = m_aEntries [nIndex];
2081
2082 size_t i;
2083 for ( i = 0; i < sPairs->GetCount (); i++ )
2084 {
2085 sTmp = sPairs->GetVerbCmd (i);
2086 if ( sTmp.Contains(sV) )
2087 command = sTmp.AfterFirst(wxT('='));
2088 }
2089 return command;
2090 }
2091
2092 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
2093 {
2094 InitIfNeeded();
2095
2096 wxString extensions;
2097 const wxArrayString& exts = filetype.GetExtensions();
2098 size_t nExts = exts.GetCount();
2099 for ( size_t nExt = 0; nExt < nExts; nExt++ ) {
2100 if ( nExt > 0 ) {
2101 extensions += wxT(' ');
2102 }
2103 extensions += exts[nExt];
2104 }
2105
2106 AddMimeTypeInfo(filetype.GetMimeType(),
2107 extensions,
2108 filetype.GetDescription());
2109
2110 AddMailcapInfo(filetype.GetMimeType(),
2111 filetype.GetOpenCommand(),
2112 filetype.GetPrintCommand(),
2113 wxT(""),
2114 filetype.GetDescription());
2115 }
2116
2117 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString& strMimeType,
2118 const wxString& strExtensions,
2119 const wxString& strDesc)
2120 {
2121 // reading mailcap may find image/* , while
2122 // reading mime.types finds image/gif and no match is made
2123 // this means all the get functions don't work fix this
2124 wxString strIcon;
2125 wxString sTmp = strExtensions;
2126
2127 wxArrayString sExts;
2128 sTmp.Trim().Trim(FALSE);
2129
2130 while (!sTmp.empty())
2131 {
2132 sExts.Add (sTmp.AfterLast(wxT(' ')));
2133 sTmp = sTmp.BeforeLast(wxT(' '));
2134 }
2135
2136 AddToMimeData (strMimeType, strIcon, NULL, sExts, strDesc, TRUE);
2137 }
2138
2139 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString& strType,
2140 const wxString& strOpenCmd,
2141 const wxString& strPrintCmd,
2142 const wxString& strTest,
2143 const wxString& strDesc)
2144 {
2145 InitIfNeeded();
2146
2147 wxMimeTypeCommands *entry = new wxMimeTypeCommands;
2148 entry->Add(wxT("open=") + strOpenCmd);
2149 entry->Add(wxT("print=") + strPrintCmd);
2150 entry->Add(wxT("test=") + strTest);
2151
2152 wxString strIcon;
2153 wxArrayString strExtensions;
2154
2155 AddToMimeData (strType, strIcon, entry, strExtensions, strDesc, TRUE);
2156
2157 }
2158
2159 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString& strFileName)
2160 {
2161 wxLogTrace(TRACE_MIME, wxT("--- Parsing mime.types file '%s' ---"),
2162 strFileName.c_str());
2163
2164 wxTextFile file(strFileName);
2165 #if defined(__WXGTK20__) && wxUSE_UNICODE
2166 if ( !file.Open( wxConvUTF8) )
2167 #else
2168 if ( !file.Open() )
2169 #endif
2170 return FALSE;
2171
2172 // the information we extract
2173 wxString strMimeType, strDesc, strExtensions;
2174
2175 size_t nLineCount = file.GetLineCount();
2176 const wxChar *pc = NULL;
2177 for ( size_t nLine = 0; nLine < nLineCount; nLine++ )
2178 {
2179 if ( pc == NULL ) {
2180 // now we're at the start of the line
2181 pc = file[nLine].c_str();
2182 }
2183 else {
2184 // we didn't finish with the previous line yet
2185 nLine--;
2186 }
2187
2188 // skip whitespace
2189 while ( wxIsspace(*pc) )
2190 pc++;
2191
2192 // comment or blank line?
2193 if ( *pc == wxT('#') || !*pc ) {
2194 // skip the whole line
2195 pc = NULL;
2196 continue;
2197 }
2198
2199 // detect file format
2200 const wxChar *pEqualSign = wxStrchr(pc, wxT('='));
2201 if ( pEqualSign == NULL ) {
2202 // brief format
2203 // ------------
2204
2205 // first field is mime type
2206 for ( strMimeType.Empty(); !wxIsspace(*pc) && *pc != wxT('\0'); pc++ ) {
2207 strMimeType += *pc;
2208 }
2209
2210 // skip whitespace
2211 while ( wxIsspace(*pc) )
2212 pc++;
2213
2214 // take all the rest of the string
2215 strExtensions = pc;
2216
2217 // no description...
2218 strDesc.Empty();
2219 }
2220 else {
2221 // expanded format
2222 // ---------------
2223
2224 // the string on the left of '=' is the field name
2225 wxString strLHS(pc, pEqualSign - pc);
2226
2227 // eat whitespace
2228 for ( pc = pEqualSign + 1; wxIsspace(*pc); pc++ )
2229 ;
2230
2231 const wxChar *pEnd;
2232 if ( *pc == wxT('"') ) {
2233 // the string is quoted and ends at the matching quote
2234 pEnd = wxStrchr(++pc, wxT('"'));
2235 if ( pEnd == NULL ) {
2236 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
2237 "quoted string."),
2238 strFileName.c_str(), nLine + 1);
2239 }
2240 }
2241 else {
2242 // unquoted string ends at the first space or at the end of
2243 // line
2244 for ( pEnd = pc; *pEnd && !wxIsspace(*pEnd); pEnd++ )
2245 ;
2246 }
2247
2248 // now we have the RHS (field value)
2249 wxString strRHS(pc, pEnd - pc);
2250
2251 // check what follows this entry
2252 if ( *pEnd == wxT('"') ) {
2253 // skip this quote
2254 pEnd++;
2255 }
2256
2257 for ( pc = pEnd; wxIsspace(*pc); pc++ )
2258 ;
2259
2260 // if there is something left, it may be either a '\\' to continue
2261 // the line or the next field of the same entry
2262 bool entryEnded = *pc == wxT('\0'),
2263 nextFieldOnSameLine = FALSE;
2264 if ( !entryEnded ) {
2265 nextFieldOnSameLine = ((*pc != wxT('\\')) || (pc[1] != wxT('\0')));
2266 }
2267
2268 // now see what we got
2269 if ( strLHS == wxT("type") ) {
2270 strMimeType = strRHS;
2271 }
2272 else if ( strLHS.StartsWith(wxT("desc")) ) {
2273 strDesc = strRHS;
2274 }
2275 else if ( strLHS == wxT("exts") ) {
2276 strExtensions = strRHS;
2277 }
2278 else if ( strLHS == _T("icon") )
2279 {
2280 // this one is simply ignored: it usually refers to Netscape
2281 // built in icons which are useless for us anyhow
2282 }
2283 else if ( !strLHS.StartsWith(_T("x-")) )
2284 {
2285 // we suppose that all fields starting with "X-" are
2286 // unregistered extensions according to the standard practice,
2287 // but it may be worth telling the user about other junk in
2288 // his mime.types file
2289 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
2290 strFileName.c_str(), nLine + 1, strLHS.c_str());
2291 }
2292
2293 if ( !entryEnded ) {
2294 if ( !nextFieldOnSameLine )
2295 pc = NULL;
2296 //else: don't reset it
2297
2298 // as we don't reset strMimeType, the next field in this entry
2299 // will be interpreted correctly.
2300
2301 continue;
2302 }
2303 }
2304
2305 // depending on the format (Mosaic or Netscape) either space or comma
2306 // is used to separate the extensions
2307 strExtensions.Replace(wxT(","), wxT(" "));
2308
2309 // also deal with the leading dot
2310 if ( !strExtensions.empty() && strExtensions[0u] == wxT('.') )
2311 {
2312 strExtensions.erase(0, 1);
2313 }
2314
2315 wxLogTrace(TRACE_MIME, wxT("mime.types: '%s' => '%s' (%s)"),
2316 strExtensions.c_str(),
2317 strMimeType.c_str(),
2318 strDesc.c_str());
2319
2320 AddMimeTypeInfo(strMimeType, strExtensions, strDesc);
2321
2322 // finished with this line
2323 pc = NULL;
2324 }
2325
2326 return TRUE;
2327 }
2328
2329 // ----------------------------------------------------------------------------
2330 // UNIX mailcap files parsing
2331 // ----------------------------------------------------------------------------
2332
2333 // the data for a single MIME type
2334 struct MailcapLineData
2335 {
2336 // field values
2337 wxString type,
2338 cmdOpen,
2339 test,
2340 icon,
2341 desc;
2342
2343 wxArrayString verbs,
2344 commands;
2345
2346 // flags
2347 bool testfailed,
2348 needsterminal,
2349 copiousoutput;
2350
2351 MailcapLineData() { testfailed = needsterminal = copiousoutput = FALSE; }
2352 };
2353
2354 // process a non-standard (i.e. not the first or second one) mailcap field
2355 bool
2356 wxMimeTypesManagerImpl::ProcessOtherMailcapField(MailcapLineData& data,
2357 const wxString& curField)
2358 {
2359 if ( curField.empty() )
2360 {
2361 // we don't care
2362 return TRUE;
2363 }
2364
2365 // is this something of the form foo=bar?
2366 const wxChar *pEq = wxStrchr(curField, wxT('='));
2367 if ( pEq != NULL )
2368 {
2369 // split "LHS = RHS" in 2
2370 wxString lhs = curField.BeforeFirst(wxT('=')),
2371 rhs = curField.AfterFirst(wxT('='));
2372
2373 lhs.Trim(TRUE); // from right
2374 rhs.Trim(FALSE); // from left
2375
2376 // it might be quoted
2377 if ( !rhs.empty() && rhs[0u] == wxT('"') && rhs.Last() == wxT('"') )
2378 {
2379 rhs = rhs.Mid(1, rhs.length() - 2);
2380 }
2381
2382 // is it a command verb or something else?
2383 if ( lhs == wxT("test") )
2384 {
2385 if ( wxSystem(rhs) == 0 )
2386 {
2387 // ok, test passed
2388 wxLogTrace(TRACE_MIME_TEST,
2389 wxT("Test '%s' for mime type '%s' succeeded."),
2390 rhs.c_str(), data.type.c_str());
2391
2392 }
2393 else
2394 {
2395 wxLogTrace(TRACE_MIME_TEST,
2396 wxT("Test '%s' for mime type '%s' failed, skipping."),
2397 rhs.c_str(), data.type.c_str());
2398
2399 data.testfailed = TRUE;
2400 }
2401 }
2402 else if ( lhs == wxT("desc") )
2403 {
2404 data.desc = rhs;
2405 }
2406 else if ( lhs == wxT("x11-bitmap") )
2407 {
2408 data.icon = rhs;
2409 }
2410 else if ( lhs == wxT("notes") )
2411 {
2412 // ignore
2413 }
2414 else // not a (recognized) special case, must be a verb (e.g. "print")
2415 {
2416 data.verbs.Add(lhs);
2417 data.commands.Add(rhs);
2418 }
2419 }
2420 else // '=' not found
2421 {
2422 // so it must be a simple flag
2423 if ( curField == wxT("needsterminal") )
2424 {
2425 data.needsterminal = TRUE;
2426 }
2427 else if ( curField == wxT("copiousoutput"))
2428 {
2429 // copiousoutput impies that the viewer is a console program
2430 data.needsterminal =
2431 data.copiousoutput = TRUE;
2432 }
2433 else if ( !IsKnownUnimportantField(curField) )
2434 {
2435 return FALSE;
2436 }
2437 }
2438
2439 return TRUE;
2440 }
2441
2442 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString& strFileName,
2443 bool fallback)
2444 {
2445 wxLogTrace(TRACE_MIME, wxT("--- Parsing mailcap file '%s' ---"),
2446 strFileName.c_str());
2447
2448 wxTextFile file(strFileName);
2449 #if defined(__WXGTK20__) && wxUSE_UNICODE
2450 if ( !file.Open( wxConvUTF8) )
2451 #else
2452 if ( !file.Open() )
2453 #endif
2454 return FALSE;
2455
2456 // indices of MIME types (in m_aTypes) we already found in this file
2457 //
2458 // (see the comments near the end of function for the reason we need this)
2459 wxArrayInt aIndicesSeenHere;
2460
2461 // accumulator for the current field
2462 wxString curField;
2463 curField.reserve(1024);
2464
2465 size_t nLineCount = file.GetLineCount();
2466 for ( size_t nLine = 0; nLine < nLineCount; nLine++ )
2467 {
2468 // now we're at the start of the line
2469 const wxChar *pc = file[nLine].c_str();
2470
2471 // skip whitespace
2472 while ( wxIsspace(*pc) )
2473 pc++;
2474
2475 // comment or empty string?
2476 if ( *pc == wxT('#') || *pc == wxT('\0') )
2477 continue;
2478
2479 // no, do parse
2480 // ------------
2481
2482 // what field are we currently in? The first 2 are fixed and there may
2483 // be an arbitrary number of other fields parsed by
2484 // ProcessOtherMailcapField()
2485 //
2486 // the first field is the MIME type
2487 enum
2488 {
2489 Field_Type,
2490 Field_OpenCmd,
2491 Field_Other
2492 } currentToken = Field_Type;
2493
2494 // the flags and field values on the current line
2495 MailcapLineData data;
2496
2497 bool cont = TRUE;
2498 while ( cont )
2499 {
2500 switch ( *pc )
2501 {
2502 case wxT('\\'):
2503 // interpret the next character literally (notice that
2504 // backslash can be used for line continuation)
2505 if ( *++pc == wxT('\0') )
2506 {
2507 // fetch the next line if there is one
2508 if ( nLine == nLineCount - 1 )
2509 {
2510 // something is wrong, bail out
2511 cont = FALSE;
2512
2513 wxLogDebug(wxT("Mailcap file %s, line %lu: "
2514 "'\\' on the end of the last line "
2515 "ignored."),
2516 strFileName.c_str(),
2517 (unsigned long)nLine + 1);
2518 }
2519 else
2520 {
2521 // pass to the beginning of the next line
2522 pc = file[++nLine].c_str();
2523
2524 // skip pc++ at the end of the loop
2525 continue;
2526 }
2527 }
2528 else
2529 {
2530 // just a normal character
2531 curField += *pc;
2532 }
2533 break;
2534
2535 case wxT('\0'):
2536 cont = FALSE; // end of line reached, exit the loop
2537
2538 // fall through to still process this field
2539
2540 case wxT(';'):
2541 // trim whitespaces from both sides
2542 curField.Trim(TRUE).Trim(FALSE);
2543
2544 switch ( currentToken )
2545 {
2546 case Field_Type:
2547 data.type = curField.Lower();
2548 if ( data.type.empty() )
2549 {
2550 // I don't think that this is a valid mailcap
2551 // entry, but try to interpret it somehow
2552 data.type = _T('*');
2553 }
2554
2555 if ( data.type.Find(wxT('/')) == wxNOT_FOUND )
2556 {
2557 // we interpret "type" as "type/*"
2558 data.type += wxT("/*");
2559 }
2560
2561 currentToken = Field_OpenCmd;
2562 break;
2563
2564 case Field_OpenCmd:
2565 data.cmdOpen = curField;
2566
2567 currentToken = Field_Other;
2568 break;
2569
2570 case Field_Other:
2571 if ( !ProcessOtherMailcapField(data, curField) )
2572 {
2573 // don't flood the user with error messages if
2574 // we don't understand something in his
2575 // mailcap, but give them in debug mode because
2576 // this might be useful for the programmer
2577 wxLogDebug
2578 (
2579 wxT("Mailcap file %s, line %lu: "
2580 "unknown field '%s' for the "
2581 "MIME type '%s' ignored."),
2582 strFileName.c_str(),
2583 (unsigned long)nLine + 1,
2584 curField.c_str(),
2585 data.type.c_str()
2586 );
2587 }
2588 else if ( data.testfailed )
2589 {
2590 // skip this entry entirely
2591 cont = FALSE;
2592 }
2593
2594 // it already has this value
2595 //currentToken = Field_Other;
2596 break;
2597
2598 default:
2599 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2600 }
2601
2602 // next token starts immediately after ';'
2603 curField.Empty();
2604 break;
2605
2606 default:
2607 curField += *pc;
2608 }
2609
2610 // continue in the same line
2611 pc++;
2612 }
2613
2614 // we read the entire entry, check what have we got
2615 // ------------------------------------------------
2616
2617 // check that we really read something reasonable
2618 if ( currentToken < Field_Other )
2619 {
2620 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
2621 "ignored."),
2622 strFileName.c_str(), nLine + 1);
2623
2624 continue;
2625 }
2626
2627 // if the test command failed, it's as if the entry were not there at
2628 // all
2629 if ( data.testfailed )
2630 {
2631 continue;
2632 }
2633
2634 // support for flags:
2635 // 1. create an xterm for 'needsterminal'
2636 // 2. append "| $PAGER" for 'copiousoutput'
2637 //
2638 // Note that the RFC says that having both needsterminal and
2639 // copiousoutput is probably a mistake, so it seems that running
2640 // programs with copiousoutput inside an xterm as it is done now
2641 // is a bad idea (FIXME)
2642 if ( data.copiousoutput )
2643 {
2644 const wxChar *p = wxGetenv(_T("PAGER"));
2645 data.cmdOpen << _T(" | ") << (p ? p : _T("more"));
2646 }
2647
2648 if ( data.needsterminal )
2649 {
2650 data.cmdOpen = wxString::Format(_T("xterm -e sh -c '%s'"),
2651 data.cmdOpen.c_str());
2652 }
2653
2654 if ( !data.cmdOpen.empty() )
2655 {
2656 data.verbs.Insert(_T("open"), 0);
2657 data.commands.Insert(data.cmdOpen, 0);
2658 }
2659
2660 // we have to decide whether the new entry should replace any entries
2661 // for the same MIME type we had previously found or not
2662 bool overwrite;
2663
2664 // the fall back entries have the lowest priority, by definition
2665 if ( fallback )
2666 {
2667 overwrite = FALSE;
2668 }
2669 else
2670 {
2671 // have we seen this one before?
2672 int nIndex = m_aTypes.Index(data.type);
2673
2674 // and if we have, was it in this file?
2675 overwrite = nIndex == wxNOT_FOUND ||
2676 aIndicesSeenHere.Index(nIndex) != wxNOT_FOUND;
2677 }
2678
2679 wxLogTrace(TRACE_MIME, _T("mailcap %s: %s [%s]"),
2680 data.type.c_str(), data.cmdOpen.c_str(),
2681 overwrite ? _T("replace") : _T("add"));
2682
2683 int n = AddToMimeData
2684 (
2685 data.type,
2686 data.icon,
2687 new wxMimeTypeCommands(data.verbs, data.commands),
2688 wxArrayString() /* extensions */,
2689 data.desc,
2690 overwrite
2691 );
2692
2693 if ( overwrite )
2694 {
2695 aIndicesSeenHere.Add(n);
2696 }
2697 }
2698
2699 return TRUE;
2700 }
2701
2702 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
2703 {
2704 InitIfNeeded();
2705
2706 mimetypes.Empty();
2707
2708 wxString type;
2709 size_t count = m_aTypes.GetCount();
2710 for ( size_t n = 0; n < count; n++ )
2711 {
2712 // don't return template types from here (i.e. anything containg '*')
2713 type = m_aTypes[n];
2714 if ( type.Find(_T('*')) == wxNOT_FOUND )
2715 {
2716 mimetypes.Add(type);
2717 }
2718 }
2719
2720 return mimetypes.GetCount();
2721 }
2722
2723 // ----------------------------------------------------------------------------
2724 // writing to MIME type files
2725 // ----------------------------------------------------------------------------
2726
2727 bool wxMimeTypesManagerImpl::Unassociate(wxFileType *ft)
2728 {
2729 wxArrayString sMimeTypes;
2730 ft->GetMimeTypes (sMimeTypes);
2731
2732 wxString sMime;
2733 size_t i;
2734 for (i = 0; i < sMimeTypes.GetCount(); i ++)
2735 {
2736 sMime = sMimeTypes.Item(i);
2737 int nIndex = m_aTypes.Index (sMime);
2738 if ( nIndex == wxNOT_FOUND)
2739 {
2740 // error if we get here ??
2741 return FALSE;
2742 }
2743 else
2744 {
2745 WriteMimeInfo(nIndex, TRUE );
2746 m_aTypes.RemoveAt(nIndex);
2747 m_aEntries.RemoveAt(nIndex);
2748 m_aExtensions.RemoveAt(nIndex);
2749 m_aDescriptions.RemoveAt(nIndex);
2750 m_aIcons.RemoveAt(nIndex);
2751 }
2752 }
2753 // check data integrity
2754 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
2755 m_aTypes.Count() == m_aExtensions.Count() &&
2756 m_aTypes.Count() == m_aIcons.Count() &&
2757 m_aTypes.Count() == m_aDescriptions.Count() );
2758
2759 return TRUE;
2760 }
2761
2762 // ----------------------------------------------------------------------------
2763 // private functions
2764 // ----------------------------------------------------------------------------
2765
2766 static bool IsKnownUnimportantField(const wxString& fieldAll)
2767 {
2768 static const wxChar *knownFields[] =
2769 {
2770 _T("x-mozilla-flags"),
2771 _T("nametemplate"),
2772 _T("textualnewlines"),
2773 };
2774
2775 wxString field = fieldAll.BeforeFirst(_T('='));
2776 for ( size_t n = 0; n < WXSIZEOF(knownFields); n++ )
2777 {
2778 if ( field.CmpNoCase(knownFields[n]) == 0 )
2779 return TRUE;
2780 }
2781
2782 return FALSE;
2783 }
2784
2785 #endif
2786 // wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE
2787