Unix compilation fixes for new MIME code
[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) ||
1295 (mailcapStyles & wxMAILCAP_STANDARD) )
1296 GetMimeInfo(sExtraDir);
1297
1298 // read GNOME tables
1299 if ( mailcapStyles & wxMAILCAP_GNOME)
1300 GetGnomeMimeInfo(sExtraDir);
1301
1302 // read KDE tables
1303 if ( mailcapStyles & wxMAILCAP_KDE)
1304 GetKDEMimeInfo(sExtraDir);
1305
1306 m_mailcapStylesInited |= mailcapStyles;
1307 }
1308
1309 // clear data so you can read another group of WM files
1310 void wxMimeTypesManagerImpl::ClearData()
1311 {
1312 m_aTypes.Clear ();
1313 m_aIcons.Clear ();
1314 m_aExtensions.Clear ();
1315 m_aDescriptions.Clear ();
1316
1317 size_t cnt = m_aTypes.GetCount();
1318 for (size_t i = 0; i < cnt; i++)
1319 {
1320 m_aEntries[i]->Clear ();
1321 }
1322 m_aEntries.Clear ();
1323 m_mailcapStylesInited = 0;
1324 }
1325
1326 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
1327 {
1328 ClearData(); // do we need to delete the ArrayStrings too to avoid a leak
1329
1330 // delete m_aEntries //fix a leak here ?;
1331 }
1332
1333
1334 void wxMimeTypesManagerImpl::GetMimeInfo (const wxString& sExtraDir)
1335 {
1336 // read this for netscape or Metamail formats
1337
1338 // directories where we look for mailcap and mime.types by default
1339 // used by netscape and pine and other mailers, using 2 different formats!
1340
1341 // (taken from metamail(1) sources)
1342 //
1343 // although RFC 1524 specifies the search path of
1344 // /etc/:/usr/etc:/usr/local/etc only, it doesn't hurt to search in more
1345 // places - OTOH, the RFC also says that this path can be changed with
1346 // MAILCAPS environment variable (containing the colon separated full
1347 // filenames to try) which is not done yet (TODO?)
1348
1349 wxString strHome = wxGetenv(wxT("HOME"));
1350
1351 wxArrayString dirs;
1352 dirs.Add ( wxT("/etc/") );
1353 dirs.Add ( wxT("/usr/etc/") );
1354 dirs.Add ( wxT("/usr/local/etc/") );
1355 dirs.Add ( wxT("/etc/mail/") );
1356 dirs.Add ( wxT("/usr/public/lib/") );
1357 dirs.Add ( strHome + wxT("/.") );
1358 if (!sExtraDir.IsEmpty()) dirs.Add ( sExtraDir + wxT("/") );
1359
1360 size_t nDirs = dirs.GetCount();
1361 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
1362 {
1363 wxString file = dirs[nDir] + wxT("mailcap");
1364 if ( wxFile::Exists(file) ) {
1365 ReadMailcap(file);
1366 }
1367
1368 file = dirs[nDir] + wxT("mime.types");
1369 if ( wxFile::Exists(file) ) {
1370 ReadMimeTypes(file);
1371 }
1372 }
1373
1374 }
1375
1376 bool wxMimeTypesManagerImpl::WriteToMimeTypes (int index, bool delete_index)
1377 {
1378 // check we have the right manager
1379 if (! ( m_mailcapStylesInited & wxMAILCAP_STANDARD) )
1380 return FALSE;
1381
1382 bool bTemp;
1383 wxString strHome = wxGetenv(wxT("HOME"));
1384
1385 // and now the users mailcap
1386 wxString strUserMailcap = strHome + wxT("/.mime.types");
1387
1388 wxMimeTextFile file;
1389 if ( wxFile::Exists(strUserMailcap) )
1390 {
1391 bTemp = file.Open(strUserMailcap);
1392 }
1393 else
1394 {
1395 if (delete_index) return FALSE;
1396 bTemp = file.Create(strUserMailcap);
1397 }
1398 if (bTemp)
1399 {
1400 int nIndex;
1401 // test for netscape's header and return FALSE if its found
1402 nIndex = file.pIndexOf (wxT("#--Netscape"));
1403 if (nIndex != wxNOT_FOUND)
1404 {
1405 wxASSERT_MSG(FALSE,wxT("Error in .mime.types \nTrying to mix Netscape and Metamail formats\nFile not modiifed"));
1406 return FALSE;
1407 }
1408 // write it in alternative format
1409 // get rid of unwanted entries
1410 wxString strType = m_aTypes[index];
1411 nIndex = file.pIndexOf (strType);
1412 // get rid of all the unwanted entries...
1413 if (nIndex != wxNOT_FOUND) file.CommentLine (nIndex);
1414
1415 if (!delete_index)
1416 {
1417 // add the new entries in
1418 wxString sTmp = strType.Append (wxT(' '), 40-strType.Len() );
1419 sTmp = sTmp + m_aExtensions[index];
1420 file.AddLine (sTmp);
1421 }
1422
1423
1424 bTemp = file.Write ();
1425 file.Close ();
1426 }
1427 return bTemp;
1428 }
1429
1430 bool wxMimeTypesManagerImpl::WriteToNSMimeTypes (int index, bool delete_index)
1431 {
1432 //check we have the right managers
1433 if (! ( m_mailcapStylesInited & wxMAILCAP_NETSCAPE) )
1434 return FALSE;
1435
1436 bool bTemp;
1437 wxString strHome = wxGetenv(wxT("HOME"));
1438
1439 // and now the users mailcap
1440 wxString strUserMailcap = strHome + wxT("/.mime.types");
1441
1442 wxMimeTextFile file;
1443 if ( wxFile::Exists(strUserMailcap) )
1444 {
1445 bTemp = file.Open(strUserMailcap);
1446 }
1447 else
1448 {
1449 if (delete_index) return FALSE;
1450 bTemp = file.Create(strUserMailcap);
1451 }
1452 if (bTemp)
1453 {
1454
1455 // write it in the format that Netscape uses
1456 int nIndex;
1457 // test for netscape's header and insert if required...
1458 // this is a comment so use TRUE
1459 nIndex = file.pIndexOf (wxT("#--Netscape"), TRUE);
1460 if (nIndex == wxNOT_FOUND)
1461 {
1462 // either empty file or metamail format
1463 // at present we can't cope with mixed formats, so exit to preseve
1464 // metamail entreies
1465 if (file.GetLineCount () > 0)
1466 {
1467 wxASSERT_MSG(FALSE, wxT(".mime.types File not in Netscape format\nNo entries written to\n.mime.types or to .mailcap"));
1468 return FALSE;
1469 }
1470 file.InsertLine (wxT( "#--Netscape Communications Corporation MIME Information" ), 0);
1471 nIndex = 0;
1472 }
1473
1474 wxString strType = wxT("type=") + m_aTypes[index];
1475 nIndex = file.pIndexOf (strType);
1476 // get rid of all the unwanted entries...
1477 if (nIndex != wxNOT_FOUND)
1478 {
1479 wxString sOld = file[nIndex];
1480 while ( (sOld.Contains(wxT("\\"))) && (nIndex < (int) file.GetLineCount()) )
1481 {
1482 file.CommentLine(nIndex);
1483 sOld = file[nIndex];
1484 wxLogTrace(TRACE_MIME, wxT("--- Deleting from mime.types line '%d %s' ---"), nIndex, sOld.c_str());
1485 nIndex ++;
1486 }
1487 if (nIndex < (int) file.GetLineCount()) file.CommentLine (nIndex);
1488 }
1489 else nIndex = (int) file.GetLineCount();
1490
1491 wxString sTmp = strType + wxT(" \\");
1492 if (!delete_index) file.InsertLine (sTmp, nIndex);
1493 if ( ! m_aDescriptions.Item(index).IsEmpty() )
1494 {
1495 sTmp = wxT("desc=\"") + m_aDescriptions[index]+ wxT("\" \\") ; //.trim ??
1496 if (!delete_index)
1497 {
1498 nIndex ++;
1499 file.InsertLine (sTmp, nIndex);
1500 }
1501 }
1502 wxString sExts = m_aExtensions.Item(index);
1503 sTmp = wxT("exts=\"") + sExts.Trim(FALSE).Trim() + wxT("\"");
1504 if (!delete_index)
1505 {
1506 nIndex ++;
1507 file.InsertLine (sTmp, nIndex);
1508 }
1509
1510 bTemp = file.Write ();
1511 file.Close ();
1512 }
1513 return bTemp;
1514 }
1515
1516
1517 bool wxMimeTypesManagerImpl::WriteToMailCap (int index, bool delete_index)
1518 {
1519 //check we have the right managers
1520 if ( !( ( m_mailcapStylesInited & wxMAILCAP_NETSCAPE) ||
1521 ( m_mailcapStylesInited & wxMAILCAP_STANDARD) ) )
1522 return FALSE;
1523
1524 bool bTemp;
1525 wxString strHome = wxGetenv(wxT("HOME"));
1526
1527 // and now the users mailcap
1528 wxString strUserMailcap = strHome + wxT("/.mailcap");
1529
1530 wxMimeTextFile file;
1531 if ( wxFile::Exists(strUserMailcap) )
1532 {
1533 bTemp = file.Open(strUserMailcap);
1534 }
1535 else
1536 {
1537 if (delete_index) return FALSE;
1538 bTemp = file.Create(strUserMailcap);
1539 }
1540 if (bTemp)
1541 {
1542 // now got a file we can write to ....
1543 wxMimeArrayString * entries = m_aEntries[index];
1544 size_t iOpen = entries->pIndexOf(wxT("open"));
1545 wxString sCmd = entries->GetCmd(iOpen);
1546 wxString sTmp;
1547
1548 sTmp = m_aTypes[index];
1549 wxString sOld;
1550 int nIndex = file.pIndexOf(sTmp);
1551 // get rid of all the unwanted entries...
1552 if (nIndex == wxNOT_FOUND)
1553 {
1554 nIndex = (int) file.GetLineCount();
1555 }
1556 else
1557 {
1558 sOld = file[nIndex];
1559 wxLogTrace(TRACE_MIME, wxT("--- Deleting from mailcap line '%d' ---"), nIndex);
1560
1561 while ( (sOld.Contains(wxT("\\"))) && (nIndex < (int) file.GetLineCount()) )
1562 {
1563 file.CommentLine(nIndex);
1564 if (nIndex < (int) file.GetLineCount()) sOld = sOld + file[nIndex];
1565 }
1566 if (nIndex < (int) file.GetLineCount()) file.CommentLine (nIndex);
1567 }
1568
1569 sTmp = sTmp + wxT(";") + sCmd ; //includes wxT(" %s ");
1570
1571 // write it in the format that Netscape uses (default)
1572 if (! ( m_mailcapStylesInited & wxMAILCAP_STANDARD ) )
1573 {
1574 if (! delete_index) file.InsertLine (sTmp, nIndex);
1575 nIndex ++;
1576 }
1577
1578 // write extended format
1579 else
1580 {
1581 // todo FIX this code;
1582 // ii) lost entries
1583 // sOld holds all the entries, but our data store only has some
1584 // eg test= is not stored
1585
1586 // so far we have written the mimetype and command out
1587 wxStringTokenizer sT (sOld, wxT(";\\"));
1588 if (sT.CountTokens () > 2)
1589 {
1590 // first one mimetype; second one command, rest unknown...
1591 wxString s;
1592 s = sT.GetNextToken();
1593 s = sT.GetNextToken();
1594
1595 // first unknown
1596 s = sT.GetNextToken();
1597 while ( ! s.IsEmpty() )
1598 {
1599 bool bKnownToken = FALSE;
1600 if (s.Contains(wxT("description="))) bKnownToken = TRUE;
1601 if (s.Contains(wxT("x11-bitmap="))) bKnownToken = TRUE;
1602 size_t i;
1603 for (i=0; i < entries->GetCount(); i++)
1604 {
1605 if (s.Contains(entries->GetVerb(i))) bKnownToken = TRUE;
1606 }
1607 if (!bKnownToken)
1608 {
1609 sTmp = sTmp + wxT("; \\");
1610 file.InsertLine (sTmp, nIndex);
1611 sTmp = s;
1612 }
1613 s = sT.GetNextToken ();
1614 }
1615
1616 }
1617
1618 if (! m_aDescriptions[index].IsEmpty() )
1619 {
1620 sTmp = sTmp + wxT("; \\");
1621 file.InsertLine (sTmp, nIndex);
1622 nIndex ++;
1623 sTmp = wxT(" description=\"") + m_aDescriptions[index] + wxT("\"");
1624 }
1625
1626 if (! m_aIcons[index].IsEmpty() )
1627 {
1628 sTmp = sTmp + wxT("; \\");
1629 file.InsertLine (sTmp, nIndex);
1630 nIndex ++;
1631 sTmp = wxT(" x11-bitmap=\"") + m_aIcons[index] + wxT("\"");
1632 }
1633 if ( entries->GetCount() > 1 )
1634
1635 {
1636 size_t i;
1637 for (i=0; i < entries->GetCount(); i++)
1638 if ( i != iOpen )
1639 {
1640 sTmp = sTmp + wxT("; \\");
1641 file.InsertLine (sTmp, nIndex);
1642 nIndex ++;
1643 sTmp = wxT(" ") + entries->Item(i);
1644 }
1645 }
1646
1647 file.InsertLine (sTmp, nIndex);
1648 nIndex ++;
1649
1650 }
1651 bTemp = file.Write ();
1652 file.Close ();
1653 }
1654 return bTemp;
1655 }
1656
1657 wxFileType *
1658 wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo& ftInfo)
1659 {
1660 InitIfNeeded();
1661
1662 wxString strType = ftInfo.GetMimeType ();
1663 wxString strDesc = ftInfo.GetDescription ();
1664 wxString strIcon = ftInfo.GetIconFile ();
1665
1666 wxMimeArrayString *entry = new wxMimeArrayString ();
1667
1668 if ( ! ftInfo.GetOpenCommand().IsEmpty())
1669 entry->Add(wxT("open=") + ftInfo.GetOpenCommand () + wxT(" %s "));
1670 if ( ! ftInfo.GetPrintCommand ().IsEmpty())
1671 entry->Add(wxT("print=") + ftInfo.GetPrintCommand () + wxT(" %s "));
1672
1673 // now find where these extensions are in the data store and remove them
1674 wxArrayString sA_Exts = ftInfo.GetExtensions ();
1675 wxString sExt, sExtStore;
1676 size_t i, nIndex;
1677 for (i=0; i < sA_Exts.GetCount(); i++)
1678 {
1679 sExt = sA_Exts.Item(i);
1680 //clean up to just a space before and after
1681 sExt.Trim().Trim(FALSE);
1682 sExt = wxT(' ') + sExt + wxT(' ');
1683 for (nIndex = 0; nIndex < m_aExtensions.GetCount(); nIndex ++)
1684 {
1685 sExtStore = m_aExtensions.Item(nIndex);
1686 if (sExtStore.Replace(sExt, wxT(" ") ) > 0) m_aExtensions.Item(nIndex) = sExtStore ;
1687 }
1688
1689 }
1690
1691 if ( !DoAssociation (strType, strIcon, entry, sA_Exts, strDesc) )
1692 return NULL;
1693
1694 return GetFileTypeFromMimeType(strType);
1695 }
1696
1697
1698 bool wxMimeTypesManagerImpl::DoAssociation(const wxString& strType,
1699 const wxString& strIcon,
1700 wxMimeArrayString *entry,
1701 const wxArrayString& strExtensions,
1702 const wxString& strDesc)
1703 {
1704 int nIndex = AddToMimeData(strType, strIcon, entry, strExtensions, strDesc, TRUE);
1705
1706 if ( nIndex == wxNOT_FOUND )
1707 return FALSE;
1708
1709 return WriteMimeInfo (nIndex, FALSE);
1710 }
1711
1712 bool wxMimeTypesManagerImpl::WriteMimeInfo(int nIndex, bool delete_mime )
1713 {
1714 bool ok = TRUE;
1715
1716 if ( m_mailcapStylesInited & wxMAILCAP_STANDARD )
1717 {
1718 // write in metamail format;
1719 if (WriteToMimeTypes (nIndex, delete_mime) )
1720 if ( WriteToMailCap (nIndex, delete_mime) )
1721 ok = FALSE;
1722 }
1723 if ( m_mailcapStylesInited & wxMAILCAP_NETSCAPE )
1724 {
1725 // write in netsacpe format;
1726 if (WriteToNSMimeTypes (nIndex, delete_mime) )
1727 if ( WriteToMailCap (nIndex, delete_mime) )
1728 ok = FALSE;
1729 }
1730 if (m_mailcapStylesInited & wxMAILCAP_GNOME)
1731 {
1732 // write in Gnome format;
1733 if (WriteGnomeMimeFile (nIndex, delete_mime) )
1734 if (WriteGnomeKeyFile (nIndex, delete_mime) )
1735 ok = FALSE;
1736 }
1737 if (m_mailcapStylesInited & wxMAILCAP_KDE)
1738 {
1739 // write in KDE format;
1740 if (WriteKDEMimeFile (nIndex, delete_mime) )
1741 ok = FALSE;
1742 }
1743
1744 return ok;
1745 }
1746
1747 int wxMimeTypesManagerImpl::AddToMimeData(const wxString& strType,
1748 const wxString& strIcon,
1749 wxMimeArrayString *entry,
1750 const wxArrayString& strExtensions,
1751 const wxString& strDesc,
1752 bool ReplaceExisting)
1753 {
1754 InitIfNeeded();
1755
1756 wxLogTrace(TRACE_MIME, wxT("In Add to Mime data '%s' with %d entries and %d exts ---"),
1757 strType.c_str(), entry->GetCount(), strExtensions.GetCount() );
1758
1759 // ensure mimetype is always lower case
1760 wxString mimeType = strType;
1761 mimeType.MakeLower();
1762 int nIndex = m_aTypes.Index(mimeType);
1763 if ( nIndex == wxNOT_FOUND )
1764 {
1765 // new file type
1766 m_aTypes.Add(mimeType);
1767 m_aIcons.Add(strIcon);
1768 m_aEntries.Add(entry);
1769 size_t i;
1770 // change nIndex so we can add to the correct line
1771 nIndex = m_aExtensions.Add(wxT(' '));
1772 for (i = 0; i < strExtensions.GetCount(); i ++)
1773 {
1774 if (! m_aExtensions.Item(nIndex).Contains(wxT(' ') + strExtensions.Item(i) + wxT(' ')))
1775 m_aExtensions.Item(nIndex) += strExtensions.Item(i) + wxT(' ');
1776 }
1777 m_aDescriptions.Add(strDesc);
1778
1779 }
1780 else
1781 {
1782 // nIndex has the existing data
1783 // always add the extensions to this mimetype
1784 size_t i;
1785 for (i = 0; i < strExtensions.GetCount(); i ++)
1786 {
1787 if (! m_aExtensions.Item(nIndex).Contains(wxT(' ') + strExtensions.Item(i) + wxT(' ')))
1788 m_aExtensions.Item(nIndex) += strExtensions.Item(i) + wxT(' ');
1789 }
1790 if (ReplaceExisting)
1791 {
1792 // if new description change it
1793 if ( ! strDesc.IsEmpty())
1794 m_aDescriptions[nIndex] = strDesc;
1795
1796 // if new icon change it
1797 if ( ! strIcon.IsEmpty())
1798 m_aIcons[nIndex] = strIcon;
1799
1800 wxMimeArrayString *entryOld = m_aEntries[nIndex];
1801 // replace any matching entries...
1802 for (i=0; i < entry->GetCount(); i++)
1803 entryOld->ReplaceOrAddLineCmd (entry->GetVerb(i),
1804 entry->GetCmd (i) );
1805 }
1806 else
1807 {
1808 // add data we don't already have ...
1809 // if new description add only if none
1810 if ( ! strDesc.IsEmpty() && m_aDescriptions.Item(i).IsEmpty() )
1811 m_aDescriptions[nIndex] = strDesc;
1812
1813 // if new icon and no existing icon
1814 if ( ! strIcon.IsEmpty() && m_aIcons.Item(i). IsEmpty () )
1815 m_aIcons[nIndex] = strIcon;
1816
1817 wxMimeArrayString *entryOld = m_aEntries[nIndex];
1818 // add any new entries...
1819 for (i=0; i < entry->GetCount(); i++)
1820 {
1821 wxString sVerb = entry->GetVerb(i);
1822 if ( entryOld->pIndexOf ( sVerb ) == (size_t) wxNOT_FOUND )
1823 entryOld->Add (entry->Item(i));
1824 }
1825 }
1826 }
1827
1828 // check data integrity
1829 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
1830 m_aTypes.Count() == m_aExtensions.Count() &&
1831 m_aTypes.Count() == m_aIcons.Count() &&
1832 m_aTypes.Count() == m_aDescriptions.Count() );
1833
1834 return nIndex;
1835 }
1836
1837
1838 wxFileType *
1839 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
1840 {
1841 if (ext.IsEmpty() )
1842 return NULL;
1843
1844 InitIfNeeded();
1845
1846 wxFileType *fileType = NULL;
1847 size_t count = m_aExtensions.GetCount();
1848 for ( size_t n = 0; n < count; n++ )
1849 {
1850 wxString extensions = m_aExtensions[n];
1851 while ( !extensions.IsEmpty() ) {
1852 wxString field = extensions.BeforeFirst(wxT(' '));
1853 extensions = extensions.AfterFirst(wxT(' '));
1854
1855 // consider extensions as not being case-sensitive
1856 if ( field.IsSameAs(ext, FALSE /* no case */) )
1857 {
1858 // found
1859 if (fileType == NULL) fileType = new wxFileType;
1860 fileType->m_impl->Init(this, n);
1861 // adds this mime type to _list_ of mime types with this extension
1862 }
1863 }
1864 }
1865
1866 return fileType;
1867 }
1868
1869 wxFileType *
1870 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1871 {
1872 InitIfNeeded();
1873
1874 wxFileType * fileType = NULL;
1875 // mime types are not case-sensitive
1876 wxString mimetype(mimeType);
1877 mimetype.MakeLower();
1878
1879 // first look for an exact match
1880 int index = m_aTypes.Index(mimetype);
1881 if ( index != wxNOT_FOUND )
1882 {
1883 fileType = new wxFileType;
1884 fileType->m_impl->Init(this, index);
1885 }
1886
1887 // then try to find "text/*" as match for "text/plain" (for example)
1888 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1889 // the whole string - ok.
1890
1891 index = wxNOT_FOUND;
1892 wxString strCategory = mimetype.BeforeFirst(wxT('/'));
1893
1894 size_t nCount = m_aTypes.Count();
1895 for ( size_t n = 0; n < nCount; n++ ) {
1896 if ( (m_aTypes[n].BeforeFirst(wxT('/')) == strCategory ) &&
1897 m_aTypes[n].AfterFirst(wxT('/')) == wxT("*") ) {
1898 index = n;
1899 break;
1900 }
1901
1902 }
1903
1904 if ( index != wxNOT_FOUND )
1905 {
1906 fileType = new wxFileType;
1907 fileType->m_impl->Init(this, index);
1908 }
1909 return fileType;
1910 }
1911
1912
1913 wxString wxMimeTypesManagerImpl::GetCommand(const wxString & verb, size_t nIndex) const
1914 {
1915 wxString command, testcmd, sV, sTmp;
1916 sV = verb + wxT("=");
1917 // list of verb = command pairs for this mimetype
1918 wxMimeArrayString * sPairs = m_aEntries [nIndex];
1919
1920 size_t i;
1921 for ( i = 0; i < sPairs->GetCount () ; i++ )
1922 {
1923 sTmp = sPairs->Item (i);
1924 if ( sTmp.Contains(sV) ) command = sTmp.AfterFirst(wxT('='));
1925 }
1926 return command;
1927 }
1928
1929 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
1930 {
1931 InitIfNeeded();
1932
1933 wxString extensions;
1934 const wxArrayString& exts = filetype.GetExtensions();
1935 size_t nExts = exts.GetCount();
1936 for ( size_t nExt = 0; nExt < nExts; nExt++ ) {
1937 if ( nExt > 0 ) {
1938 extensions += wxT(' ');
1939 }
1940 extensions += exts[nExt];
1941 }
1942
1943 AddMimeTypeInfo(filetype.GetMimeType(),
1944 extensions,
1945 filetype.GetDescription());
1946
1947 AddMailcapInfo(filetype.GetMimeType(),
1948 filetype.GetOpenCommand(),
1949 filetype.GetPrintCommand(),
1950 wxT(""),
1951 filetype.GetDescription());
1952 }
1953
1954 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString& strMimeType,
1955 const wxString& strExtensions,
1956 const wxString& strDesc)
1957 {
1958 // reading mailcap may find image/* , while
1959 // reading mime.types finds image/gif and no match is made
1960 // this means all the get functions don't work fix this
1961 wxString strIcon;
1962 wxString sTmp = strExtensions;
1963 wxMimeArrayString * entry = new wxMimeArrayString () ;
1964
1965 wxArrayString sExts;
1966 sTmp.Trim().Trim(FALSE);
1967
1968 while (!sTmp.IsEmpty())
1969 {
1970 sExts.Add (sTmp.AfterLast(wxT(' ')));
1971 sTmp = sTmp.BeforeLast(wxT(' '));
1972 }
1973
1974 AddToMimeData (strMimeType, strIcon, entry, sExts, strDesc, (bool)TRUE);
1975 }
1976
1977 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString& strType,
1978 const wxString& strOpenCmd,
1979 const wxString& strPrintCmd,
1980 const wxString& strTest,
1981 const wxString& strDesc)
1982 {
1983 InitIfNeeded();
1984
1985 wxMimeArrayString *entry = new wxMimeArrayString;
1986 entry->Add(wxT("open=") + strOpenCmd);
1987 entry->Add(wxT("print=") + strPrintCmd);
1988 entry->Add(wxT("test=") + strTest);
1989
1990 wxString strIcon;
1991 wxArrayString strExtensions;
1992
1993 AddToMimeData (strType, strIcon, entry, strExtensions, strDesc, TRUE);
1994
1995 }
1996
1997 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString& strFileName)
1998 {
1999 wxLogTrace(TRACE_MIME, wxT("--- Parsing mime.types file '%s' ---"),
2000 strFileName.c_str());
2001
2002 wxTextFile file(strFileName);
2003 if ( !file.Open() )
2004 return FALSE;
2005
2006 // the information we extract
2007 wxString strMimeType, strDesc, strExtensions;
2008
2009 size_t nLineCount = file.GetLineCount();
2010 const wxChar *pc = NULL;
2011 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
2012 if ( pc == NULL ) {
2013 // now we're at the start of the line
2014 pc = file[nLine].c_str();
2015 }
2016 else {
2017 // we didn't finish with the previous line yet
2018 nLine--;
2019 }
2020
2021 // skip whitespace
2022 while ( wxIsspace(*pc) )
2023 pc++;
2024
2025 // comment or blank line?
2026 if ( *pc == wxT('#') || !*pc ) {
2027 // skip the whole line
2028 pc = NULL;
2029 continue;
2030 }
2031
2032 // detect file format
2033 const wxChar *pEqualSign = wxStrchr(pc, wxT('='));
2034 if ( pEqualSign == NULL ) {
2035 // brief format
2036 // ------------
2037
2038 // first field is mime type
2039 for ( strMimeType.Empty(); !wxIsspace(*pc) && *pc != wxT('\0'); pc++ ) {
2040 strMimeType += *pc;
2041 }
2042
2043 // skip whitespace
2044 while ( wxIsspace(*pc) )
2045 pc++;
2046
2047 // take all the rest of the string
2048 strExtensions = pc;
2049
2050 // no description...
2051 strDesc.Empty();
2052 }
2053 else {
2054 // expanded format
2055 // ---------------
2056
2057 // the string on the left of '=' is the field name
2058 wxString strLHS(pc, pEqualSign - pc);
2059
2060 // eat whitespace
2061 for ( pc = pEqualSign + 1; wxIsspace(*pc); pc++ )
2062 ;
2063
2064 const wxChar *pEnd;
2065 if ( *pc == wxT('"') ) {
2066 // the string is quoted and ends at the matching quote
2067 pEnd = wxStrchr(++pc, wxT('"'));
2068 if ( pEnd == NULL ) {
2069 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
2070 "quoted string."),
2071 strFileName.c_str(), nLine + 1);
2072 }
2073 }
2074 else {
2075 // unquoted string ends at the first space or at the end of
2076 // line
2077 for ( pEnd = pc; *pEnd && !wxIsspace(*pEnd); pEnd++ )
2078 ;
2079 }
2080
2081 // now we have the RHS (field value)
2082 wxString strRHS(pc, pEnd - pc);
2083
2084 // check what follows this entry
2085 if ( *pEnd == wxT('"') ) {
2086 // skip this quote
2087 pEnd++;
2088 }
2089
2090 for ( pc = pEnd; wxIsspace(*pc); pc++ )
2091 ;
2092
2093 // if there is something left, it may be either a '\\' to continue
2094 // the line or the next field of the same entry
2095 bool entryEnded = *pc == wxT('\0'),
2096 nextFieldOnSameLine = FALSE;
2097 if ( !entryEnded ) {
2098 nextFieldOnSameLine = ((*pc != wxT('\\')) || (pc[1] != wxT('\0')));
2099 }
2100
2101 // now see what we got
2102 if ( strLHS == wxT("type") ) {
2103 strMimeType = strRHS;
2104 }
2105 else if ( strLHS == wxT("desc") ) {
2106 strDesc = strRHS;
2107 }
2108 else if ( strLHS == wxT("exts") ) {
2109 strExtensions = strRHS;
2110 }
2111 else {
2112 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
2113 strFileName.c_str(), nLine + 1, strLHS.c_str());
2114 }
2115
2116 if ( !entryEnded ) {
2117 if ( !nextFieldOnSameLine )
2118 pc = NULL;
2119 //else: don't reset it
2120
2121 // as we don't reset strMimeType, the next field in this entry
2122 // will be interpreted correctly.
2123
2124 continue;
2125 }
2126 }
2127
2128 // depending on the format (Mosaic or Netscape) either space or comma
2129 // is used to separate the extensions
2130 strExtensions.Replace(wxT(","), wxT(" "));
2131
2132 // also deal with the leading dot
2133 if ( !strExtensions.IsEmpty() && strExtensions[0u] == wxT('.') )
2134 {
2135 strExtensions.erase(0, 1);
2136 }
2137
2138 wxLogTrace(TRACE_MIME, wxT("--- Found Mimetype '%s' ---"),
2139 strMimeType.c_str());
2140
2141 AddMimeTypeInfo(strMimeType, strExtensions, strDesc);
2142
2143 // finished with this line
2144 pc = NULL;
2145 }
2146
2147 return TRUE;
2148 }
2149
2150 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString& strFileName,
2151 bool fallback)
2152 {
2153 // wxLog::AddTraceMask (TRACE_MIME);
2154 wxLogTrace(TRACE_MIME, wxT("--- Parsing mailcap file '%s' ---"),
2155 strFileName.c_str());
2156
2157 wxTextFile file(strFileName);
2158 if ( !file.Open() )
2159 return FALSE;
2160
2161 // see the comments near the end of function for the reason we need these
2162 // variables (search for the next occurence of them)
2163 // indices of MIME types (in m_aTypes) we already found in this file
2164 wxArrayInt aEntryIndices;
2165 // aLastIndices[n] is the index of last element in
2166 // m_aEntries[aEntryIndices[n]] from this file
2167 // wxArrayInt aLastIndices;
2168
2169 size_t nLineCount = file.GetLineCount();
2170 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
2171 // now we're at the start of the line
2172 const wxChar *pc = file[nLine].c_str();
2173
2174 // skip whitespace
2175 while ( wxIsspace(*pc) )
2176 pc++;
2177
2178 // comment or empty string?
2179 if ( *pc == wxT('#') || *pc == wxT('\0') )
2180 continue;
2181
2182 // no, do parse
2183
2184 // what field are we currently in? The first 2 are fixed and there may
2185 // be an arbitrary number of other fields -- currently, we are not
2186 // interested in any of them, but we should parse them as well...
2187 enum
2188 {
2189 Field_Type,
2190 Field_OpenCmd,
2191 Field_Other
2192 } currentToken = Field_Type;
2193
2194 // the flags and field values on the current line
2195 bool needsterminal = FALSE,
2196 copiousoutput = FALSE;
2197 wxMimeArrayString *entry;
2198
2199 wxString strType,
2200 strOpenCmd,
2201 strIcon,
2202 strTest,
2203 strDesc,
2204 curField; // accumulator
2205 bool cont = TRUE;
2206 bool test_passed = TRUE;
2207 while ( cont ) {
2208 switch ( *pc ) {
2209 case wxT('\\'):
2210 // interpret the next character literally (notice that
2211 // backslash can be used for line continuation)
2212 if ( *++pc == wxT('\0') ) {
2213 // fetch the next line if there is one
2214 if ( nLine == nLineCount - 1 ) {
2215 // something is wrong, bail out
2216 cont = FALSE;
2217
2218 wxLogDebug(wxT("Mailcap file %s, line %d: "
2219 "'\\' on the end of the last line "
2220 "ignored."),
2221 strFileName.c_str(),
2222 nLine + 1);
2223 }
2224 else {
2225 // pass to the beginning of the next line
2226 pc = file[++nLine].c_str();
2227
2228 // skip pc++ at the end of the loop
2229 continue;
2230 }
2231 }
2232 else {
2233 // just a normal character
2234 curField += *pc;
2235 }
2236 break;
2237
2238 case wxT('\0'):
2239 cont = FALSE; // end of line reached, exit the loop
2240
2241 // fall through
2242
2243 case wxT(';'):
2244 // store this field and start looking for the next one
2245
2246 // trim whitespaces from both sides
2247 curField.Trim(TRUE).Trim(FALSE);
2248
2249 switch ( currentToken ) {
2250 case Field_Type:
2251 strType = curField;
2252 if ( strType.empty() ) {
2253 // I don't think that this is a valid mailcap
2254 // entry, but try to interpret it somehow
2255 strType = _T('*');
2256 }
2257
2258 if ( strType.Find(wxT('/')) == wxNOT_FOUND ) {
2259 // we interpret "type" as "type/*"
2260 strType += wxT("/*");
2261 }
2262
2263 currentToken = Field_OpenCmd;
2264 break;
2265
2266 case Field_OpenCmd:
2267 strOpenCmd = curField;
2268 entry = new wxMimeArrayString ();
2269 entry->Add(wxT("open=") + strOpenCmd);
2270
2271 currentToken = Field_Other;
2272 break;
2273
2274 case Field_Other:
2275 if ( !curField.empty() ) {
2276 // "good" mailcap entry?
2277 bool ok = TRUE;
2278
2279 if ( IsKnownUnimportantField(curField) ) ok = FALSE;
2280
2281 // is this something of the form foo=bar?
2282 const wxChar *pEq = wxStrchr(curField, wxT('='));
2283 if (ok)
2284 {
2285 if ( pEq != NULL )
2286 {
2287 wxString lhs = curField.BeforeFirst(wxT('=')),
2288 rhs = curField.AfterFirst(wxT('='));
2289
2290 lhs.Trim(TRUE); // from right
2291 rhs.Trim(FALSE); // from left
2292
2293 // it might be quoted
2294 if ( rhs[0u] == wxT('"') && rhs.Last() == wxT('"') )
2295 {
2296 wxString sTmp = wxString(rhs.c_str() + 1, rhs.Len() - 2);
2297 rhs = sTmp;
2298 }
2299 bool verbfound = TRUE;
2300 if ( lhs.Contains (wxT("test")))
2301 {
2302 if ( ! rhs.IsEmpty() )
2303 {
2304 if ( wxSystem(rhs) == 0 ) {
2305 // ok, test passed
2306 test_passed = TRUE;
2307 wxLogTrace(TRACE_MIME,
2308 wxT("Test '%s' for mime type '%s' succeeded."),
2309 rhs.c_str(), strType.c_str());
2310
2311 }
2312 else {
2313 test_passed = FALSE;
2314 wxLogTrace(TRACE_MIME,
2315 wxT("Test '%s' for mime type '%s' failed."),
2316 rhs.c_str(), strType.c_str());
2317 }
2318 }
2319 verbfound = FALSE;
2320 }
2321 if ( lhs.Contains (wxT("desc")))
2322 {
2323 strDesc = rhs;
2324 verbfound = FALSE;
2325 }
2326 if ( lhs.Contains (wxT("x11-bitmap")))
2327 {
2328 strIcon = rhs;
2329 verbfound = FALSE;
2330 }
2331 if ( lhs.Contains (wxT("notes")))
2332 {
2333 // ignore
2334 verbfound = FALSE;
2335 }
2336 if (verbfound) entry->Add ( lhs + wxT('=') + rhs );
2337 ok = TRUE;
2338 }
2339 else
2340 {
2341 // no, it's a simple flag
2342 if ( curField == wxT("needsterminal") ) {
2343 needsterminal = TRUE;
2344 ok = TRUE;
2345 }
2346 if ( curField == wxT("copiousoutput")) {
2347 // copiousoutput impies that the
2348 // viewer is a console program
2349 needsterminal =
2350 copiousoutput =
2351 ok = TRUE;
2352
2353 if ( !ok )
2354 {
2355 // don't flood the user with error
2356 // messages if we don't understand
2357 // something in his mailcap, but give
2358 // them in debug mode because this might
2359 // be useful for the programmer
2360 wxLogDebug
2361 (
2362 wxT("Mailcap file %s, line %d: "
2363 "unknown field '%s' for the "
2364 "MIME type '%s' ignored."),
2365 strFileName.c_str(),
2366 nLine + 1,
2367 curField.c_str(),
2368 strType.c_str()
2369 );
2370
2371 }
2372
2373 }
2374
2375 }
2376
2377 }
2378
2379 }
2380
2381
2382 // it already has this value
2383 //currentToken = Field_Other;
2384 break;
2385
2386 default:
2387 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2388 }
2389
2390 // next token starts immediately after ';'
2391 curField.Empty();
2392 break;
2393
2394 default:
2395 curField += *pc;
2396 }
2397
2398 // continue in the same line
2399 pc++;
2400 }
2401
2402 // check that we really read something reasonable
2403 if ( currentToken == Field_Type || currentToken == Field_OpenCmd ) {
2404 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
2405 "ignored."),
2406 strFileName.c_str(), nLine + 1);
2407 }
2408 else {
2409 // support for flags:
2410 // 1. create an xterm for 'needsterminal'
2411 // 2. append "| $PAGER" for 'copiousoutput'
2412 //
2413 // Note that the RFC says that having both needsterminal and
2414 // copiousoutput is probably a mistake, so it seems that running
2415 // programs with copiousoutput inside an xterm as it is done now
2416 // is a bad idea (FIXME)
2417 if ( copiousoutput )
2418 {
2419 const wxChar *p = wxGetenv(_T("PAGER"));
2420 strOpenCmd << _T(" | ") << (p ? p : _T("more"));
2421 wxLogTrace(TRACE_MIME, wxT("Replacing .(for pager)...") + entry->Item(0u) + wxT("with") + strOpenCmd );
2422
2423 entry->ReplaceOrAddLineCmd (wxString(wxT("open")), strOpenCmd );
2424 }
2425
2426 if ( needsterminal )
2427 {
2428 strOpenCmd.Printf(_T("xterm -e sh -c '%s'"), strOpenCmd.c_str());
2429 wxLogTrace(TRACE_MIME, wxT("Replacing .(for needs term)...") + entry->Item(0u) + wxT("with") + strOpenCmd );
2430
2431 entry->ReplaceOrAddLineCmd (wxString(wxT("open")), strOpenCmd );
2432 }
2433
2434 // NB: because of complications below (we must get entries priority
2435 // right), we can't use AddMailcapInfo() here, unfortunately.
2436 if ( test_passed )
2437 {
2438 strType.MakeLower();
2439 bool overwrite = TRUE;
2440 int entryIndex ;
2441 if (fallback)
2442 overwrite = FALSE;
2443 else
2444 {
2445 int nIndex = m_aTypes.Index(strType);
2446 entryIndex = aEntryIndices.Index(nIndex);
2447 if ( entryIndex == wxNOT_FOUND )
2448 {
2449 //check this fix
2450 // first time in this file, so replace the icons, entries
2451 // and description (no extensions to replace so ignore these
2452 overwrite = TRUE;
2453 aEntryIndices.Add(nIndex);
2454 //aLastIndices.Add(0);
2455 }
2456 else {
2457 // not the first time in _this_ file
2458 // so we don't want to overwrite
2459 // existing entries,but want to add to them
2460 // so we don't alter the mimetype
2461 // the indices were shifted by 1
2462 overwrite = FALSE;
2463 }
2464
2465
2466 }
2467 wxArrayString strExtensions;
2468 AddToMimeData (strType, strIcon, entry, strExtensions, strDesc, !overwrite );
2469 test_passed = TRUE;
2470 }
2471 }
2472
2473 }
2474
2475 return TRUE;
2476 }
2477
2478 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
2479 {
2480 InitIfNeeded();
2481
2482 mimetypes.Empty();
2483
2484 wxString type;
2485 size_t count = m_aTypes.GetCount();
2486 for ( size_t n = 0; n < count; n++ )
2487 {
2488 // don't return template types from here (i.e. anything containg '*')
2489 type = m_aTypes[n];
2490 if ( type.Find(_T('*')) == wxNOT_FOUND )
2491 {
2492 mimetypes.Add(type);
2493 }
2494 }
2495
2496 return mimetypes.GetCount();
2497 }
2498
2499 // ----------------------------------------------------------------------------
2500 // writing to MIME type files
2501 // ----------------------------------------------------------------------------
2502
2503 bool wxMimeTypesManagerImpl::Unassociate(wxFileType *ft)
2504 {
2505 wxArrayString sMimeTypes;
2506 ft->GetMimeTypes (sMimeTypes);
2507
2508 wxString sMime;
2509 size_t i;
2510 for (i = 0; i < sMimeTypes.GetCount(); i ++)
2511 {
2512 sMime = sMimeTypes.Item(i);
2513 int nIndex = m_aTypes.Index (sMime);
2514 if ( nIndex == wxNOT_FOUND)
2515 {
2516 // error if we get here ??
2517 return FALSE;
2518 }
2519 else
2520 {
2521 WriteMimeInfo(nIndex, TRUE );
2522 m_aTypes.Remove (nIndex);
2523 m_aEntries.Remove (nIndex);
2524 m_aExtensions.Remove (nIndex);
2525 m_aDescriptions.Remove (nIndex);
2526 m_aIcons.Remove (nIndex);
2527 }
2528 }
2529 // check data integrity
2530 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
2531 m_aTypes.Count() == m_aExtensions.Count() &&
2532 m_aTypes.Count() == m_aIcons.Count() &&
2533 m_aTypes.Count() == m_aDescriptions.Count() );
2534
2535 return TRUE;
2536 }
2537
2538 // ----------------------------------------------------------------------------
2539 // private functions
2540 // ----------------------------------------------------------------------------
2541
2542 static bool IsKnownUnimportantField(const wxString& fieldAll)
2543 {
2544 static const wxChar *knownFields[] =
2545 {
2546 _T("x-mozilla-flags"),
2547 _T("nametemplate"),
2548 _T("textualnewlines"),
2549 };
2550
2551 wxString field = fieldAll.BeforeFirst(_T('='));
2552 for ( size_t n = 0; n < WXSIZEOF(knownFields); n++ )
2553 {
2554 if ( field.CmpNoCase(knownFields[n]) == 0 )
2555 return TRUE;
2556 }
2557
2558 return FALSE;
2559 }
2560
2561 #endif
2562 // wxUSE_FILE && wxUSE_TEXTFILE
2563