rewrote wxExtHelpController loading code to use wxFileName as it was broken under...
[wxWidgets.git] / src / generic / helpext.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/generic/helpext.cpp
3 // Purpose: an external help controller for wxWidgets
4 // Author: Karsten Ballueder
5 // Modified by:
6 // Created: 04/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Karsten Ballueder
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #include "wx/wxprec.h"
13
14 #ifdef __BORLANDC__
15 #pragma hdrstop
16 #endif
17
18 #if wxUSE_HELP && !defined(__WXWINCE__) && (!defined(__WXMAC__) || defined(__WXMAC_OSX__))
19
20 #ifndef WX_PRECOMP
21 #include "wx/string.h"
22 #include "wx/utils.h"
23 #include "wx/list.h"
24 #include "wx/intl.h"
25 #include "wx/msgdlg.h"
26 #include "wx/choicdlg.h"
27 #include "wx/log.h"
28 #endif
29
30 #include "wx/filename.h"
31 #include "wx/textfile.h"
32 #include "wx/generic/helpext.h"
33
34 #include <stdio.h>
35 #include <ctype.h>
36 #include <sys/stat.h>
37
38 #if !defined(__WINDOWS__) && !defined(__OS2__)
39 #include <unistd.h>
40 #endif
41
42 #ifdef __WINDOWS__
43 #include "wx/msw/mslu.h"
44 #endif
45
46 #ifdef __WXMSW__
47 #include <windows.h>
48 #include "wx/msw/winundef.h"
49 #endif
50
51 // ----------------------------------------------------------------------------
52 // constants
53 // ----------------------------------------------------------------------------
54
55 /// Name for map file.
56 #define WXEXTHELP_MAPFILE _T("wxhelp.map")
57
58 /// Character introducing comments/documentation field in map file.
59 #define WXEXTHELP_COMMENTCHAR ';'
60
61 #define CONTENTS_ID 0
62
63 IMPLEMENT_CLASS(wxExtHelpController, wxHelpControllerBase)
64
65 /// Name of environment variable to set help browser.
66 #define WXEXTHELP_ENVVAR_BROWSER wxT("WX_HELPBROWSER")
67 /// Is browser a netscape browser?
68 #define WXEXTHELP_ENVVAR_BROWSERISNETSCAPE wxT("WX_HELPBROWSER_NS")
69
70 /**
71 This class implements help via an external browser.
72 It requires the name of a directory containing the documentation
73 and a file mapping numerical Section numbers to relative URLS.
74 */
75
76 wxExtHelpController::wxExtHelpController(wxWindow* parentWindow):
77 wxHelpControllerBase(parentWindow)
78 {
79 m_MapList = (wxList*) NULL;
80 m_NumOfEntries = 0;
81 m_BrowserName = WXEXTHELP_DEFAULTBROWSER;
82 m_BrowserIsNetscape = WXEXTHELP_DEFAULTBROWSER_IS_NETSCAPE;
83
84 wxChar *browser = wxGetenv(WXEXTHELP_ENVVAR_BROWSER);
85 if(browser)
86 {
87 m_BrowserName = browser;
88 browser = wxGetenv(WXEXTHELP_ENVVAR_BROWSERISNETSCAPE);
89 m_BrowserIsNetscape = browser && (wxAtoi(browser) != 0);
90 }
91 }
92
93 wxExtHelpController::~wxExtHelpController()
94 {
95 DeleteList();
96 }
97
98 void wxExtHelpController::SetBrowser(const wxString& browsername, bool isNetscape)
99 {
100 m_BrowserName = browsername;
101 m_BrowserIsNetscape = isNetscape;
102 }
103
104 // Set viewer: new, generic name for SetBrowser
105 void wxExtHelpController::SetViewer(const wxString& viewer, long flags)
106 {
107 SetBrowser(viewer, ((flags & wxHELP_NETSCAPE) == wxHELP_NETSCAPE));
108 }
109
110 bool
111 wxExtHelpController::DisplayHelp(const wxString &relativeURL)
112 {
113 wxBusyCursor b; // display a busy cursor
114
115
116 #if defined(__WXMSW__)
117 wxString url;
118 url << m_MapFile << '\\' << relativeURL.BeforeFirst('#');
119 bool bOk = (int)ShellExecute(NULL, wxT("open"), url.c_str(),
120 NULL, NULL, SW_SHOWNORMAL ) > 32;
121 if ( !bOk )
122 {
123 wxLogSysError(_("Cannot open URL '%s'"), relativeURL.c_str());
124 return false;
125 }
126
127 return true;
128 #elif defined(__OS2__)
129
130 wxString url;
131 url << m_MapFile << '\\' << relativeURL.BeforeFirst('#');
132 // will have to fix for OS/2, later.....DW
133 // bool bOk = (int)ShellExecute(NULL, "open", url,
134 // NULL, NULL, SW_SHOWNORMAL ) > 32;
135 // if ( !bOk )
136 // {
137 // wxLogSysError(_("Cannot open URL '%s'"), relativeURL.c_str());
138 // return false;
139 // }
140 // else
141 return true;
142
143 #elif defined(__DOS__)
144
145 wxString command;
146 command = m_BrowserName;
147 command << wxT(" file://")
148 << m_MapFile << wxFILE_SEP_PATH << relativeURL;
149 return wxExecute(command) != 0;
150
151 #else // UNIX
152 wxString command;
153
154 #ifndef __EMX__
155 if(m_BrowserIsNetscape) // try re-loading first
156 {
157 wxString lockfile;
158 wxGetHomeDir(&lockfile);
159 #ifdef __VMS__
160 lockfile << wxFILE_SEP_PATH << wxT(".netscape]lock.");
161 struct stat statbuf;
162 if(stat(lockfile.fn_str(), &statbuf) == 0)
163 #else
164 lockfile << wxFILE_SEP_PATH << wxT(".netscape/lock");
165 struct stat statbuf;
166 if(lstat(lockfile.fn_str(), &statbuf) == 0)
167 // cannot use wxFileExists, because it's a link pointing to a
168 // non-existing location if(wxFileExists(lockfile))
169 #endif
170 {
171 long success;
172 command << m_BrowserName << wxT(" -remote openURL(")
173 << wxT("file://") << m_MapFile
174 << wxFILE_SEP_PATH << relativeURL << wxT(")");
175 success = wxExecute(command);
176 if(success != 0 ) // returns PID on success
177 return true;
178 }
179 }
180 #endif
181 command = m_BrowserName;
182 command << wxT(" file://")
183 << m_MapFile << wxFILE_SEP_PATH << relativeURL;
184 return wxExecute(command) != 0;
185 #endif
186 }
187
188 class wxExtHelpMapEntry : public wxObject
189 {
190 public:
191 int id;
192 wxString url;
193 wxString doc;
194 wxExtHelpMapEntry(int iid, wxString const &iurl, wxString const &idoc)
195 { id = iid; url = iurl; doc = idoc; }
196 };
197
198 void wxExtHelpController::DeleteList()
199 {
200 if(m_MapList)
201 {
202 wxList::compatibility_iterator node = m_MapList->GetFirst();
203 while (node)
204 {
205 delete (wxExtHelpMapEntry *)node->GetData();
206 m_MapList->Erase(node);
207 node = m_MapList->GetFirst();
208 }
209 delete m_MapList;
210 m_MapList = (wxList*) NULL;
211 }
212 }
213
214 /** This must be called to tell the controller where to find the
215 documentation.
216 @param file - NOT a filename, but a directory name.
217 @return true on success
218 */
219 bool
220 wxExtHelpController::Initialize(const wxString& file)
221 {
222 return LoadFile(file);
223 }
224
225
226 bool wxExtHelpController::ParseMapFileLine(const wxString& line)
227 {
228 const wxChar *p = line.c_str();
229
230 // skip whitespace
231 while ( isascii(*p) && isspace(*p) )
232 p++;
233
234 // skip empty lines and comments
235 if ( *p == _T('\0') || *p == WXEXTHELP_COMMENTCHAR )
236 return true;
237
238 // the line is of the form "num url" so we must have an integer now
239 wxChar *end;
240 const unsigned long id = wxStrtoul(p, &end, 0);
241
242 if ( end == p )
243 return false;
244
245 p = end;
246 while ( isascii(*p) && isspace(*p) )
247 p++;
248
249 // next should be the URL
250 wxString url;
251 url.reserve(line.length());
252 while ( isascii(*p) && !isspace(*p) )
253 url += *p++;
254
255 while ( isascii(*p) && isspace(*p) )
256 p++;
257
258 // and finally the optional description of the entry after comment
259 wxString doc;
260 if ( *p == WXEXTHELP_COMMENTCHAR )
261 {
262 p++;
263 while ( isascii(*p) && isspace(*p) )
264 p++;
265 doc = p;
266 }
267
268 m_MapList->Append(new wxExtHelpMapEntry(id, url, doc));
269 m_NumOfEntries++;
270
271 return true;
272 }
273
274 // file is a misnomer as it's the name of the base help directory
275 bool wxExtHelpController::LoadFile(const wxString& file)
276 {
277 wxFileName helpDir(wxFileName::DirName(file));
278 helpDir.MakeAbsolute();
279
280 bool dirExists = false;
281
282 #if wxUSE_INTL
283 // If a locale is set, look in file/localename, i.e. If passed
284 // "/usr/local/myapp/help" and the current wxLocale is set to be "de", then
285 // look in "/usr/local/myapp/help/de/" first and fall back to
286 // "/usr/local/myapp/help" if that doesn't exist.
287 const wxLocale * const loc = wxGetLocale();
288 if ( loc )
289 {
290 wxString locName = loc->GetName();
291
292 // the locale is in general of the form xx_YY.zzzz, try the full firm
293 // first and then also more general ones
294 wxFileName helpDirLoc(helpDir);
295 helpDirLoc.AppendDir(locName);
296 dirExists = helpDirLoc.DirExists();
297
298 if ( !dirExists )
299 {
300 // try without encoding
301 const wxString locNameWithoutEncoding = locName.BeforeLast(_T('.'));
302 if ( !locNameWithoutEncoding.empty() )
303 {
304 helpDirLoc = helpDir;
305 helpDirLoc.AppendDir(locNameWithoutEncoding);
306 dirExists = helpDirLoc.DirExists();
307 }
308 }
309
310 if ( !dirExists )
311 {
312 // try without country part
313 wxString locNameWithoutCountry = locName.BeforeLast(_T('_'));
314 if ( !locNameWithoutCountry.empty() )
315 {
316 helpDirLoc = helpDir;
317 helpDirLoc.AppendDir(locNameWithoutCountry);
318 dirExists = helpDirLoc.DirExists();
319 }
320 }
321
322 if ( dirExists )
323 helpDir = helpDirLoc;
324 }
325 #endif // wxUSE_INTL
326
327 if ( !dirExists && !helpDir.DirExists() )
328 {
329 wxLogError(_("Help directory \"%s\" not found."),
330 helpDir.GetFullPath().c_str());
331 return false;
332 }
333
334 const wxFileName mapFile(helpDir.GetFullPath(), WXEXTHELP_MAPFILE);
335 if ( !mapFile.FileExists() )
336 {
337 wxLogError(_("Help file \"%s\" not found."),
338 mapFile.GetFullPath().c_str());
339 return false;
340 }
341
342 DeleteList();
343 m_MapList = new wxList;
344 m_NumOfEntries = 0;
345
346 wxTextFile input;
347 if ( !input.Open(mapFile.GetFullPath()) )
348 return false;
349
350 for ( wxString& line = input.GetFirstLine();
351 !input.Eof();
352 line = input.GetNextLine() )
353 {
354 if ( !ParseMapFileLine(line) )
355 {
356 wxLogWarning(_("Line %lu of map file \"%s\" has invalid syntax, skipped."),
357 (unsigned long)input.GetCurrentLine(),
358 mapFile.GetFullPath().c_str());
359 }
360 }
361
362 if ( !m_NumOfEntries )
363 {
364 wxLogError(_("No valid mappings found in the file \"%s\"."),
365 mapFile.GetFullPath().c_str());
366 return false;
367 }
368
369 m_MapFile = helpDir.GetFullPath(); // now it's valid
370 return true;
371 }
372
373
374 bool
375 wxExtHelpController::DisplayContents()
376 {
377 if(! m_NumOfEntries)
378 return false;
379
380 wxString contents;
381 wxList::compatibility_iterator node = m_MapList->GetFirst();
382 wxExtHelpMapEntry *entry;
383 while(node)
384 {
385 entry = (wxExtHelpMapEntry *)node->GetData();
386 if(entry->id == CONTENTS_ID)
387 {
388 contents = entry->url;
389 break;
390 }
391 node = node->GetNext();
392 }
393
394 bool rc = false;
395 wxString file;
396 file << m_MapFile << wxFILE_SEP_PATH << contents;
397 if(file.Contains(wxT('#')))
398 file = file.BeforeLast(wxT('#'));
399 if(contents.length() && wxFileExists(file))
400 rc = DisplaySection(CONTENTS_ID);
401
402 // if not found, open homemade toc:
403 return rc ? true : KeywordSearch(wxEmptyString);
404 }
405
406 bool
407 wxExtHelpController::DisplaySection(int sectionNo)
408 {
409 if(! m_NumOfEntries)
410 return false;
411
412 wxBusyCursor b; // display a busy cursor
413 wxList::compatibility_iterator node = m_MapList->GetFirst();
414 wxExtHelpMapEntry *entry;
415 while(node)
416 {
417 entry = (wxExtHelpMapEntry *)node->GetData();
418 if(entry->id == sectionNo)
419 return DisplayHelp(entry->url);
420 node = node->GetNext();
421 }
422 return false;
423 }
424
425 bool wxExtHelpController::DisplaySection(const wxString& section)
426 {
427 bool isFilename = (section.Find(wxT(".htm")) != -1);
428
429 if (isFilename)
430 return DisplayHelp(section);
431 else
432 return KeywordSearch(section);
433 }
434
435 bool
436 wxExtHelpController::DisplayBlock(long blockNo)
437 {
438 return DisplaySection((int)blockNo);
439 }
440
441 bool
442 wxExtHelpController::KeywordSearch(const wxString& k,
443 wxHelpSearchMode WXUNUSED(mode))
444 {
445 if(! m_NumOfEntries)
446 return false;
447
448 wxString *choices = new wxString[m_NumOfEntries];
449 wxString *urls = new wxString[m_NumOfEntries];
450 wxString compA, compB;
451
452 int idx = 0, j;
453 bool rc;
454 bool showAll = k.empty();
455 wxList::compatibility_iterator node = m_MapList->GetFirst();
456 wxExtHelpMapEntry *entry;
457
458 {
459 wxBusyCursor b; // display a busy cursor
460 compA = k; compA.LowerCase(); // we compare case insensitive
461 while(node)
462 {
463 entry = (wxExtHelpMapEntry *)node->GetData();
464 compB = entry->doc; compB.LowerCase();
465 if((showAll || compB.Contains(k)) && ! compB.empty())
466 {
467 urls[idx] = entry->url;
468 // doesn't work:
469 // choices[idx] = (**i).doc.Contains((**i).doc.Before(WXEXTHELP_COMMENTCHAR));
470 //if(choices[idx].empty()) // didn't contain the ';'
471 // choices[idx] = (**i).doc;
472 choices[idx] = wxEmptyString;
473 for(j=0;entry->doc.c_str()[j]
474 && entry->doc.c_str()[j] != WXEXTHELP_COMMENTCHAR; j++)
475 choices[idx] << entry->doc.c_str()[j];
476 idx++;
477 }
478 node = node->GetNext();
479 }
480 }
481
482 if(idx == 1)
483 rc = DisplayHelp(urls[0]);
484 else if(idx == 0)
485 {
486 wxMessageBox(_("No entries found."));
487 rc = false;
488 }
489 else
490 {
491 idx = wxGetSingleChoiceIndex(showAll ? _("Help Index") : _("Relevant entries:"),
492 showAll ? _("Help Index") : _("Entries found"),
493 idx,choices);
494 if(idx != -1)
495 rc = DisplayHelp(urls[idx]);
496 else
497 rc = false;
498 }
499 delete[] urls;
500 delete[] choices;
501
502 return rc;
503 }
504
505
506 bool wxExtHelpController::Quit()
507 {
508 return true;
509 }
510
511 void wxExtHelpController::OnQuit()
512 {
513 }
514
515
516 #endif // wxUSE_HELP