source: git/src/aven.cc @ 36b2cc3

debug-cidebug-ci-sanitisersfaster-cavernlogwalls-datawalls-data-hanging-as-warning
Last change on this file since 36b2cc3 was 47f55ed, checked in by Olly Betts <olly@…>, 2 years ago

Don't force X11 if wxGLCanvas uses EGL

This requires wxWidgets 3.1.5.

  • Property mode set to 100644
File size: 13.7 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,2016,2017,2018 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#define MSG_SETUP_PROJ_SEARCH_PATH 1
29
30#include "aven.h"
31#include "log.h"
32#include "gla.h"
33#include "mainfrm.h"
34
35#include "cmdline.h"
36#include "message.h"
37#include "useful.h"
38
39#include <assert.h>
40#include <stdio.h>
41
42#include <wx/confbase.h>
43#include <wx/image.h>
44#if wxUSE_DISPLAY
45// wxDisplay was added in wx 2.5; but it may not be built for mingw (because
46// the header seems to be missing).
47#include <wx/display.h>
48#endif
49
50#ifdef __WXMSW__
51#include <windows.h>
52#endif
53
54static const struct option long_opts[] = {
55    /* const char *name; int has_arg (0 no_argument, 1 required_*, 2 optional_*); int *flag; int val; */
56    {"survey", required_argument, 0, 's'},
57    {"print", no_argument, 0, 'p'},
58    {"help", no_argument, 0, HLP_HELP},
59    {"version", no_argument, 0, HLP_VERSION},
60    {0, 0, 0, 0}
61};
62
63#define short_opts "s:p"
64
65static struct help_msg help[] = {
66    /*                          <-- */
67    /* TRANSLATORS: --help output for --survey option.
68     *
69     * "this" has been added to English translation */
70    {HLP_ENCODELONG(0),       /*only load the sub-survey with this prefix*/199, 0},
71    /* TRANSLATORS: --help output for aven --print option */
72    {HLP_ENCODELONG(1),       /*print and exit (requires a 3d file)*/119, 0},
73    {0, 0, 0}
74};
75
76#ifdef __WXMSW__
77IMPLEMENT_APP(Aven)
78#else
79IMPLEMENT_APP_NO_MAIN(Aven)
80IMPLEMENT_WX_THEME_SUPPORT
81#endif
82
83Aven::Aven() :
84    m_Frame(NULL), m_pageSetupData(NULL)
85{
86    wxFont::SetDefaultEncoding(wxFONTENCODING_UTF8);
87}
88
89Aven::~Aven()
90{
91    delete m_pageSetupData;
92}
93
94static int getopt_first_response = 0;
95
96static char ** utf8_argv;
97
98#ifdef __WXMSW__
99bool Aven::Initialize(int& my_argc, wxChar **my_argv)
100{
101    const wxChar * cmd_line = GetCommandLineW();
102
103    // Horrible bodge to handle therion's assumptions about the "Process"
104    // file association.
105    if (cmd_line) {
106        // None of these are valid aven command line options, so this is not
107        // going to be triggered accidentally.
108        const wxChar * p = wxStrstr(cmd_line,
109                                    wxT("aven.exe\" --quiet --log --output="));
110        if (p) {
111            // Just change the command name in the command line string - that
112            // way the quoting should match what the C runtime expects.
113            wxString cmd(cmd_line, p - cmd_line);
114            cmd += "cavern";
115            cmd += p + 4;
116            exit(wxExecute(cmd, wxEXEC_SYNC));
117        }
118    }
119
120    int utf8_argc;
121    {
122        // wxWidgets doesn't split up the command line in the standard way, so
123        // redo it ourselves using the standard API function.
124        //
125        // Warning: The returned array from this has no terminating NULL
126        // element.
127        wxChar ** new_argv = NULL;
128        if (cmd_line)
129            new_argv = CommandLineToArgvW(cmd_line, &utf8_argc);
130        bool failed = (new_argv == NULL);
131        if (failed) {
132            wxChar * p;
133            FormatMessage(
134                    FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
135                    NULL,
136                    GetLastError(),
137                    0,
138                    (LPWSTR)&p,
139                    4096,
140                    NULL);
141            wxString m = "CommandLineToArgvW failed: ";
142            m += p;
143            wxMessageBox(m, APP_NAME, wxOK | wxCENTRE | wxICON_EXCLAMATION);
144            LocalFree(p);
145            utf8_argc = my_argc;
146            new_argv = my_argv;
147        }
148
149        // Convert wide characters to UTF-8.
150        utf8_argv = new char * [utf8_argc + 1];
151        for (int i = 0; i < utf8_argc; ++i){
152            utf8_argv[i] = strdup(wxString(new_argv[i]).utf8_str());
153        }
154        utf8_argv[utf8_argc] = NULL;
155
156        if (!failed) LocalFree(new_argv);
157    }
158
159    msg_init(utf8_argv);
160    select_charset(CHARSET_UTF8);
161    /* Want --version and decent --help output, which cmdline does for us.
162     * wxCmdLine is much less good.
163     */
164    /* TRANSLATORS: Here "survey" is a "cave map" rather than list of questions
165     * - it should be translated to the terminology that cavers using the
166     * language would use.
167     *
168     * Part of aven --help */
169    cmdline_set_syntax_message(/*[SURVEY_FILE]*/269, 0, NULL);
170    cmdline_init(utf8_argc, utf8_argv, short_opts, long_opts, NULL, help, 0, 1);
171    getopt_first_response = cmdline_getopt();
172
173    // The argc and argv arguments don't actually get used here.
174    int dummy_argc = 0;
175    return wxApp::Initialize(dummy_argc, NULL);
176}
177#else
178int main(int argc, char **argv)
179{
180#ifdef __WXGTK3__
181# if !(wxUSE_GLCANVAS_EGL-0)
182    // The GLX-based wxGLCanvas doesn't work under Wayland, and the code
183    // segfaults: https://trac.wxwidgets.org/ticket/17702
184    //
185    // Therefore we force X11 unless we're using the EGL-based wxGLCanvas
186    // (which was added in wxWidgets 3.1.5 and hasn't been backported to
187    // 3.0.x).
188    //
189    // Setting GDK_BACKEND=x11 is the recommended workaround, and it seems to
190    // work to set it here.  GTK2 doesn't support Wayland, so doesn't need
191    // this.
192    setenv("GDK_BACKEND", "x11", 1);
193# endif
194
195    // FIXME: The OpenGL code needs work before scaling on hidpi displays will
196    // work usefully, so for now disable such scaling (which simulates how
197    // things are when using GTK2).
198    setenv("GDK_SCALE", "1", 1);
199#endif
200#ifdef __WXMAC__
201    // MacOS passes a magic -psn_XXXX command line argument in argv[1] which
202    // wx ignores for us, but in wxApp::Initialize() which hasn't been
203    // called yet.  So we need to remove it ourselves.
204    if (argc > 1 && strncmp(argv[1], "-psn_", 5) == 0) {
205        --argc;
206        memmove(argv + 1, argv + 2, argc * sizeof(char *));
207    }
208#endif
209    // Call msg_init() and start processing the command line first so that
210    // we can respond to --help and --version even without an X display.
211    msg_init(argv);
212    select_charset(CHARSET_UTF8);
213    /* Want --version and decent --help output, which cmdline does for us.
214     * wxCmdLine is much less good.
215     */
216    cmdline_set_syntax_message(/*[SURVEY_FILE]*/269, 0, NULL);
217    cmdline_init(argc, argv, short_opts, long_opts, NULL, help, 0, 1);
218    getopt_first_response = cmdline_getopt();
219
220    utf8_argv = argv;
221
222#if wxUSE_UNICODE
223    wxWCharBuffer buf(wxConvFileName->cMB2WX(argv[0]));
224    wxChar * wargv[2];
225    if (buf) {
226        wargv[0] = wxStrdup(buf);
227    } else {
228        // Eep - couldn't convert the executable's name to wide characters!
229        wargv[0] = wxStrdup(APP_NAME);
230    }
231    wargv[1] = NULL;
232    int wargc = 1;
233    return wxEntry(wargc, wargv);
234#else
235    char *dummy_argv[2] = { argv[0], NULL };
236    int dummy_argc = 1;
237    return wxEntry(dummy_argc, dummy_argv);
238#endif
239}
240#endif
241
242bool Aven::OnInit()
243{
244    wxLog::SetActiveTarget(new MyLogWindow());
245
246    {
247        // Suppress message box warnings about messages not found.
248        wxLogNull logNo;
249        wxLocale *loc = new wxLocale();
250        loc->AddCatalogLookupPathPrefix(wmsg_cfgpth());
251        wxString msg_lang_str(msg_lang, wxConvUTF8);
252        const char *lang = msg_lang2 ? msg_lang2 : msg_lang;
253        wxString lang_str(lang, wxConvUTF8);
254        loc->Init(msg_lang_str, lang_str, msg_lang_str);
255        // The existence of the wxLocale object is enough - no need to keep a
256        // pointer to it!
257    }
258
259    const char* opt_survey = NULL;
260    bool print_and_exit = false;
261
262    while (true) {
263        int opt;
264        if (getopt_first_response) {
265            opt = getopt_first_response;
266            getopt_first_response = 0;
267        } else {
268            opt = cmdline_getopt();
269        }
270        if (opt == EOF) break;
271        if (opt == 's') {
272            if (opt_survey != NULL) {
273                // FIXME: Not a helpful error, but this is temporary until
274                // we actually hook up support for specifying multiple
275                // --survey options properly here.
276                cmdline_syntax();
277                exit(1);
278            }
279            opt_survey = optarg;
280        }
281        if (opt == 'p') {
282            print_and_exit = true;
283        }
284    }
285
286    if (print_and_exit && !utf8_argv[optind]) {
287        cmdline_syntax(); // FIXME : not a helpful error...
288        exit(1);
289    }
290
291    wxString fnm;
292    if (utf8_argv[optind]) {
293        fnm = wxString(utf8_argv[optind], wxConvUTF8);
294        if (fnm.empty() && *(utf8_argv[optind])) {
295            ReportError(wxT("File argument's filename has bad encoding"));
296            return false;
297        }
298    }
299
300    if (!GLACanvas::check_visual()) {
301        wxString m;
302        /* TRANSLATORS: %s will be replaced with "Aven" currently (and
303         * perhaps by "Survex" or other things in future). */
304        m.Printf(wmsg(/*This version of %s requires OpenGL to work, but it isn’t available.*/405), APP_NAME);
305        wxMessageBox(m, APP_NAME, wxOK | wxCENTRE | wxICON_EXCLAMATION);
306        exit(1);
307    }
308
309    wxImage::AddHandler(new wxPNGHandler);
310
311    // Obtain the screen geometry.
312#if wxUSE_DISPLAY
313    wxRect geom = wxDisplay().GetGeometry();
314#else
315    wxRect geom;
316    wxClientDisplayRect(&geom.x, &geom.y, &geom.width, &geom.height);
317#endif
318
319    wxPoint pos(wxDefaultPosition);
320    int width, height;
321    wxConfigBase::Get()->Read(wxT("width"), &width, 0);
322    if (width > 0) wxConfigBase::Get()->Read(wxT("height"), &height, 0);
323    // We used to persist full screen mode (-1 was maximized,
324    // -2 full screen), but people would get stuck in full
325    // screen mode, unsure how to exit.
326    bool maximized = (width <= -1);
327    if (width <= 0 || height <= 0) {
328        pos.x = geom.x;
329        pos.y = geom.y;
330        width = geom.width;
331        height = geom.height;
332
333        // Calculate a reasonable size for our window.
334        pos.x += width / 8;
335        pos.y += height / 8;
336        width = width * 3 / 4;
337        height = height * 3 / 4;
338    } else {
339        // Impose a minimum size for sanity, and make sure the window fits on
340        // the display (in case the current display is smaller than the one
341        // in use when the window size was saved).  (480x320) is about the
342        // smallest usable size for aven's window.
343        const int min_width = min(geom.width, 480);
344        const int min_height = min(geom.height, 320);
345        if (width < min_width || height < min_height) {
346            if (width < min_width) {
347                width = min_width;
348            }
349            if (height < min_height) {
350                height = min_height;
351            }
352            pos.x = geom.x + (geom.width - width) / 4;
353            pos.y = geom.y + (geom.height - height) / 4;
354        }
355    }
356
357    // Create the main window.
358    m_Frame = new MainFrm(APP_NAME, pos, wxSize(width, height));
359
360    // Select maximised if that's the saved state.
361    if (maximized) {
362        m_Frame->Maximize();
363    }
364
365    if (utf8_argv[optind]) {
366        if (!opt_survey) opt_survey = "";
367        m_Frame->OpenFile(fnm, wxString(opt_survey, wxConvUTF8));
368    }
369
370    if (print_and_exit) {
371        m_Frame->PrintAndExit();
372        return true;
373    }
374
375    m_Frame->Show(true);
376#ifdef _WIN32
377    m_Frame->SetFocus();
378#endif
379    return true;
380}
381
382wxPageSetupDialogData *
383Aven::GetPageSetupDialogData()
384{
385    if (!m_pageSetupData) m_pageSetupData = new wxPageSetupDialogData;
386#ifdef __WXGTK__
387    // Fetch paper margins stored on disk.
388    int left, right, top, bottom;
389    wxConfigBase * cfg = wxConfigBase::Get();
390    // These default margins were chosen by looking at all the .ppd files
391    // on my machine.
392    cfg->Read(wxT("paper_margin_left"), &left, 7);
393    cfg->Read(wxT("paper_margin_right"), &right, 7);
394    cfg->Read(wxT("paper_margin_top"), &top, 14);
395    cfg->Read(wxT("paper_margin_bottom"), &bottom, 14);
396    m_pageSetupData->SetMarginTopLeft(wxPoint(left, top));
397    m_pageSetupData->SetMarginBottomRight(wxPoint(right, bottom));
398#endif
399    return m_pageSetupData;
400}
401
402void
403Aven::SetPageSetupDialogData(const wxPageSetupDialogData & psdd)
404{
405    if (!m_pageSetupData) m_pageSetupData = new wxPageSetupDialogData;
406    *m_pageSetupData = psdd;
407#ifdef __WXGTK__
408    wxPoint topleft = psdd.GetMarginTopLeft();
409    wxPoint bottomright = psdd.GetMarginBottomRight();
410
411    // Store user specified paper margins on disk/in registry.
412    wxConfigBase * cfg = wxConfigBase::Get();
413    cfg->Write(wxT("paper_margin_left"), topleft.x);
414    cfg->Write(wxT("paper_margin_right"), bottomright.x);
415    cfg->Write(wxT("paper_margin_top"), topleft.y);
416    cfg->Write(wxT("paper_margin_bottom"), bottomright.y);
417    cfg->Flush();
418#endif
419}
420
421#ifdef __WXMAC__
422void
423Aven::MacOpenFiles(const wxArrayString & filenames)
424{
425    if (filenames.size() != 1) {
426        ReportError(wxT("Aven can only load one file at a time"));
427        return;
428    }
429    m_Frame->OpenFile(filenames[0], wxString());
430}
431
432void
433Aven::MacPrintFiles(const wxArrayString & filenames)
434{
435    if (filenames.size() != 1) {
436        ReportError(wxT("Aven can only print one file at a time"));
437        return;
438    }
439    m_Frame->OpenFile(filenames[0], wxString());
440    m_Frame->PrintAndExit();
441}
442#endif
443
444void Aven::ReportError(const wxString& msg)
445{
446    if (!m_Frame) {
447        wxMessageBox(msg, APP_NAME, wxOK | wxICON_ERROR);
448        return;
449    }
450    wxMessageDialog dlg(m_Frame, msg, APP_NAME, wxOK | wxICON_ERROR);
451    dlg.ShowModal();
452}
453
454const wxString &
455wmsg_cfgpth()
456{
457    static wxString path;
458    if (path.empty())
459        path = wxString(msg_cfgpth(), wxConvUTF8);
460    return path;
461}
462
463// called to report errors by message.c
464extern "C" void
465aven_v_report(int severity, const char *fnm, int line, int en, va_list ap)
466{
467    wxString m;
468    if (fnm) {
469        m = wxString(fnm, wxConvUTF8);
470        if (line) m += wxString::Format(wxT(":%d"), line);
471        m += wxT(": ");
472    }
473
474    if (severity == DIAG_WARN) {
475        m += wmsg(/*warning*/4);
476        m += wxT(": ");
477    }
478
479    char buf[1024];
480    vsnprintf(buf, sizeof(buf), msg(en), ap);
481    m += wxString(buf, wxConvUTF8);
482    if (wxTheApp == NULL) {
483        // We haven't initialised the Aven app object yet.
484        if (!wxInitialize()) {
485            fputs(buf, stderr);
486            PUTC('\n', stderr);
487            exit(1);
488        }
489        wxMessageBox(m, APP_NAME, wxOK | wxICON_ERROR);
490        wxUninitialize();
491    } else {
492        wxGetApp().ReportError(m);
493    }
494}
Note: See TracBrowser for help on using the repository browser.