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