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