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