source: git/src/aven.cc @ 52dad0e

RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernloglog-selectstereowalls-datawalls-data-hanging-as-warningwarn-only-for-hanging-survey
Last change on this file since 52dad0e was b208d0b, checked in by Olly Betts <olly@…>, 9 years ago

src/aven.cc: Add workaround for therion's assumptions about the
"Process" file association.

  • Property mode set to 100644
File size: 12.4 KB
Line 
1//
2//  aven.cc
3//
4//  Main class for Aven.
5//
6//  Copyright (C) 2001 Mark R. Shinwell.
7//  Copyright (C) 2002,2003,2004,2005,2006,2011,2013,2014,2015 Olly Betts
8//
9//  This program is free software; you can redistribute it and/or modify
10//  it under the terms of the GNU General Public License as published by
11//  the Free Software Foundation; either version 2 of the License, or
12//  (at your option) any later version.
13//
14//  This program is distributed in the hope that it will be useful,
15//  but WITHOUT ANY WARRANTY; without even the implied warranty of
16//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17//  GNU General Public License for more details.
18//
19//  You should have received a copy of the GNU General Public License
20//  along with this program; if not, write to the Free Software
21//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
22//
23
24#ifdef HAVE_CONFIG_H
25#include <config.h>
26#endif
27
28#include "aven.h"
29#include "log.h"
30#include "mainfrm.h"
31
32#include "cmdline.h"
33#include "message.h"
34#include "useful.h"
35
36#include <assert.h>
37#include <stdio.h>
38
39#include <wx/confbase.h>
40#include <wx/image.h>
41#if wxUSE_DISPLAY
42// wxDisplay was added in wx 2.5; but it may not be built for mingw (because
43// the header seems to be missing).
44#include <wx/display.h>
45#endif
46
47#if defined __WXMAC__ || defined __WXMSW__
48#include <proj_api.h>
49#endif
50
51bool double_buffered = false;
52
53static const struct option long_opts[] = {
54    /* const char *name; int has_arg (0 no_argument, 1 required_*, 2 optional_*); int *flag; int val; */
55    {"survey", required_argument, 0, 's'},
56    {"print", no_argument, 0, 'p'},
57    {"help", no_argument, 0, HLP_HELP},
58    {"version", no_argument, 0, HLP_VERSION},
59    {0, 0, 0, 0}
60};
61
62#define short_opts "s:p"
63
64static struct help_msg help[] = {
65    /*                          <-- */
66    /* TRANSLATORS: --help output for --survey option.
67     *
68     * "this" has been added to English translation */
69    {HLP_ENCODELONG(0),       /*only load the sub-survey with this prefix*/199, 0},
70    /* TRANSLATORS: --help output for aven --print option */
71    {HLP_ENCODELONG(1),       /*print and exit (requires a 3d file)*/119, 0},
72    {0, 0, 0}
73};
74
75#ifdef __WXMSW__
76IMPLEMENT_APP(Aven)
77#else
78IMPLEMENT_APP_NO_MAIN(Aven)
79IMPLEMENT_WX_THEME_SUPPORT
80#endif
81
82Aven::Aven() :
83    m_Frame(NULL), m_pageSetupData(NULL)
84{
85    wxFont::SetDefaultEncoding(wxFONTENCODING_UTF8);
86}
87
88Aven::~Aven()
89{
90    delete m_pageSetupData;
91}
92
93static int getopt_first_response = 0;
94
95static char ** utf8_argv;
96
97#ifdef __WXMSW__
98bool Aven::Initialize(int& my_argc, wxChar **my_argv)
99{
100    // Horrible bodge to handle therion's assumptions about the "Process"
101    // file association.
102    if (my_argc == 5 &&
103        wxStrcmp(my_argv[1], wxT("--quiet")) == 0 &&
104        wxStrcmp(my_argv[2], wxT("--log")) == 0 &&
105        wxStrncmp(my_argv[3], wxT("--output="), 9) == 0) {
106        wxString cavern = my_argv[0];
107        int slash = max(cavern.Find(wxT('/'), true),
108                        cavern.Find(wxT('\\'), true));
109        // wxNOT_FOUND is -1, so this should work even if there's no slash.
110        cavern.replace(slash + 1, wxString::npos, wxT("cavern.exe"));
111        my_argv[0] = const_cast<wxChar*>((const wxChar*)cavern.c_str());
112        exit(wxExecute(my_argv, wxEXEC_SYNC));
113    }
114
115    // wxWidgets passes us wxChars, which may be wide characters but cmdline
116    // wants UTF-8 so we need to convert.
117    utf8_argv = new char * [my_argc + 1];
118    for (int i = 0; i < my_argc; ++i){
119        utf8_argv[i] = strdup(wxString(my_argv[i]).mb_str());
120    }
121    utf8_argv[my_argc] = NULL;
122
123    msg_init(utf8_argv);
124    pj_set_finder(msg_proj_finder);
125    select_charset(CHARSET_UTF8);
126    /* Want --version and decent --help output, which cmdline does for us.
127     * wxCmdLine is much less good.
128     */
129    /* TRANSLATORS: Here "survey" is a "cave map" rather than list of questions
130     * - it should be translated to the terminology that cavers using the
131     * language would use.
132     *
133     * Part of aven --help */
134    cmdline_set_syntax_message(/*[SURVEY_FILE]*/269, 0, NULL);
135    cmdline_init(my_argc, utf8_argv, short_opts, long_opts, NULL, help, 0, 1);
136    getopt_first_response = cmdline_getopt();
137    return wxApp::Initialize(my_argc, my_argv);
138}
139#else
140int main(int argc, char **argv)
141{
142#ifdef __WXMAC__
143    // MacOS passes a magic -psn_XXXX command line argument in argv[1] which
144    // wx ignores for us, but in wxApp::Initialize() which hasn't been
145    // called yet.  So we need to remove it ourselves.
146    if (argc > 1 && strncmp(argv[1], "-psn_", 5) == 0) {
147        --argc;
148        memmove(argv + 1, argv + 2, argc * sizeof(char *));
149    }
150#endif
151    // Call msg_init() and start processing the command line first so that
152    // we can respond to --help and --version even without an X display.
153    msg_init(argv);
154#ifdef __WXMAC__
155    pj_set_finder(msg_proj_finder);
156#endif
157    select_charset(CHARSET_UTF8);
158    /* Want --version and decent --help output, which cmdline does for us.
159     * wxCmdLine is much less good.
160     */
161    cmdline_set_syntax_message(/*[SURVEY_FILE]*/269, 0, NULL);
162    cmdline_init(argc, argv, short_opts, long_opts, NULL, help, 0, 1);
163    getopt_first_response = cmdline_getopt();
164
165    utf8_argv = argv;
166
167#if wxUSE_UNICODE
168    wxWCharBuffer buf(wxConvFileName->cMB2WX(argv[0]));
169    wxChar * wargv[2];
170    if (buf) {
171        wargv[0] = wxStrdup(buf);
172    } else {
173        // Eep - couldn't convert the executable's name to wide characters!
174        wargv[0] = wxStrdup(APP_NAME);
175    }
176    wargv[1] = NULL;
177    int wargc = 1;
178    return wxEntry(wargc, wargv);
179#else
180    char *dummy_argv[2] = { argv[0], NULL };
181    int dummy_argc = 1;
182    return wxEntry(dummy_argc, dummy_argv);
183#endif
184}
185#endif
186
187bool Aven::OnInit()
188{
189    wxLog::SetActiveTarget(new MyLogWindow());
190
191    {
192        // Suppress message box warnings about messages not found.
193        wxLogNull logNo;
194        wxLocale *loc = new wxLocale();
195        loc->AddCatalogLookupPathPrefix(wmsg_cfgpth());
196        wxString msg_lang_str(msg_lang, wxConvUTF8);
197        const char *lang = msg_lang2 ? msg_lang2 : msg_lang;
198        wxString lang_str(lang, wxConvUTF8);
199#if wxCHECK_VERSION(2,9,0)
200        loc->Init(msg_lang_str, lang_str, msg_lang_str);
201#else
202        loc->Init(msg_lang_str, lang_str, msg_lang_str, true, true);
203#endif
204        // The existence of the wxLocale object is enough - no need to keep a
205        // pointer to it!
206    }
207
208    wxString survey;
209    bool print_and_exit = false;
210
211    while (true) {
212        int opt;
213        if (getopt_first_response) {
214            opt = getopt_first_response;
215            getopt_first_response = 0;
216        } else {
217            opt = cmdline_getopt();
218        }
219        if (opt == EOF) break;
220        if (opt == 's') {
221            survey = wxString(optarg, wxConvUTF8);
222        }
223        if (opt == 'p') {
224            print_and_exit = true;
225        }
226    }
227
228    if (print_and_exit && !utf8_argv[optind]) {
229        cmdline_syntax(); // FIXME : not a helpful error...
230        exit(1);
231    }
232
233    wxString fnm;
234    if (utf8_argv[optind]) {
235        fnm = wxString(utf8_argv[optind], wxConvUTF8);
236        if (fnm.empty() && *(utf8_argv[optind])) {
237            ReportError(wxT("File argument's filename has bad encoding"));
238            return false;
239        }
240    }
241
242    // Use a double-buffered visual if available, as it will give much smoother
243    // animation.
244    double_buffered = true;
245    const int wx_gl_attribs[] = {
246        WX_GL_DOUBLEBUFFER,
247        WX_GL_RGBA,
248        0
249    };
250    if (!InitGLVisual(wx_gl_attribs)) {
251        if (!InitGLVisual(wx_gl_attribs + 1)) {
252            wxString m;
253            /* TRANSLATORS: %s will be replaced with "Aven" currently (and
254             * perhaps by "Survex" or other things in future). */
255            m.Printf(wmsg(/*This version of %s requires OpenGL to work, but it isn’t available.*/405), APP_NAME);
256            wxMessageBox(m, APP_NAME, wxOK | wxCENTRE | wxICON_EXCLAMATION);
257            exit(1);
258        }
259        double_buffered = false;
260    }
261
262    wxImage::AddHandler(new wxPNGHandler);
263
264    // Obtain the screen geometry.
265#if wxUSE_DISPLAY
266    wxRect geom = wxDisplay().GetGeometry();
267#else
268    wxRect geom;
269    wxClientDisplayRect(&geom.x, &geom.y, &geom.width, &geom.height);
270#endif
271
272    wxPoint pos(wxDefaultPosition);
273    int width, height;
274    wxConfigBase::Get()->Read(wxT("width"), &width, 0);
275    if (width > 0) wxConfigBase::Get()->Read(wxT("height"), &height, 0);
276    // We used to persist full screen mode (-1 was maximized,
277    // -2 full screen), but people would get stuck in full
278    // screen mode, unsure how to exit.
279    bool maximized = (width <= -1);
280    if (width <= 0 || height <= 0) {
281        pos.x = geom.x;
282        pos.y = geom.y;
283        width = geom.width;
284        height = geom.height;
285
286        // Calculate a reasonable size for our window.
287        pos.x += width / 8;
288        pos.y += height / 8;
289        width = width * 3 / 4;
290        height = height * 3 / 4;
291    } else {
292        // Impose a minimum size for sanity, and make sure the window fits on
293        // the display (in case the current display is smaller than the one
294        // in use when the window size was saved).  (480x320) is about the
295        // smallest usable size for aven's window.
296        const int min_width = min(geom.width, 480);
297        const int min_height = min(geom.height, 320);
298        if (width < min_width || height < min_height) {
299            if (width < min_width) {
300                width = min_width;
301            }
302            if (height < min_height) {
303                height = min_height;
304            }
305            pos.x = geom.x + (geom.width - width) / 4;
306            pos.y = geom.y + (geom.height - height) / 4;
307        }
308    }
309
310    // Create the main window.
311    m_Frame = new MainFrm(APP_NAME, pos, wxSize(width, height));
312
313    // Select maximised if that's the saved state.
314    if (maximized) {
315        m_Frame->Maximize();
316    }
317
318    if (utf8_argv[optind]) {
319        m_Frame->OpenFile(fnm, survey);
320    }
321
322    if (print_and_exit) {
323        m_Frame->PrintAndExit();
324        return true;
325    }
326
327    m_Frame->Show(true);
328#ifdef _WIN32
329    m_Frame->SetFocus();
330#endif
331    return true;
332}
333
334wxPageSetupDialogData *
335Aven::GetPageSetupDialogData()
336{
337    if (!m_pageSetupData) m_pageSetupData = new wxPageSetupDialogData;
338#ifdef __WXGTK__
339    // Fetch paper margins stored on disk.
340    int left, right, top, bottom;
341    wxConfigBase * cfg = wxConfigBase::Get();
342    // These default margins were chosen by looking at all the .ppd files
343    // on my machine.
344    cfg->Read(wxT("paper_margin_left"), &left, 7);
345    cfg->Read(wxT("paper_margin_right"), &right, 7);
346    cfg->Read(wxT("paper_margin_top"), &top, 14);
347    cfg->Read(wxT("paper_margin_bottom"), &bottom, 14);
348    m_pageSetupData->SetMarginTopLeft(wxPoint(left, top));
349    m_pageSetupData->SetMarginBottomRight(wxPoint(right, bottom));
350#endif
351    return m_pageSetupData;
352}
353
354void
355Aven::SetPageSetupDialogData(const wxPageSetupDialogData & psdd)
356{
357    if (!m_pageSetupData) m_pageSetupData = new wxPageSetupDialogData;
358    *m_pageSetupData = psdd;
359#ifdef __WXGTK__
360    wxPoint topleft = psdd.GetMarginTopLeft();
361    wxPoint bottomright = psdd.GetMarginBottomRight();
362
363    // Store user specified paper margins on disk/in registry.
364    wxConfigBase * cfg = wxConfigBase::Get();
365    cfg->Write(wxT("paper_margin_left"), topleft.x);
366    cfg->Write(wxT("paper_margin_right"), bottomright.x);
367    cfg->Write(wxT("paper_margin_top"), topleft.y);
368    cfg->Write(wxT("paper_margin_bottom"), bottomright.y);
369    cfg->Flush();
370#endif
371}
372
373#ifdef __WXMAC__
374void
375Aven::MacOpenFiles(const wxArrayString & filenames)
376{
377    if (filenames.size() != 1) {
378        ReportError(wxT("Aven can only load one file at a time"));
379        return;
380    }
381    m_Frame->OpenFile(filenames[0], wxString());
382}
383
384void
385Aven::MacPrintFiles(const wxArrayString & filenames)
386{
387    if (filenames.size() != 1) {
388        ReportError(wxT("Aven can only print one file at a time"));
389        return;
390    }
391    m_Frame->OpenFile(filenames[0], wxString());
392    m_Frame->PrintAndExit();
393}
394#endif
395
396void Aven::ReportError(const wxString& msg)
397{
398    if (!m_Frame) {
399        wxMessageBox(msg, APP_NAME, wxOK | wxICON_ERROR);
400        return;
401    }
402    AvenAllowOnTop ontop(m_Frame);
403    wxMessageDialog dlg(m_Frame, msg, APP_NAME, wxOK | wxICON_ERROR);
404    dlg.ShowModal();
405}
406
407wxString
408wmsg(int msg_no)
409{
410    return wxString::FromUTF8(msg(msg_no));
411}
412
413const wxString &
414wmsg_cfgpth()
415{
416    static wxString path;
417    if (path.empty())
418        path = wxString(msg_cfgpth(), wxConvUTF8);
419    return path;
420}
421
422// called to report errors by message.c
423extern "C" void
424aven_v_report(int severity, const char *fnm, int line, int en, va_list ap)
425{
426    wxString m;
427    if (fnm) {
428        m = wxString(fnm, wxConvUTF8);
429        if (line) m += wxString::Format(wxT(":%d"), line);
430        m += wxT(": ");
431    }
432
433    if (severity == 0) {
434        m += wmsg(/*warning*/4);
435        m += wxT(": ");
436    }
437
438    char buf[1024];
439    vsnprintf(buf, sizeof(buf), msg(en), ap);
440    m += wxString(buf, wxConvUTF8);
441    if (wxTheApp == NULL) {
442        // We haven't initialised the Aven app object yet.
443        if (!wxInitialize()) {
444            fputs(buf, stderr);
445            PUTC('\n', stderr);
446            exit(1);
447        }
448        wxMessageBox(m, APP_NAME, wxOK | wxICON_ERROR);
449        wxUninitialize();
450    } else {
451        wxGetApp().ReportError(m);
452    }
453}
Note: See TracBrowser for help on using the repository browser.