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