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