source: git/src/aven.cc @ 3910312

stereo-2025
Last change on this file since 3910312 was 7af6fff, checked in by Olly Betts <olly@…>, 4 months ago

Refactor around min() and max() macros

These are only used in img.c so only define them there.

  • Property mode set to 100644
File size: 13.7 KB
RevLine 
[0060ba5]1//
[203d2a7]2//  aven.cc
[0060ba5]3//
[5809313]4//  Main class for Aven.
[0060ba5]5//
[3675a18]6//  Copyright (C) 2001 Mark R. Shinwell.
[dba56bb]7//  Copyright (C) 2002-2024 Olly Betts
[0060ba5]8//
[89231c4]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.
[0060ba5]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
[89231c4]16//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17//  GNU General Public License for more details.
[0060ba5]18//
[89231c4]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
[ecbc6c18]21//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
[5809313]22//
[0060ba5]23
[b462168]24#include <config.h>
25
[9990aab]26#define MSG_SETUP_PROJ_SEARCH_PATH 1
27
[5809313]28#include "aven.h"
[78924eb]29#include "log.h"
[caa5fda]30#include "gla.h"
[5809313]31#include "mainfrm.h"
[706b033]32
[d07944e]33#include "cmdline.h"
[93c3f97]34#include "message.h"
[c49e27f]35#include "useful.h"
[0060ba5]36
[7af6fff]37#include <algorithm>
38
[0060ba5]39#include <assert.h>
[c49e27f]40#include <stdio.h>
[0060ba5]41
[e0ffc2c]42#include <wx/confbase.h>
[573f4e9]43#include <wx/image.h>
[e0ffc2c]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).
[ca18348]47#include <wx/display.h>
48#endif
[573f4e9]49
[faf83bee]50#ifdef __WXMSW__
51#include <windows.h>
52#endif
53
[879e9c3]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[] = {
[45af761]66    /*                          <-- */
[736f7df]67    /* TRANSLATORS: --help output for --survey option.
68     *
69     * "this" has been added to English translation */
[5a2d346]70    {HLP_ENCODELONG(0),       /*only load the sub-survey with this prefix*/199, 0, 0},
[736f7df]71    /* TRANSLATORS: --help output for aven --print option */
[5a2d346]72    {HLP_ENCODELONG(1),       /*print and exit (requires a 3d file)*/119, 0, 0},
73    {0, 0, 0, 0}
[879e9c3]74};
75
[5627cbb]76#ifdef __WXMSW__
[5809313]77IMPLEMENT_APP(Aven)
[5627cbb]78#else
79IMPLEMENT_APP_NO_MAIN(Aven)
80IMPLEMENT_WX_THEME_SUPPORT
81#endif
[0060ba5]82
[a3f83057]83Aven::Aven()
[0060ba5]84{
[1f81f3d]85    wxFont::SetDefaultEncoding(wxFONTENCODING_UTF8);
[0060ba5]86}
87
[2c1d2f4]88Aven::~Aven()
89{
[81f1266]90    delete m_pageSetupData;
[2c1d2f4]91}
92
[5627cbb]93static int getopt_first_response = 0;
94
[5440c295]95static char ** utf8_argv;
96
[5627cbb]97#ifdef __WXMSW__
98bool Aven::Initialize(int& my_argc, wxChar **my_argv)
99{
[faf83bee]100    const wxChar * cmd_line = GetCommandLineW();
101
[b208d0b]102    // Horrible bodge to handle therion's assumptions about the "Process"
103    // file association.
[faf83bee]104    if (cmd_line) {
105        // None of these are valid aven command line options, so this is not
106        // going to be triggered accidentally.
[ccaf632]107        const wxChar * p = wxStrstr(cmd_line,
108                                    wxT("aven.exe\" --quiet --log --output="));
[faf83bee]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        }
[b208d0b]117    }
118
[faf83bee]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){
[8562abc]151            utf8_argv[i] = strdup(wxString(new_argv[i]).utf8_str());
[faf83bee]152        }
153        utf8_argv[utf8_argc] = NULL;
154
155        if (!failed) LocalFree(new_argv);
[5627cbb]156    }
157
[5440c295]158    msg_init(utf8_argv);
[f1cbf74]159    select_charset(CHARSET_UTF8);
[293eec8]160    /* Want --version and decent --help output, which cmdline does for us.
[f1cbf74]161     * wxCmdLine is much less good.
162     */
[736f7df]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.
[b49ac56]166     *
[736f7df]167     * Part of aven --help */
[d8dbdff]168    cmdline_set_syntax_message(/*[SURVEY_FILE]*/269, 0, NULL);
[faf83bee]169    cmdline_init(utf8_argc, utf8_argv, short_opts, long_opts, NULL, help, 0, 1);
[5627cbb]170    getopt_first_response = cmdline_getopt();
[faf83bee]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);
[f1cbf74]175}
[5627cbb]176#else
[b49ac56]177int main(int argc, char **argv)
[0060ba5]178{
[96c239c]179#ifdef __WXGTK3__
[47f55ed]180# if !(wxUSE_GLCANVAS_EGL-0)
181    // The GLX-based wxGLCanvas doesn't work under Wayland, and the code
[736ec93]182    // segfaults: https://github.com/wxWidgets/wxWidgets/issues/17702
[47f55ed]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    //
[96c239c]188    // Setting GDK_BACKEND=x11 is the recommended workaround, and it seems to
[b0908ea]189    // work to set it here.  GTK2 doesn't support Wayland, so doesn't need
190    // this.
[96c239c]191    setenv("GDK_BACKEND", "x11", 1);
[47f55ed]192# endif
[96c239c]193#endif
[705adee9]194
[27b8b59]195#ifdef __WXMAC__
[879e9c3]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.
[5627cbb]199    if (argc > 1 && strncmp(argv[1], "-psn_", 5) == 0) {
200        --argc;
201        memmove(argv + 1, argv + 2, argc * sizeof(char *));
[879e9c3]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.
[5627cbb]206    msg_init(argv);
207    select_charset(CHARSET_UTF8);
[293eec8]208    /* Want --version and decent --help output, which cmdline does for us.
[5627cbb]209     * wxCmdLine is much less good.
210     */
[d8dbdff]211    cmdline_set_syntax_message(/*[SURVEY_FILE]*/269, 0, NULL);
[5627cbb]212    cmdline_init(argc, argv, short_opts, long_opts, NULL, help, 0, 1);
[879e9c3]213    getopt_first_response = cmdline_getopt();
[5627cbb]214
[5440c295]215    utf8_argv = argv;
[5627cbb]216
[f891a0c]217#if wxUSE_UNICODE
[5627cbb]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);
[495cd3e]229#else
[a212391]230    char *dummy_argv[2] = { argv[0], NULL };
231    int dummy_argc = 1;
232    return wxEntry(dummy_argc, dummy_argv);
[495cd3e]233#endif
[879e9c3]234}
[5627cbb]235#endif
[879e9c3]236
237bool Aven::OnInit()
238{
[4013d9c]239    wxLog::SetActiveTarget(new MyLogWindow());
[421b7d2]240
[d607cea]241    {
[b1876d3]242        // Suppress message box warnings about messages not found.
[71ea9e1]243        wxLogNull logNo;
244        wxLocale *loc = new wxLocale();
[8a05a7a]245        loc->AddCatalogLookupPathPrefix(wmsg_cfgpth());
[b1876d3]246        wxString msg_lang_str(msg_lang, wxConvUTF8);
247        const char *lang = msg_lang2 ? msg_lang2 : msg_lang;
248        wxString lang_str(lang, wxConvUTF8);
[f1d5d26]249        loc->Init(msg_lang_str, lang_str, msg_lang_str);
[71ea9e1]250        // The existence of the wxLocale object is enough - no need to keep a
251        // pointer to it!
[003d953]252    }
[93c3f97]253
[668b930]254    const char* opt_survey = NULL;
[3ee64fb]255    bool print_and_exit = false;
[421b7d2]256
[0580c6a]257    while (true) {
[879e9c3]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        }
[d07944e]265        if (opt == EOF) break;
266        if (opt == 's') {
[668b930]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;
[d07944e]275        }
[3ee64fb]276        if (opt == 'p') {
277            print_and_exit = true;
278        }
279    }
280
[5440c295]281    if (print_and_exit && !utf8_argv[optind]) {
[3ee64fb]282        cmdline_syntax(); // FIXME : not a helpful error...
283        exit(1);
[d07944e]284    }
[068b4f2]285
[5627cbb]286    wxString fnm;
[5440c295]287    if (utf8_argv[optind]) {
288        fnm = wxString(utf8_argv[optind], wxConvUTF8);
289        if (fnm.empty() && *(utf8_argv[optind])) {
[c49e27f]290            ReportError(wxT("File argument's filename has bad encoding"));
[5627cbb]291            return false;
292        }
293    }
294
[caa5fda]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);
[5892e08]302    }
303
[573f4e9]304    wxImage::AddHandler(new wxPNGHandler);
[08d2074]305
[4909e6bc]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
[3db0798]314    wxPoint pos(wxDefaultPosition);
[ca18348]315    int width, height;
[5627cbb]316    wxConfigBase::Get()->Read(wxT("width"), &width, 0);
317    if (width > 0) wxConfigBase::Get()->Read(wxT("height"), &height, 0);
[30621f5]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);
[3db0798]322    if (width <= 0 || height <= 0) {
323        pos.x = geom.x;
324        pos.y = geom.y;
325        width = geom.width;
326        height = geom.height;
[486ae6a]327
[3db0798]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;
[4909e6bc]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        }
[3db0798]350    }
[486ae6a]351
352    // Create the main window.
[3db0798]353    m_Frame = new MainFrm(APP_NAME, pos, wxSize(width, height));
354
[30621f5]355    // Select maximised if that's the saved state.
356    if (maximized) {
[3db0798]357        m_Frame->Maximize();
358    }
[068b4f2]359
[5440c295]360    if (utf8_argv[optind]) {
[668b930]361        if (!opt_survey) opt_survey = "";
362        m_Frame->OpenFile(fnm, wxString(opt_survey, wxConvUTF8));
[d07944e]363    }
[068b4f2]364
[3ee64fb]365    if (print_and_exit) {
[4ed8154]366        m_Frame->PrintAndExit();
[3ee64fb]367        return true;
368    }
369
[5809313]370    m_Frame->Show(true);
[526775d]371#ifdef _WIN32
372    m_Frame->SetFocus();
373#endif
[0060ba5]374    return true;
375}
376
[e0ffc2c]377wxPageSetupDialogData *
378Aven::GetPageSetupDialogData()
379{
[2c1d2f4]380    if (!m_pageSetupData) m_pageSetupData = new wxPageSetupDialogData;
[e0ffc2c]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.
[5627cbb]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);
[2c1d2f4]391    m_pageSetupData->SetMarginTopLeft(wxPoint(left, top));
392    m_pageSetupData->SetMarginBottomRight(wxPoint(right, bottom));
[e0ffc2c]393#endif
[2c1d2f4]394    return m_pageSetupData;
[e0ffc2c]395}
396
397void
398Aven::SetPageSetupDialogData(const wxPageSetupDialogData & psdd)
399{
[2c1d2f4]400    if (!m_pageSetupData) m_pageSetupData = new wxPageSetupDialogData;
401    *m_pageSetupData = psdd;
[e0ffc2c]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();
[5627cbb]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);
[e0ffc2c]412    cfg->Flush();
413#endif
414}
415
[ddc0994]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
[5809313]439void Aven::ReportError(const wxString& msg)
[0060ba5]440{
[c8b5fa5]441    if (!m_Frame) {
442        wxMessageBox(msg, APP_NAME, wxOK | wxICON_ERROR);
443        return;
444    }
[7015222]445    wxMessageDialog dlg(m_Frame, msg, APP_NAME, wxOK | wxICON_ERROR);
446    dlg.ShowModal();
[0060ba5]447}
[59fda0a]448
[8a05a7a]449const wxString &
450wmsg_cfgpth()
451{
452    static wxString path;
453    if (path.empty())
454        path = wxString(msg_cfgpth(), wxConvUTF8);
455    return path;
456}
457
[a9a32f2]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{
[c49e27f]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
[37d6b84]469    if (severity == DIAG_WARN) {
[c49e27f]470        m += wmsg(/*warning*/4);
471        m += wxT(": ");
472    }
473
474    char buf[1024];
[dba56bb]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
[9b5f251]481    vsnprintf(buf, sizeof(buf), msg(en), ap);
[dba56bb]482#endif
[c49e27f]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    }
[a9a32f2]496}
Note: See TracBrowser for help on using the repository browser.