source: git/src/aven.cc @ 6138f60

stereo-2025
Last change on this file since 6138f60 was 7962c9d, checked in by Olly Betts <olly@…>, 4 months ago

Renumber messages to align with IMG_* error codes

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