source: git/src/cavernlog.cc @ 6baad4a

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-data
Last change on this file since 6baad4a was 6baad4a, checked in by Olly Betts <olly@…>, 14 years ago

src/cavernlog.cc: Fix to work on Microsoft Windows.

git-svn-id: file:///home/survex-svn/survex/trunk@3557 4b37db11-9a0c-4f06-9ece-9ab7cdaee568

  • Property mode set to 100644
File size: 9.5 KB
Line 
1/* cavernlog.cc
2 * Run cavern inside an Aven window
3 *
4 * Copyright (C) 2005,2006,2010 Olly Betts
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19 */
20
21#ifdef HAVE_CONFIG_H
22# include <config.h>
23#endif
24
25#include "aven.h"
26#include "cavernlog.h"
27#include "filename.h"
28#include "mainfrm.h"
29#include "message.h"
30
31#include <errno.h>
32#include <stdio.h>
33#include <stdlib.h>
34
35// For select():
36#ifdef HAVE_SYS_SELECT_H
37#include <sys/select.h>
38#endif
39#include <sys/time.h>
40#include <sys/types.h>
41#include <unistd.h>
42
43enum { LOG_REPROCESS = 1234 };
44
45BEGIN_EVENT_TABLE(CavernLogWindow, wxHtmlWindow)
46    EVT_BUTTON(LOG_REPROCESS, CavernLogWindow::OnReprocess)
47    EVT_BUTTON(wxID_OK, CavernLogWindow::OnOK)
48END_EVENT_TABLE()
49
50static wxString escape_for_shell(wxString s, bool protect_dash = false)
51{
52    size_t p = 0;
53#ifdef __WXMSW__
54    bool needs_quotes = false;
55    while (p < s.size()) {
56        wxChar ch = s[p];
57        if (ch < 127) {
58            if (ch == wxT('"')) {
59                s.insert(p, 1, wxT('\\'));
60                ++p;
61                needs_quotes = true;
62            } else if (strchr(" <>&|^", ch)) {
63                needs_quotes = true;
64            }
65        }
66        ++p;
67    }
68    if (needs_quotes) {
69        s.insert(0u, 1, wxT('"'));
70        s += wxT('"');
71    }
72#else
73    if (protect_dash && !s.empty() && s[0u] == '-') {
74        // If the filename starts with a '-', protect it from being
75        // treated as an option by prepending "./".
76        s.insert(0, wxT("./"));
77        p = 2;
78    }
79    while (p < s.size()) {
80        // Exclude a few safe characters which are common in filenames
81        if (!isalnum(s[p]) && strchr("/._-", s[p]) == NULL) {
82            s.insert(p, 1, wxT('\\'));
83            ++p;
84        }
85        ++p;
86    }
87#endif
88    return s;
89}
90
91CavernLogWindow::CavernLogWindow(MainFrm * mainfrm_, wxWindow * parent)
92    : wxHtmlWindow(parent), mainfrm(mainfrm_)
93{
94    int fsize = parent->GetFont().GetPointSize();
95    int sizes[7] = { fsize, fsize, fsize, fsize, fsize, fsize, fsize };
96    SetFonts(wxString(), wxString(), sizes);
97}
98
99void
100CavernLogWindow::OnLinkClicked(const wxHtmlLinkInfo &link)
101{
102    wxString href = link.GetHref();
103    wxString title = link.GetTarget();
104    size_t colon = href.rfind(wxT(':'));
105    if (colon != wxString::npos) {
106#ifdef __WXMSW__
107        wxString cmd = wxT("notepad $f");
108#else
109        wxString cmd = wxT("x-terminal-emulator -title $t -e vim -c $l $f");
110        // wxString cmd = "x-terminal-emulator -title $t -e emacs +$l $f";
111        // wxString cmd = "x-terminal-emulator -title $t -e nano +$l $f";
112        // wxString cmd = "x-terminal-emulator -title $t -e jed -g $l $f";
113#endif
114        const char * p = getenv("SURVEXEDITOR");
115        if (p) {
116            cmd = wxString(p, wxConvUTF8);
117            if (!cmd.find(wxT("$f"))) {
118                cmd += wxT(" $f");
119            }
120        }
121        size_t i = 0;
122        while ((i = cmd.find(wxT('$'), i)) != wxString::npos) {
123            if (++i >= cmd.size()) break;
124            switch (cmd[i]) {
125                case wxT('$'):
126                    cmd.erase(i, 1);
127                    break;
128                case wxT('f'): {
129                    wxString f = escape_for_shell(href.substr(0, colon), true);
130                    cmd.replace(i - 1, 2, f);
131                    i += f.size() - 1;
132                    break;
133                }
134                case wxT('t'): {
135                    wxString t = escape_for_shell(title);
136                    cmd.replace(i - 1, 2, t);
137                    i += t.size() - 1;
138                    break;
139                }
140                case wxT('l'): {
141                    wxString l = escape_for_shell(href.substr(colon + 1));
142                    cmd.replace(i - 1, 2, l);
143                    i += l.size() - 1;
144                    break;
145                }
146                default:
147                    ++i;
148            }
149        }
150#ifdef __WXMSW__
151        _wsystem(cmd.c_str());
152#else
153        system(cmd.mb_str());
154#endif
155    }
156}
157
158int
159CavernLogWindow::process(const wxString &file)
160{
161    SetFocus();
162    filename = file;
163
164#ifdef __WXMSW__
165    SetEnvironmentVariable(wxT("SURVEX_UTF8"), wxT("1"));
166#else
167    setenv("SURVEX_UTF8", "1", 1);
168#endif
169
170    wxString escaped_file = escape_for_shell(file, true);
171#ifdef __WXMSW__
172    wxString cmd;
173    {
174        DWORD len = 256;
175        wchar_t *buf = NULL, *p;
176        while (1) {
177            DWORD got;
178            buf = (wchar_t*)osrealloc(buf, len * 2);
179            got = GetModuleFileNameW(NULL, buf, len);
180            if (got < len) break;
181            len += len;
182        }
183        /* Strange Win32 nastiness - strip prefix "\\?\" if present */
184        if (wcsncmp(buf, L"\\\\?\\", 4) == 0) buf += 4;
185        p = wcsrchr(buf, L'\\');
186        wchar_t * slash = wcsrchr(buf, L'\\');
187        if (slash) {
188            cmd.assign(buf, slash - buf + 1);
189        }
190    }
191    cmd += L"cavern";
192    cmd = escape_for_shell(cmd, false);
193#else
194    char *cavern = use_path(msg_exepth(), "cavern");
195    wxString cmd = escape_for_shell(wxString(cavern, wxConvUTF8), false);
196    osfree(cavern);
197#endif
198    cmd += wxT(" -o ");
199    cmd += escaped_file;
200    cmd += wxT(' ');
201    cmd += escaped_file;
202
203#ifdef __WXMSW__
204    FILE * cavern_out = _wpopen(cmd.c_str(), L"r");
205#else
206    FILE * cavern_out = popen(cmd.mb_str(), "r");
207#endif
208    if (!cavern_out) {
209        wxString m;
210        m.Printf(wmsg(/*Couldn't open pipe: `%s'*/17), cmd.c_str());
211        m += wxT(" (");
212        m += wxString(strerror(errno), wxConvUTF8);
213        m += wxT(')');
214        wxGetApp().ReportError(m);
215        return -2;
216    }
217
218    int cavern_fd;
219#ifdef __WXMSW__
220    cavern_fd = _fileno(cavern_out);
221#else
222    cavern_fd = fileno(cavern_out);
223#endif
224    assert(cavern_fd < FD_SETSIZE); // FIXME we shouldn't just assert, but what else to do?
225    wxString cur;
226    int link_count = 0;
227    // We're only guaranteed one character of pushback by ungetc() but we
228    // need two so for portability we implement the second ourselves.
229    int left = EOF;
230    while (!feof(cavern_out)) {
231        fd_set rfds, efds;
232        FD_ZERO(&rfds);
233        FD_SET(cavern_fd, &rfds);
234        FD_ZERO(&efds);
235        FD_SET(cavern_fd, &efds);
236        // Timeout instantly.
237        struct timeval timeout;
238        timeout.tv_sec = 0;
239        timeout.tv_usec = 0;
240        if (select(cavern_fd + 1, &rfds, NULL, &efds, &timeout) == 0) {
241            Update();
242            FD_SET(cavern_fd, &rfds);
243            FD_SET(cavern_fd, &efds);
244            // Set timeout to 0.1 seconds.
245            timeout.tv_sec = 0;
246            timeout.tv_usec = 100000;
247            if (select(cavern_fd + 1, &rfds, NULL, &efds, &timeout) == 0) {
248                wxYield();
249                continue;
250            }
251        }
252        if (!FD_ISSET(cavern_fd, &rfds)) {
253            // Error, which pclose() should report.
254            break;
255        }
256        int ch;
257        if (left == EOF) {
258            ch = GETC(cavern_out);
259            if (ch == EOF) break;
260        } else {
261            ch = left;
262            left = EOF;
263        }
264        // Decode UTF-8 first to avoid security issues with <, >, &, etc
265        // encoded using multibyte encodings.
266        if (ch >= 0xc0 && ch < 0xf0) {
267            int ch1 = GETC(cavern_out);
268            if ((ch1 & 0xc0) != 0x80) {
269                left = ch1;
270            } else if (ch < 0xe0) {
271                /* 2 byte sequence */
272                ch = ((ch & 0x1f) << 6) | (ch1 & 0x3f);
273            } else {
274                /* 3 byte sequence */
275                int ch2 = GETC(cavern_out);
276                if ((ch2 & 0xc0) != 0x80) {
277                    ungetc(ch2, cavern_out);
278                    left = ch1;
279                } else {
280                    ch = ((ch & 0x1f) << 12) | ((ch1 & 0x3f) << 6) | (ch2 & 0x3f);
281                }
282            }
283        }
284
285        switch (ch) {
286            case '\r':
287                // Ignore.
288                break;
289            case '\n': {
290                if (cur.empty()) continue;
291#ifndef __WXMSW__
292                size_t colon = cur.find(':');
293#else
294                // If the path is "C:\path\to\file.svx" then don't split at the
295                // : after the drive letter!  FIXME: better to look for ": "?
296                size_t colon = cur.find(':', 2);
297#endif
298                if (colon != wxString::npos && colon < cur.size() - 1) {
299                    ++colon;
300                    size_t i = colon;
301                    while (i < cur.size() - 1 &&
302                           cur[i] >= wxT('0') && cur[i] <= wxT('9')) {
303                        ++i;
304                    }
305                    if (i > colon && cur[i] == wxT(':') ) {
306                        colon = i;
307                        wxString tag = wxT("<a href=\"");
308                        tag.append(cur, 0, colon);
309                        while (cur[++i] == wxT(' ')) { }
310                        tag += wxT("\" target=\"");
311                        tag.append(cur, i, wxString::npos);
312                        tag += wxT("\">");
313                        cur.insert(0, tag);
314                        cur.insert(colon + tag.size(), wxT("</a>"));
315                        ++link_count;
316                    }
317                }
318
319                // Save the scrollbar positions.
320                int scroll_x = 0, scroll_y = 0;
321                GetViewStart(&scroll_x, &scroll_y);
322
323                cur += wxT("<br>\n");
324                AppendToPage(cur);
325
326                if (!link_count) {
327                    // Auto-scroll the window until we've reported a warning or
328                    // error.
329                    int x, y;
330                    GetVirtualSize(&x, &y);
331                    int xs, ys;
332                    GetClientSize(&xs, &ys);
333                    y -= ys;
334                    int xu, yu;
335                    GetScrollPixelsPerUnit(&xu, &yu);
336                    Scroll(scroll_x, y / yu);
337                } else {
338                    // Restore the scrollbar positions.
339                    Scroll(scroll_x, scroll_y);
340                }
341
342                cur.clear();
343                break;
344            }
345            case '<':
346                cur += wxT("&lt;");
347                break;
348            case '>':
349                cur += wxT("&gt;");
350                break;
351            case '&':
352                cur += wxT("&amp;");
353                break;
354            case '"':
355                cur += wxT("&#22;");
356                continue;
357            default:
358                if (ch >= 128) {
359                    cur += wxString::Format(wxT("&#%u;"), ch);
360                } else {
361                    cur += (char)ch;
362                }
363        }
364    }
365
366    int retval = pclose(cavern_out);
367    if (retval) {
368        AppendToPage(wxT("<avenbutton default id=1234 name=\"Reprocess\">"));
369        if (retval == -1) {
370            wxString m = wxT("Problem running cavern: ");
371            m += wxString(strerror(errno), wxConvUTF8);
372            wxGetApp().ReportError(m);
373            return -2;
374        }
375        return -1;
376    }
377    if (link_count) {
378        AppendToPage(wxT("<avenbutton id=1234 name=\"Reprocess\">"));
379        AppendToPage(wxString::Format(wxT("<avenbutton default id=%d>"), (int)wxID_OK));
380        Update();
381    }
382    return link_count;
383}
384
385void
386CavernLogWindow::OnReprocess(wxCommandEvent & e)
387{
388    SetPage(wxString());
389    if (process(filename) == 0) {
390        OnOK(e);
391    }
392}
393
394void
395CavernLogWindow::OnOK(wxCommandEvent &)
396{
397    mainfrm->InitialiseAfterLoad(filename);
398}
Note: See TracBrowser for help on using the repository browser.