source: git/src/printing.cc @ 1dfd718

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

Use C++11 member initialisation where sensible

  • Property mode set to 100644
File size: 68.0 KB
Line 
1/* printing.cc */
2/* Aven printing code */
3/* Copyright (C) 1993-2003,2004,2005,2006,2010,2011,2012,2013,2014,2015,2016,2017,2018 Olly Betts
4 * Copyright (C) 2001,2004 Philip Underwood
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#include <config.h>
22
23#include <wx/confbase.h>
24#include <wx/filename.h>
25#include <wx/print.h>
26#include <wx/printdlg.h>
27#include <wx/spinctrl.h>
28#include <wx/radiobox.h>
29#include <wx/statbox.h>
30#include <wx/valgen.h>
31
32#include <vector>
33
34#include <stdio.h>
35#include <stdlib.h>
36#include <math.h>
37#include <string.h>
38#include <ctype.h>
39#include <float.h>
40#include <limits.h>
41
42#include "export.h"
43#include "filelist.h"
44#include "filename.h"
45#include "message.h"
46#include "useful.h"
47
48#include "aven.h"
49#include "avenprcore.h"
50#include "mainfrm.h"
51#include "printing.h"
52
53using namespace std;
54
55// How many decimal points to show on angles:
56#define ANGLE_DP 1
57
58#if ANGLE_DP == 0
59# define ANGLE_FMT wxT("%03.f")
60# define ANGLE2_FMT wxT("%.f")
61#elif ANGLE_DP == 1
62# define ANGLE_FMT wxT("%05.1f")
63# define ANGLE2_FMT wxT("%.1f")
64#elif ANGLE_DP == 2
65# define ANGLE_FMT wxT("%06.2f")
66# define ANGLE2_FMT wxT("%.2f")
67#else
68# error Need to add ANGLE_FMT and ANGLE2_FMT for the currently set ANGLE_DP
69#endif
70
71static wxString
72format_angle(const wxChar * fmt, double angle)
73{
74    wxString s;
75    s.Printf(fmt, angle);
76    size_t dot = s.find('.');
77    size_t i = s.size();
78    while (i > dot) {
79        --i;
80        if (s[i] != '0') {
81            if (i != dot) ++i;
82            s.resize(i);
83            break;
84        }
85    }
86    s += wmsg(/*°*/344);
87    return s;
88}
89
90enum {
91        svx_EXPORT = 1200,
92        svx_FORMAT,
93        svx_SCALE,
94        svx_BEARING,
95        svx_TILT,
96        svx_LEGS,
97        svx_STATIONS,
98        svx_NAMES,
99        svx_XSECT,
100        svx_WALLS,
101        svx_PASSAGES,
102        svx_BORDERS,
103        svx_BLANKS,
104        svx_LEGEND,
105        svx_SURFACE,
106        svx_SPLAYS,
107        svx_PLAN,
108        svx_ELEV,
109        svx_ENTS,
110        svx_FIXES,
111        svx_EXPORTS,
112        svx_GRID,
113        svx_TEXT_HEIGHT,
114        svx_MARKER_SIZE,
115        svx_CENTRED,
116        svx_FULLCOORDS,
117        svx_CLAMP_TO_GROUND
118};
119
120class BitValidator : public wxValidator {
121    // Disallow assignment.
122    BitValidator & operator=(const BitValidator&);
123
124  protected:
125    int * val;
126
127    int mask;
128
129  public:
130    BitValidator(int * val_, int mask_)
131        : val(val_), mask(mask_) { }
132
133    BitValidator(const BitValidator &o) : wxValidator() {
134        Copy(o);
135    }
136
137    ~BitValidator() { }
138
139    wxObject *Clone() const { return new BitValidator(val, mask); }
140
141    bool Copy(const BitValidator& o) {
142        wxValidator::Copy(o);
143        val = o.val;
144        mask = o.mask;
145        return true;
146    }
147
148    bool Validate(wxWindow *) { return true; }
149
150    bool TransferToWindow() {
151        if (!m_validatorWindow->IsKindOf(CLASSINFO(wxCheckBox)))
152            return false;
153        ((wxCheckBox*)m_validatorWindow)->SetValue(*val & mask);
154        return true;
155    }
156
157    bool TransferFromWindow() {
158        if (!m_validatorWindow->IsKindOf(CLASSINFO(wxCheckBox)))
159            return false;
160        if (((wxCheckBox*)m_validatorWindow)->IsChecked())
161            *val |= mask;
162        else
163            *val &= ~mask;
164        return true;
165    }
166};
167
168class svxPrintout : public wxPrintout {
169    MainFrm *mainfrm;
170    layout *m_layout;
171    wxPageSetupDialogData* m_data;
172    wxDC* pdc;
173    wxFont *font_labels = nullptr, *font_default = nullptr;
174    // Currently unused, but "skip blank pages" would use it.
175    bool scan_for_blank_pages = false;
176
177    wxPen *pen_frame, *pen_cross, *pen_leg, *pen_surface_leg, *pen_splay;
178    wxColour colour_text, colour_labels;
179
180    long x_t, y_t;
181    double font_scaling_x, font_scaling_y;
182
183    struct {
184        long x_min, y_min, x_max, y_max;
185    } clip;
186
187    bool fBlankPage;
188
189    int check_intersection(long x_p, long y_p);
190    void draw_info_box();
191    void draw_scale_bar(double x, double y, double MaxLength);
192    int next_page(int *pstate, char **q, int pageLim);
193    void drawticks(int tsize, int x, int y);
194
195    void MOVEMM(double X, double Y) {
196        MoveTo((long)(X * m_layout->scX), (long)(Y * m_layout->scY));
197    }
198    void DRAWMM(double X, double Y) {
199        DrawTo((long)(X * m_layout->scX), (long)(Y * m_layout->scY));
200    }
201    void MoveTo(long x, long y);
202    void DrawTo(long x, long y);
203    void DrawCross(long x, long y);
204    void SetFont(wxFont * font) {
205        pdc->SetFont(*font);
206    }
207    void WriteString(const wxString & s);
208    void DrawEllipse(long x, long y, long r, long R);
209    void SolidRectangle(long x, long y, long w, long h);
210    void NewPage(int pg, int pagesX, int pagesY);
211    void PlotLR(const vector<XSect> & centreline);
212    void PlotUD(const vector<XSect> & centreline);
213  public:
214    svxPrintout(MainFrm *mainfrm, layout *l, wxPageSetupDialogData *data, const wxString & title);
215    bool OnPrintPage(int pageNum);
216    void GetPageInfo(int *minPage, int *maxPage,
217                     int *pageFrom, int *pageTo);
218    bool HasPage(int pageNum);
219    void OnBeginPrinting();
220    void OnEndPrinting();
221};
222
223BEGIN_EVENT_TABLE(svxPrintDlg, wxDialog)
224    EVT_CHOICE(svx_FORMAT, svxPrintDlg::OnChange)
225    EVT_TEXT(svx_SCALE, svxPrintDlg::OnChangeScale)
226    EVT_COMBOBOX(svx_SCALE, svxPrintDlg::OnChangeScale)
227    EVT_SPINCTRLDOUBLE(svx_BEARING, svxPrintDlg::OnChangeSpin)
228    EVT_SPINCTRLDOUBLE(svx_TILT, svxPrintDlg::OnChangeSpin)
229    EVT_BUTTON(wxID_PRINT, svxPrintDlg::OnPrint)
230    EVT_BUTTON(svx_EXPORT, svxPrintDlg::OnExport)
231    EVT_BUTTON(wxID_CANCEL, svxPrintDlg::OnCancel)
232#ifdef AVEN_PRINT_PREVIEW
233    EVT_BUTTON(wxID_PREVIEW, svxPrintDlg::OnPreview)
234#endif
235    EVT_BUTTON(svx_PLAN, svxPrintDlg::OnPlan)
236    EVT_BUTTON(svx_ELEV, svxPrintDlg::OnElevation)
237    EVT_UPDATE_UI(svx_PLAN, svxPrintDlg::OnPlanUpdate)
238    EVT_UPDATE_UI(svx_ELEV, svxPrintDlg::OnElevationUpdate)
239    EVT_CHECKBOX(svx_LEGS, svxPrintDlg::OnChange)
240    EVT_CHECKBOX(svx_STATIONS, svxPrintDlg::OnChange)
241    EVT_CHECKBOX(svx_NAMES, svxPrintDlg::OnChange)
242    EVT_CHECKBOX(svx_SURFACE, svxPrintDlg::OnChange)
243    EVT_CHECKBOX(svx_SPLAYS, svxPrintDlg::OnChange)
244    EVT_CHECKBOX(svx_ENTS, svxPrintDlg::OnChange)
245    EVT_CHECKBOX(svx_FIXES, svxPrintDlg::OnChange)
246    EVT_CHECKBOX(svx_EXPORTS, svxPrintDlg::OnChange)
247END_EVENT_TABLE()
248
249static wxString scales[] = {
250    wxT(""),
251    wxT("25"),
252    wxT("50"),
253    wxT("100"),
254    wxT("250"),
255    wxT("500"),
256    wxT("1000"),
257    wxT("2500"),
258    wxT("5000"),
259    wxT("10000"),
260    wxT("25000"),
261    wxT("50000"),
262    wxT("100000"),
263    wxT("240 (1\":20')"),
264    wxT("300 (1\":25')"),
265    // This entry will be "304.8 (1mm:1ft)" but we need to use the
266    // locale-specific decimal point so this gets filled in on first
267    // use, after the locale is initialised.
268#define SCALES_INDEX_MM_TO_FEET 15
269    wxT(""),
270    wxT("480 (1\":40')"),
271    wxT("600 (1\":50')"),
272    wxT("...")
273};
274
275// The order of these arrays must match export_format in export.h.
276
277static wxString formats[] = {
278    wxT("Survex 3d"),
279    wxT("CSV"),
280    wxT("DXF"),
281    wxT("EPS"),
282    wxT("GPX"),
283    wxT("HPGL"),
284    wxT("JSON"),
285    wxT("KML"),
286    wxT("Plot"),
287    wxT("Survex pos"),
288    wxT("SVG"),
289    // These next two get filled in lazily since they are translated which
290    // means we need to wait until after the messages are loaded.
291    wxT(""), // "Shapefiles (lines)"
292    wxT("") // "Shapefiles (points)"
293};
294
295static_assert(sizeof(formats) == FMT_MAX_PLUS_ONE_ * sizeof(formats[0]),
296              "formats[] matches enum export_format");
297
298// We discriminate as "One page" isn't valid for exporting.
299static wxString default_scale_print;
300static wxString default_scale_export;
301
302svxPrintDlg::svxPrintDlg(MainFrm* mainfrm_, const wxString & filename,
303                         const wxString & title,
304                         const wxString & datestamp,
305                         double angle, double tilt_angle,
306                         bool labels, bool crosses, bool legs, bool surf,
307                         bool splays, bool tubes, bool ents, bool fixes,
308                         bool exports, bool printing, bool close_after_)
309        : wxDialog(mainfrm_, wxID_ANY,
310                   wxString(printing ? /* TRANSLATORS: Title of the print
311                                        * dialog */
312                                       wmsg(/*Print*/399) :
313                                       /* TRANSLATORS: Title of the export
314                                        * dialog */
315                                       wmsg(/*Export*/383))),
316          m_layout(printing ? wxGetApp().GetPageSetupDialogData() : NULL),
317          m_File(filename), mainfrm(mainfrm_), close_after(close_after_)
318{
319    int show_mask = 0;
320    if (labels)
321        show_mask |= LABELS;
322    if (crosses)
323        show_mask |= STNS;
324    if (legs)
325        show_mask |= LEGS;
326    if (surf)
327        show_mask |= SURF;
328    if (splays)
329        show_mask |= SPLAYS;
330    if (tubes)
331        show_mask |= XSECT|WALLS|PASG;
332    if (ents)
333        show_mask |= ENTS;
334    if (fixes)
335        show_mask |= FIXES;
336    if (exports)
337        show_mask |= EXPORTS;
338    m_layout.show_mask = show_mask;
339    m_layout.datestamp = datestamp;
340    m_layout.rot = angle;
341    m_layout.title = title;
342    if (mainfrm->IsExtendedElevation()) {
343        m_layout.view = layout::EXTELEV;
344        if (m_layout.rot != 0.0 && m_layout.rot != 180.0) m_layout.rot = 0;
345        m_layout.tilt = 0;
346    } else {
347        m_layout.tilt = tilt_angle;
348        if (m_layout.tilt == -90.0) {
349            m_layout.view = layout::PLAN;
350        } else if (m_layout.tilt == 0.0) {
351            m_layout.view = layout::ELEV;
352        } else {
353            m_layout.view = layout::TILT;
354        }
355    }
356
357    /* setup our print dialog*/
358    wxBoxSizer* v1 = new wxBoxSizer(wxVERTICAL);
359    wxBoxSizer* h1 = new wxBoxSizer(wxHORIZONTAL); // holds controls
360    /* TRANSLATORS: Used as a label for the surrounding box for the "Bearing"
361     * and "Tilt angle" fields, and the "Plan view" and "Elevation" buttons in
362     * the "what to print/export" dialog. */
363    m_viewbox = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, wmsg(/*View*/283)), wxVERTICAL);
364    /* TRANSLATORS: Used as a label for the surrounding box for the "survey
365     * legs" "stations" "names" etc checkboxes in the "what to print" dialog.
366     * "Elements" isn’t a good name for this but nothing better has yet come to
367     * mind! */
368    wxBoxSizer* v2 = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, wmsg(/*Elements*/256)), wxVERTICAL);
369    wxBoxSizer* h2 = new wxBoxSizer(wxHORIZONTAL); // holds buttons
370
371    if (!printing) {
372        wxStaticText* label;
373        label = new wxStaticText(this, wxID_ANY, wxString(wmsg(/*Export format*/410)));
374        if (formats[FMT_SHP_LINES].empty()) {
375            formats[FMT_SHP_LINES] = wmsg(/*Shapefiles (lines)*/523);
376            formats[FMT_SHP_POINTS] = wmsg(/*Shapefiles (points)*/524);
377        }
378        const size_t n_formats = sizeof(formats) / sizeof(formats[0]);
379        m_format = new wxChoice(this, svx_FORMAT,
380                                wxDefaultPosition, wxDefaultSize,
381                                n_formats, formats);
382        unsigned current_format = 0;
383        wxConfigBase * cfg = wxConfigBase::Get();
384        wxString s;
385        if (cfg->Read(wxT("export_format"), &s, wxString())) {
386            for (unsigned i = 0; i != n_formats; ++i) {
387                if (s == formats[i]) {
388                    current_format = i;
389                    break;
390                }
391            }
392        }
393        m_format->SetSelection(current_format);
394        wxBoxSizer* formatbox = new wxBoxSizer(wxHORIZONTAL);
395        formatbox->Add(label, 0, wxALIGN_CENTRE_VERTICAL|wxALL, 5);
396        formatbox->Add(m_format, 0, wxALIGN_CENTRE_VERTICAL|wxALL, 5);
397
398        v1->Add(formatbox, 0, wxALIGN_LEFT|wxALL, 0);
399    }
400
401    if (scales[SCALES_INDEX_MM_TO_FEET][0] == '\0') {
402        scales[SCALES_INDEX_MM_TO_FEET] = wxString::FromDouble(304.8) + wxT(" (1mm:1ft)");
403    }
404    wxStaticText* label;
405    label = new wxStaticText(this, wxID_ANY, wxString(wmsg(/*Scale*/154)) + wxT(" 1:"));
406    if (printing && scales[0].empty()) {
407        /* TRANSLATORS: used in the scale drop down selector in the print
408         * dialog the implicit meaning is "choose a suitable scale to fit
409         * the plot on a single page", but we need something shorter */
410        scales[0].assign(wmsg(/*One page*/258));
411    }
412    wxString default_scale;
413    if (printing) {
414        default_scale = default_scale_print;
415        if (default_scale.empty()) default_scale = scales[0];
416    } else {
417        default_scale = default_scale_export;
418        if (default_scale.empty()) default_scale = wxT("1000");
419    }
420    const wxString* scale_list = scales;
421    size_t n_scales = sizeof(scales) / sizeof(scales[0]);
422    if (!printing) {
423        ++scale_list;
424        --n_scales;
425    }
426    m_scale = new wxComboBox(this, svx_SCALE, default_scale, wxDefaultPosition,
427                             wxDefaultSize, n_scales, scale_list);
428    m_scalebox = new wxBoxSizer(wxHORIZONTAL);
429    m_scalebox->Add(label, 0, wxALIGN_CENTRE_VERTICAL|wxALL, 5);
430    m_scalebox->Add(m_scale, 0, wxALIGN_CENTRE_VERTICAL|wxALL, 5);
431
432    m_viewbox->Add(m_scalebox, 0, wxALIGN_LEFT|wxALL, 0);
433
434    if (printing) {
435        // Make the dummy string wider than any sane value and use that to
436        // fix the width of the control so the sizers allow space for bigger
437        // page layouts.
438        m_printSize = new wxStaticText(this, wxID_ANY, wxString::Format(wmsg(/*%d pages (%dx%d)*/257), 9604, 98, 98));
439        m_viewbox->Add(m_printSize, 0, wxALIGN_LEFT|wxALL, 5);
440    }
441
442    if (m_layout.view != layout::EXTELEV) {
443        wxFlexGridSizer* anglebox = new wxFlexGridSizer(2);
444        wxStaticText * brg_label, * tilt_label;
445        brg_label = new wxStaticText(this, wxID_ANY, wmsg(/*Bearing*/259));
446        anglebox->Add(brg_label, 0, wxALIGN_CENTRE_VERTICAL|wxALIGN_LEFT|wxALL, 5);
447        // wSP_WRAP means that you can scroll past 360 to 0, and vice versa.
448        m_bearing = new wxSpinCtrlDouble(this, svx_BEARING, wxEmptyString,
449                wxDefaultPosition, wxDefaultSize,
450                wxSP_ARROW_KEYS|wxALIGN_RIGHT|wxSP_WRAP);
451        m_bearing->SetRange(0.0, 360.0);
452        m_bearing->SetDigits(ANGLE_DP);
453        anglebox->Add(m_bearing, 0, wxALIGN_CENTRE|wxALL, 5);
454        /* TRANSLATORS: Used in the print dialog: */
455        tilt_label = new wxStaticText(this, wxID_ANY, wmsg(/*Tilt angle*/263));
456        anglebox->Add(tilt_label, 0, wxALIGN_CENTRE_VERTICAL|wxALIGN_LEFT|wxALL, 5);
457        m_tilt = new wxSpinCtrlDouble(this, svx_TILT, wxEmptyString,
458                wxDefaultPosition, wxDefaultSize,
459                wxSP_ARROW_KEYS|wxALIGN_RIGHT);
460        m_tilt->SetRange(-90.0, 90.0);
461        m_tilt->SetDigits(ANGLE_DP);
462        anglebox->Add(m_tilt, 0, wxALIGN_CENTRE|wxALL, 5);
463
464        m_viewbox->Add(anglebox, 0, wxALIGN_LEFT|wxALL, 0);
465
466        wxBoxSizer * planelevsizer = new wxBoxSizer(wxHORIZONTAL);
467        planelevsizer->Add(new wxButton(this, svx_PLAN, wmsg(/*P&lan view*/117)),
468                           0, wxALIGN_CENTRE_VERTICAL|wxALL, 5);
469        planelevsizer->Add(new wxButton(this, svx_ELEV, wmsg(/*&Elevation*/285)),
470                           0, wxALIGN_CENTRE_VERTICAL|wxALL, 5);
471
472        m_viewbox->Add(planelevsizer, 0, wxALIGN_LEFT|wxALL, 5);
473    }
474
475    /* TRANSLATORS: Here a "survey leg" is a set of measurements between two
476     * "survey stations". */
477    v2->Add(new wxCheckBox(this, svx_LEGS, wmsg(/*Underground Survey Legs*/262),
478                           wxDefaultPosition, wxDefaultSize, 0,
479                           BitValidator(&m_layout.show_mask, LEGS)),
480            0, wxALIGN_LEFT|wxALL, 2);
481    /* TRANSLATORS: Here a "survey leg" is a set of measurements between two
482     * "survey stations". */
483    v2->Add(new wxCheckBox(this, svx_SURFACE, wmsg(/*Sur&face Survey Legs*/403),
484                           wxDefaultPosition, wxDefaultSize, 0,
485                           BitValidator(&m_layout.show_mask, SURF)),
486            0, wxALIGN_LEFT|wxALL, 2);
487    v2->Add(new wxCheckBox(this, svx_SPLAYS, wmsg(/*Spla&y Legs*/406),
488                           wxDefaultPosition, wxDefaultSize, 0,
489                           BitValidator(&m_layout.show_mask, SPLAYS)),
490            0, wxALIGN_LEFT|wxALL, 2);
491    v2->Add(new wxCheckBox(this, svx_STATIONS, wmsg(/*Crosses*/261),
492                           wxDefaultPosition, wxDefaultSize, 0,
493                           BitValidator(&m_layout.show_mask, STNS)),
494            0, wxALIGN_LEFT|wxALL, 2);
495    v2->Add(new wxCheckBox(this, svx_NAMES, wmsg(/*Station Names*/260),
496                           wxDefaultPosition, wxDefaultSize, 0,
497                           BitValidator(&m_layout.show_mask, LABELS)),
498            0, wxALIGN_LEFT|wxALL, 2);
499    v2->Add(new wxCheckBox(this, svx_ENTS, wmsg(/*Entrances*/418),
500                           wxDefaultPosition, wxDefaultSize, 0,
501                           BitValidator(&m_layout.show_mask, ENTS)),
502            0, wxALIGN_LEFT|wxALL, 2);
503    v2->Add(new wxCheckBox(this, svx_FIXES, wmsg(/*Fixed Points*/419),
504                           wxDefaultPosition, wxDefaultSize, 0,
505                           BitValidator(&m_layout.show_mask, FIXES)),
506            0, wxALIGN_LEFT|wxALL, 2);
507    v2->Add(new wxCheckBox(this, svx_EXPORTS, wmsg(/*Exported Stations*/420),
508                           wxDefaultPosition, wxDefaultSize, 0,
509                           BitValidator(&m_layout.show_mask, EXPORTS)),
510            0, wxALIGN_LEFT|wxALL, 2);
511    v2->Add(new wxCheckBox(this, svx_XSECT, wmsg(/*Cross-sections*/393),
512                           wxDefaultPosition, wxDefaultSize, 0,
513                           BitValidator(&m_layout.show_mask, XSECT)),
514            0, wxALIGN_LEFT|wxALL, 2);
515    if (!printing) {
516        v2->Add(new wxCheckBox(this, svx_WALLS, wmsg(/*Walls*/394),
517                               wxDefaultPosition, wxDefaultSize, 0,
518                               BitValidator(&m_layout.show_mask, WALLS)),
519                0, wxALIGN_LEFT|wxALL, 2);
520        // TRANSLATORS: Label for checkbox which controls whether there's a
521        // layer in the exported file (for formats such as DXF and SVG)
522        // containing polygons for the inside of cave passages).
523        v2->Add(new wxCheckBox(this, svx_PASSAGES, wmsg(/*Passages*/395),
524                               wxDefaultPosition, wxDefaultSize, 0,
525                               BitValidator(&m_layout.show_mask, PASG)),
526                0, wxALIGN_LEFT|wxALL, 2);
527        v2->Add(new wxCheckBox(this, svx_CENTRED, wmsg(/*Origin in centre*/421),
528                               wxDefaultPosition, wxDefaultSize, 0,
529                               BitValidator(&m_layout.show_mask, CENTRED)),
530                0, wxALIGN_LEFT|wxALL, 2);
531        v2->Add(new wxCheckBox(this, svx_FULLCOORDS, wmsg(/*Full coordinates*/422),
532                               wxDefaultPosition, wxDefaultSize, 0,
533                               BitValidator(&m_layout.show_mask, FULL_COORDS)),
534                0, wxALIGN_LEFT|wxALL, 2);
535        v2->Add(new wxCheckBox(this, svx_CLAMP_TO_GROUND, wmsg(/*Clamp to ground*/477),
536                               wxDefaultPosition, wxDefaultSize, 0,
537                               BitValidator(&m_layout.show_mask, CLAMP_TO_GROUND)),
538                0, wxALIGN_LEFT|wxALL, 2);
539    }
540    if (printing) {
541        /* TRANSLATORS: used in the print dialog - controls drawing lines
542         * around each page */
543        v2->Add(new wxCheckBox(this, svx_BORDERS, wmsg(/*Page Borders*/264),
544                               wxDefaultPosition, wxDefaultSize, 0,
545                               wxGenericValidator(&m_layout.Border)),
546                0, wxALIGN_LEFT|wxALL, 2);
547        /* TRANSLATORS: will be used in the print dialog - check this to print
548         * blank pages (otherwise they’ll be skipped to save paper) */
549//      m_blanks = new wxCheckBox(this, svx_BLANKS, wmsg(/*Blank Pages*/266));
550//      v2->Add(m_blanks, 0, wxALIGN_LEFT|wxALL, 2);
551        /* TRANSLATORS: As in the legend on a map.  Used in the print dialog -
552         * controls drawing the box at the lower left with survey name, view
553         * angles, etc */
554        v2->Add(new wxCheckBox(this, svx_LEGEND, wmsg(/*Legend*/265),
555                               wxDefaultPosition, wxDefaultSize, 0,
556                               wxGenericValidator(&m_layout.Legend)),
557                0, wxALIGN_LEFT|wxALL, 2);
558    }
559
560    h1->Add(v2, 0, wxALIGN_LEFT|wxALL, 5);
561    h1->Add(m_viewbox, 0, wxALIGN_LEFT|wxLEFT, 5);
562
563    v1->Add(h1, 0, wxALIGN_LEFT|wxALL, 5);
564
565    // When we enable/disable checkboxes in the export dialog, ideally we'd
566    // like the dialog to resize, but not sure how to achieve that, so we
567    // add a stretchable spacer here so at least the buttons stay in the
568    // lower right corner.
569    v1->AddStretchSpacer();
570
571    wxButton * but;
572    but = new wxButton(this, wxID_CANCEL);
573    h2->Add(but, 0, wxALL, 5);
574    if (printing) {
575#ifdef AVEN_PRINT_PREVIEW
576        but = new wxButton(this, wxID_PREVIEW);
577        h2->Add(but, 0, wxALL, 5);
578        but = new wxButton(this, wxID_PRINT);
579#else
580        but = new wxButton(this, wxID_PRINT, wmsg(/*&Print...*/400));
581#endif
582    } else {
583        /* TRANSLATORS: The text on the action button in the "Export" settings
584         * dialog */
585        but = new wxButton(this, svx_EXPORT, wmsg(/*&Export...*/230));
586    }
587    but->SetDefault();
588    h2->Add(but, 0, wxALL, 5);
589    v1->Add(h2, 0, wxALIGN_RIGHT|wxALL, 5);
590
591    SetAutoLayout(true);
592    SetSizer(v1);
593    v1->SetSizeHints(this);
594
595    LayoutToUI();
596    SomethingChanged(0);
597}
598
599void
600svxPrintDlg::OnPrint(wxCommandEvent&) {
601    SomethingChanged(0);
602    TransferDataFromWindow();
603    wxPageSetupDialogData * psdd = wxGetApp().GetPageSetupDialogData();
604    wxPrintDialogData pd(psdd->GetPrintData());
605    wxPrinter pr(&pd);
606    svxPrintout po(mainfrm, &m_layout, psdd, m_File);
607    if (m_layout.SkipBlank) {
608        // FIXME: wx's printing requires a contiguous range of valid page
609        // numbers.  To achieve that, we need to run a scan for blank pages
610        // here, so that GetPageInfo() knows what range to return, and so
611        // that OnPrintPage() can map a page number back to where in the
612        // MxN multi-page layout.
613#if 0
614        po.scan_for_blank_pages = true;
615        for (int page = 1; page <= m_layout->pages; ++page) {
616            po.fBlankPage = true;
617            po.OnPrintPage(page);
618            // FIXME: Do something with po.fBlankPage
619        }
620        po.scan_for_blank_pages = false;
621#endif
622    }
623    if (pr.Print(this, &po, true)) {
624        // Close the print dialog if printing succeeded.
625        Destroy();
626    }
627}
628
629void
630svxPrintDlg::OnExport(wxCommandEvent&) {
631    UIToLayout();
632    TransferDataFromWindow();
633    wxString leaf;
634    wxFileName::SplitPath(m_File, NULL, NULL, &leaf, NULL, wxPATH_NATIVE);
635    unsigned format_idx = ((wxChoice*)FindWindow(svx_FORMAT))->GetSelection();
636    const auto& info = export_format_info[format_idx];
637    leaf += wxString::FromUTF8(info.extension);
638
639    wxString filespec = wmsg(info.msg_filetype);
640    filespec += wxT("|*");
641    filespec += wxString::FromUTF8(info.extension);
642    filespec += wxT("|");
643    filespec += wmsg(/*All files*/208);
644    filespec += wxT("|");
645    filespec += wxFileSelectorDefaultWildcardStr;
646
647    /* TRANSLATORS: Title of file dialog to choose name and type of exported
648     * file. */
649    wxFileDialog dlg(this, wmsg(/*Export as:*/401), wxString(), leaf,
650                     filespec, wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
651    if (dlg.ShowModal() == wxID_OK) {
652        /* FIXME: Set up a way for the user to specify these: */
653        double grid = DEFAULT_GRID_SPACING; // metres
654        double text_height = DEFAULT_TEXT_HEIGHT;
655        double marker_size = DEFAULT_MARKER_SIZE;
656
657        try {
658            const wxString& export_fnm = dlg.GetPath();
659            unsigned mask = info.mask;
660            double rot, tilt;
661            if (mask & ORIENTABLE) {
662                rot = m_layout.rot;
663                tilt = m_layout.tilt;
664            } else {
665                rot = 0.0;
666                tilt = -90.0;
667            }
668            if (!Export(export_fnm, m_layout.title,
669                        m_layout.datestamp, *mainfrm, mainfrm->GetTreeFilter(),
670                        rot, tilt, m_layout.get_effective_show_mask(),
671                        export_format(format_idx),
672                        grid, text_height, marker_size, m_layout.Scale)) {
673                wxString m = wxString::Format(wmsg(/*Couldn’t write file “%s”*/402).c_str(),
674                                              export_fnm.c_str());
675                wxGetApp().ReportError(m);
676            }
677        } catch (const wxString & m) {
678            wxGetApp().ReportError(m);
679        }
680    }
681    Destroy();
682}
683
684#ifdef AVEN_PRINT_PREVIEW
685void
686svxPrintDlg::OnPreview(wxCommandEvent&) {
687    SomethingChanged(0);
688    TransferDataFromWindow();
689    wxPageSetupDialogData * psdd = wxGetApp().GetPageSetupDialogData();
690    wxPrintDialogData pd(psdd->GetPrintData());
691    wxPrintPreview* pv;
692    pv = new wxPrintPreview(new svxPrintout(mainfrm, &m_layout, psdd, m_File),
693                            new svxPrintout(mainfrm, &m_layout, psdd, m_File),
694                            &pd);
695    // TRANSLATORS: Title of the print preview dialog
696    wxPreviewFrame *frame = new wxPreviewFrame(pv, mainfrm, wmsg(/*Print Preview*/398));
697    frame->Initialize();
698
699    // Size preview frame so that all of the controlbar and canvas can be seen
700    // if possible.
701    int w, h;
702    // GetBestSize gives us the width needed to show the whole controlbar.
703    frame->GetBestSize(&w, &h);
704    if (h < w) {
705        // On wxGTK at least, GetBestSize() returns much too small a height.
706        h = w * 6 / 5;
707    }
708    // Ensure that we don't make the window bigger than the screen.
709    // Use wxGetClientDisplayRect() so we don't cover the MS Windows
710    // task bar either.
711    wxRect disp = wxGetClientDisplayRect();
712    if (w > disp.GetWidth()) w = disp.GetWidth();
713    if (h > disp.GetHeight()) h = disp.GetHeight();
714    // Centre the window within the "ClientDisplayRect".
715    int x = disp.GetLeft() + (disp.GetWidth() - w) / 2;
716    int y = disp.GetTop() + (disp.GetHeight() - h) / 2;
717    frame->SetSize(x, y, w, h);
718
719    frame->Show();
720}
721#endif
722
723void
724svxPrintDlg::OnPlan(wxCommandEvent&) {
725    m_tilt->SetValue(-90.0);
726    SomethingChanged(svx_TILT);
727}
728
729void
730svxPrintDlg::OnElevation(wxCommandEvent&) {
731    m_tilt->SetValue(0.0);
732    SomethingChanged(svx_TILT);
733}
734
735void
736svxPrintDlg::OnPlanUpdate(wxUpdateUIEvent& e) {
737    e.Enable(m_tilt->GetValue() != -90.0);
738}
739
740void
741svxPrintDlg::OnElevationUpdate(wxUpdateUIEvent& e) {
742    e.Enable(m_tilt->GetValue() != 0.0);
743}
744
745void
746svxPrintDlg::OnChangeSpin(wxSpinDoubleEvent& e) {
747    SomethingChanged(e.GetId());
748}
749
750void
751svxPrintDlg::OnChange(wxCommandEvent& e) {
752    SomethingChanged(e.GetId());
753}
754
755void
756svxPrintDlg::OnChangeScale(wxCommandEvent& e) {
757    // Seems to be needed on macOS.
758    if (!m_scale) return;
759    wxString value = m_scale->GetValue();
760    if (value == "...") {
761        m_scale->SetValue("");
762        m_scale->SetFocus();
763    } else {
764        default_scale_print = value;
765        if (default_scale_print != scales[0]) {
766            // Don't store "One page" for use when exporting.
767            default_scale_export = default_scale_print;
768        }
769    }
770    SomethingChanged(e.GetId());
771}
772
773void
774svxPrintDlg::OnCancel(wxCommandEvent&) {
775    if (close_after)
776        mainfrm->Close();
777    Destroy();
778}
779
780void
781svxPrintDlg::SomethingChanged(int control_id) {
782    if ((control_id == 0 || control_id == svx_FORMAT) && m_format) {
783        // Update the shown/hidden fields for the newly selected export filter.
784        int new_filter_idx = m_format->GetSelection();
785        if (new_filter_idx != wxNOT_FOUND) {
786            unsigned mask = export_format_info[new_filter_idx].mask;
787            static const struct { int id; unsigned mask; } controls[] = {
788                { svx_LEGS, LEGS },
789                { svx_SURFACE, SURF },
790                { svx_SPLAYS, SPLAYS },
791                { svx_STATIONS, STNS },
792                { svx_NAMES, LABELS },
793                { svx_XSECT, XSECT },
794                { svx_WALLS, WALLS },
795                { svx_PASSAGES, PASG },
796                { svx_ENTS, ENTS },
797                { svx_FIXES, FIXES },
798                { svx_EXPORTS, EXPORTS },
799                { svx_CENTRED, CENTRED },
800                { svx_FULLCOORDS, FULL_COORDS },
801                { svx_CLAMP_TO_GROUND, CLAMP_TO_GROUND },
802            };
803            static unsigned n_controls = sizeof(controls) / sizeof(controls[0]);
804            for (unsigned i = 0; i != n_controls; ++i) {
805                wxWindow * control = FindWindow(controls[i].id);
806                if (control) control->Show(mask & controls[i].mask);
807            }
808            m_scalebox->Show(bool(mask & SCALE));
809            m_viewbox->Show(bool(mask & ORIENTABLE));
810            GetSizer()->Layout();
811            // Force the window to resize to match the updated layout.
812            if (control_id) SetSizerAndFit(GetSizer());
813            if (control_id == svx_FORMAT) {
814                wxConfigBase * cfg = wxConfigBase::Get();
815                cfg->Write(wxT("export_format"), formats[new_filter_idx]);
816            }
817        }
818    }
819
820    UIToLayout();
821
822    if (m_printSize || m_scale) {
823        // Update the bounding box.
824        RecalcBounds();
825
826        if (m_scale) {
827            // Remove the comment part (e.g. `(1":20')`).
828            wxString value = m_scale->GetValue();
829            auto comment = value.find('(');
830            if (comment != value.npos) value.resize(comment);
831            // Strip spaces as trailing spaces cause wxWidgets to fail to
832            // parse.
833            value.Replace(" ", "");
834            // Convert `,` to `.` and parse with ToCDouble() so either decimal
835            // separator works regardless of locale settings.
836            value.Replace(",", ".");
837            if (!value.ToCDouble(&(m_layout.Scale)) ||
838                m_layout.Scale == 0.0) {
839                m_layout.pick_scale(1, 1);
840            }
841        }
842    }
843
844    if (m_printSize && m_layout.xMax >= m_layout.xMin) {
845        m_layout.pages_required();
846        m_printSize->SetLabel(wxString::Format(wmsg(/*%d pages (%dx%d)*/257), m_layout.pages, m_layout.pagesX, m_layout.pagesY));
847    }
848}
849
850void
851svxPrintDlg::LayoutToUI()
852{
853//    m_blanks->SetValue(m_layout.SkipBlank);
854    if (m_layout.view != layout::EXTELEV) {
855        m_tilt->SetValue(m_layout.tilt);
856        m_bearing->SetValue(m_layout.rot);
857    }
858
859    if (m_scale && m_layout.Scale != 0) {
860        // Do this last as it causes an OnChange message which calls UIToLayout
861        wxString temp;
862        temp << m_layout.Scale;
863        m_scale->SetValue(temp);
864    }
865}
866
867void
868svxPrintDlg::UIToLayout()
869{
870//    m_layout.SkipBlank = m_blanks->IsChecked();
871
872    if (m_layout.view != layout::EXTELEV && m_tilt) {
873        m_layout.tilt = m_tilt->GetValue();
874        if (m_layout.tilt == -90.0) {
875            m_layout.view = layout::PLAN;
876        } else if (m_layout.tilt == 0.0) {
877            m_layout.view = layout::ELEV;
878        } else {
879            m_layout.view = layout::TILT;
880        }
881
882        bool enable_passage_opts = (m_layout.view != layout::TILT);
883        wxWindow * win;
884        win = FindWindow(svx_XSECT);
885        if (win) win->Enable(enable_passage_opts);
886        win = FindWindow(svx_WALLS);
887        if (win) win->Enable(enable_passage_opts);
888        win = FindWindow(svx_PASSAGES);
889        if (win) win->Enable(enable_passage_opts);
890
891        m_layout.rot = m_bearing->GetValue();
892    }
893}
894
895void
896svxPrintDlg::RecalcBounds()
897{
898    m_layout.yMax = m_layout.xMax = -DBL_MAX;
899    m_layout.yMin = m_layout.xMin = DBL_MAX;
900
901    double SIN = sin(rad(m_layout.rot));
902    double COS = cos(rad(m_layout.rot));
903    double SINT = sin(rad(m_layout.tilt));
904    double COST = cos(rad(m_layout.tilt));
905
906    const SurveyFilter* filter = mainfrm->GetTreeFilter();
907    int show_mask = m_layout.get_effective_show_mask();
908    if (show_mask & LEGS) {
909        for (int f = 0; f != 8; ++f) {
910            if ((show_mask & (f & img_FLAG_SURFACE) ? SURF : LEGS) == 0) {
911                // Not showing traverse because of surface/underground status.
912                continue;
913            }
914            if ((f & img_FLAG_SPLAY) && (show_mask & SPLAYS) == 0) {
915                // Not showing because it's a splay.
916                continue;
917            }
918            list<traverse>::const_iterator trav = mainfrm->traverses_begin(f, filter);
919            list<traverse>::const_iterator tend = mainfrm->traverses_end(f);
920            for ( ; trav != tend; trav = mainfrm->traverses_next(f, filter, trav)) {
921                vector<PointInfo>::const_iterator pos = trav->begin();
922                vector<PointInfo>::const_iterator end = trav->end();
923                for ( ; pos != end; ++pos) {
924                    double x = pos->GetX();
925                    double y = pos->GetY();
926                    double z = pos->GetZ();
927                    double X = x * COS - y * SIN;
928                    if (X > m_layout.xMax) m_layout.xMax = X;
929                    if (X < m_layout.xMin) m_layout.xMin = X;
930                    double Y = z * COST - (x * SIN + y * COS) * SINT;
931                    if (Y > m_layout.yMax) m_layout.yMax = Y;
932                    if (Y < m_layout.yMin) m_layout.yMin = Y;
933                }
934            }
935        }
936    }
937
938    if ((show_mask & XSECT) &&
939        (m_layout.tilt == 0.0 || m_layout.tilt == 90.0 || m_layout.tilt == -90.0)) {
940        list<vector<XSect>>::const_iterator trav = mainfrm->tubes_begin();
941        list<vector<XSect>>::const_iterator tend = mainfrm->tubes_end();
942        for ( ; trav != tend; ++trav) {
943            const XSect* prev_pt_v = NULL;
944            Vector3 last_right(1.0, 0.0, 0.0);
945
946            vector<XSect>::const_iterator i = trav->begin();
947            vector<XSect>::size_type segment = 0;
948            while (i != trav->end()) {
949                // get the coordinates of this vertex
950                const XSect & pt_v = *i++;
951                if (m_layout.tilt == 0.0) {
952                    double u = pt_v.GetU();
953                    double d = pt_v.GetD();
954
955                    if (u >= 0 || d >= 0) {
956                        if (filter && !filter->CheckVisible(pt_v.GetLabel()))
957                            continue;
958
959                        double x = pt_v.GetX();
960                        double y = pt_v.GetY();
961                        double z = pt_v.GetZ();
962                        double X = x * COS - y * SIN;
963                        double Y = z * COST - (x * SIN + y * COS) * SINT;
964
965                        if (X > m_layout.xMax) m_layout.xMax = X;
966                        if (X < m_layout.xMin) m_layout.xMin = X;
967                        double U = Y + max(0.0, pt_v.GetU());
968                        if (U > m_layout.yMax) m_layout.yMax = U;
969                        double D = Y - max(0.0, pt_v.GetD());
970                        if (D < m_layout.yMin) m_layout.yMin = D;
971                    }
972                } else {
973                    // More complex, and this duplicates the algorithm from
974                    // PlotLR() - we should try to share that, maybe via a
975                    // template.
976                    Vector3 right;
977
978                    const Vector3 up_v(0.0, 0.0, 1.0);
979
980                    if (segment == 0) {
981                        assert(i != trav->end());
982                        // first segment
983
984                        // get the coordinates of the next vertex
985                        const XSect & next_pt_v = *i;
986
987                        // calculate vector from this pt to the next one
988                        Vector3 leg_v = next_pt_v - pt_v;
989
990                        // obtain a vector in the LRUD plane
991                        right = leg_v * up_v;
992                        if (right.magnitude() == 0) {
993                            right = last_right;
994                        } else {
995                            last_right = right;
996                        }
997                    } else if (segment + 1 == trav->size()) {
998                        // last segment
999
1000                        // Calculate vector from the previous pt to this one.
1001                        Vector3 leg_v = pt_v - *prev_pt_v;
1002
1003                        // Obtain a horizontal vector in the LRUD plane.
1004                        right = leg_v * up_v;
1005                        if (right.magnitude() == 0) {
1006                            right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
1007                        } else {
1008                            last_right = right;
1009                        }
1010                    } else {
1011                        assert(i != trav->end());
1012                        // Intermediate segment.
1013
1014                        // Get the coordinates of the next vertex.
1015                        const XSect & next_pt_v = *i;
1016
1017                        // Calculate vectors from this vertex to the
1018                        // next vertex, and from the previous vertex to
1019                        // this one.
1020                        Vector3 leg1_v = pt_v - *prev_pt_v;
1021                        Vector3 leg2_v = next_pt_v - pt_v;
1022
1023                        // Obtain horizontal vectors perpendicular to
1024                        // both legs, then normalise and average to get
1025                        // a horizontal bisector.
1026                        Vector3 r1 = leg1_v * up_v;
1027                        Vector3 r2 = leg2_v * up_v;
1028                        r1.normalise();
1029                        r2.normalise();
1030                        right = r1 + r2;
1031                        if (right.magnitude() == 0) {
1032                            // This is the "mid-pitch" case...
1033                            right = last_right;
1034                        }
1035                        last_right = right;
1036                    }
1037
1038                    // Scale to unit vectors in the LRUD plane.
1039                    right.normalise();
1040
1041                    double l = pt_v.GetL();
1042                    double r = pt_v.GetR();
1043
1044                    if (l >= 0 || r >= 0) {
1045                        if (!filter || filter->CheckVisible(pt_v.GetLabel())) {
1046                            // Get the x and y coordinates of the survey station
1047                            double pt_X = pt_v.GetX() * COS - pt_v.GetY() * SIN;
1048                            double pt_Y = pt_v.GetX() * SIN + pt_v.GetY() * COS;
1049
1050                            double X, Y;
1051                            if (l >= 0) {
1052                                // Get the x and y coordinates of the end of the left arrow
1053                                Vector3 p = pt_v.GetPoint() - right * l;
1054                                X = p.GetX() * COS - p.GetY() * SIN;
1055                                Y = (p.GetX() * SIN + p.GetY() * COS);
1056                            } else {
1057                                X = pt_X;
1058                                Y = pt_Y;
1059                            }
1060                            if (X > m_layout.xMax) m_layout.xMax = X;
1061                            if (X < m_layout.xMin) m_layout.xMin = X;
1062                            if (Y > m_layout.yMax) m_layout.yMax = Y;
1063                            if (Y < m_layout.yMin) m_layout.yMin = Y;
1064
1065                            if (r >= 0) {
1066                                // Get the x and y coordinates of the end of the right arrow
1067                                Vector3 p = pt_v.GetPoint() + right * r;
1068                                X = p.GetX() * COS - p.GetY() * SIN;
1069                                Y = (p.GetX() * SIN + p.GetY() * COS);
1070                            } else {
1071                                X = pt_X;
1072                                Y = pt_Y;
1073                            }
1074                            if (X > m_layout.xMax) m_layout.xMax = X;
1075                            if (X < m_layout.xMin) m_layout.xMin = X;
1076                            if (Y > m_layout.yMax) m_layout.yMax = Y;
1077                            if (Y < m_layout.yMin) m_layout.yMin = Y;
1078                        }
1079                    }
1080
1081                    prev_pt_v = &pt_v;
1082
1083                    ++segment;
1084                }
1085            }
1086        }
1087    }
1088
1089    if (show_mask & (LABELS|STNS)) {
1090        for (auto label = mainfrm->GetLabels();
1091             label != mainfrm->GetLabelsEnd();
1092             ++label) {
1093            if (filter && !filter->CheckVisible((*label)->GetText()))
1094                continue;
1095            double x = (*label)->GetX();
1096            double y = (*label)->GetY();
1097            double z = (*label)->GetZ();
1098            if ((show_mask & SURF) || (*label)->IsUnderground()) {
1099                double X = x * COS - y * SIN;
1100                if (X > m_layout.xMax) m_layout.xMax = X;
1101                if (X < m_layout.xMin) m_layout.xMin = X;
1102                double Y = z * COST - (x * SIN + y * COS) * SINT;
1103                if (Y > m_layout.yMax) m_layout.yMax = Y;
1104                if (Y < m_layout.yMin) m_layout.yMin = Y;
1105            }
1106        }
1107    }
1108}
1109
1110static int xpPageWidth, ypPageDepth;
1111static long x_offset, y_offset;
1112static int fontsize, fontsize_labels;
1113
1114/* FIXME: allow the font to be set */
1115
1116static const char *fontname = "Arial", *fontname_labels = "Arial";
1117
1118svxPrintout::svxPrintout(MainFrm *mainfrm_, layout *l,
1119                         wxPageSetupDialogData *data, const wxString & title)
1120    : wxPrintout(title),
1121      mainfrm(mainfrm_), m_layout(l), m_data(data)
1122{
1123}
1124
1125void
1126svxPrintout::draw_info_box()
1127{
1128   layout *l = m_layout;
1129   int boxwidth = 70;
1130   int boxheight = 30;
1131
1132   pdc->SetPen(*pen_frame);
1133
1134   int div = boxwidth;
1135   if (l->view != layout::EXTELEV) {
1136      boxwidth += boxheight;
1137      MOVEMM(div, boxheight);
1138      DRAWMM(div, 0);
1139      MOVEMM(0, 30); DRAWMM(div, 30);
1140   }
1141
1142   MOVEMM(0, boxheight);
1143   DRAWMM(boxwidth, boxheight);
1144   DRAWMM(boxwidth, 0);
1145   if (!l->Border) {
1146      DRAWMM(0, 0);
1147      DRAWMM(0, boxheight);
1148   }
1149
1150   MOVEMM(0, 20); DRAWMM(div, 20);
1151   MOVEMM(0, 10); DRAWMM(div, 10);
1152
1153   switch (l->view) {
1154    case layout::PLAN: {
1155      long ax, ay, bx, by, cx, cy, dx, dy;
1156
1157      long xc = boxwidth - boxheight / 2;
1158      long yc = boxheight / 2;
1159      const double RADIUS = boxheight / 3;
1160      DrawEllipse(long(xc * l->scX), long(yc * l->scY),
1161                  long(RADIUS * l->scX), long(RADIUS * l->scY));
1162
1163      ax = (long)((xc - (RADIUS - 1) * sin(rad(000.0 + l->rot))) * l->scX);
1164      ay = (long)((yc + (RADIUS - 1) * cos(rad(000.0 + l->rot))) * l->scY);
1165      bx = (long)((xc - RADIUS * 0.5 * sin(rad(180.0 + l->rot))) * l->scX);
1166      by = (long)((yc + RADIUS * 0.5 * cos(rad(180.0 + l->rot))) * l->scY);
1167      cx = (long)((xc - (RADIUS - 1) * sin(rad(160.0 + l->rot))) * l->scX);
1168      cy = (long)((yc + (RADIUS - 1) * cos(rad(160.0 + l->rot))) * l->scY);
1169      dx = (long)((xc - (RADIUS - 1) * sin(rad(200.0 + l->rot))) * l->scX);
1170      dy = (long)((yc + (RADIUS - 1) * cos(rad(200.0 + l->rot))) * l->scY);
1171
1172      MoveTo(ax, ay);
1173      DrawTo(bx, by);
1174      DrawTo(cx, cy);
1175      DrawTo(ax, ay);
1176      DrawTo(dx, dy);
1177      DrawTo(bx, by);
1178
1179      pdc->SetTextForeground(colour_text);
1180      MOVEMM(div + 0.5, boxheight - 5.5);
1181      WriteString(wmsg(/*North*/115));
1182
1183      wxString angle = format_angle(ANGLE_FMT, l->rot);
1184      wxString s;
1185      /* TRANSLATORS: This is used on printouts of plans, with %s replaced by
1186       * something like "123°".  The bearing is up the page. */
1187      s.Printf(wmsg(/*Plan view, %s up page*/168), angle.c_str());
1188      MOVEMM(2, 12); WriteString(s);
1189      break;
1190    }
1191    case layout::ELEV: case layout::TILT: {
1192      const int L = div + 2;
1193      const int R = boxwidth - 2;
1194      const int H = boxheight / 2;
1195      MOVEMM(L, H); DRAWMM(L + 5, H - 3); DRAWMM(L + 3, H); DRAWMM(L + 5, H + 3);
1196
1197      DRAWMM(L, H); DRAWMM(R, H);
1198
1199      DRAWMM(R - 5, H + 3); DRAWMM(R - 3, H); DRAWMM(R - 5, H - 3); DRAWMM(R, H);
1200
1201      MOVEMM((L + R) / 2, H - 2); DRAWMM((L + R) / 2, H + 2);
1202
1203      pdc->SetTextForeground(colour_text);
1204      MOVEMM(div + 2, boxheight - 8);
1205      /* TRANSLATORS: "Elevation on" 020 <-> 200 degrees */
1206      WriteString(wmsg(/*Elevation on*/116));
1207
1208      MOVEMM(L, 2);
1209      WriteString(format_angle(ANGLE_FMT, fmod(l->rot + 270.0, 360.0)));
1210      MOVEMM(R - 10, 2);
1211      WriteString(format_angle(ANGLE_FMT, fmod(l->rot + 90.0, 360.0)));
1212
1213      wxString angle = format_angle(ANGLE_FMT, l->rot);
1214      wxString s;
1215      if (l->view == layout::ELEV) {
1216          /* TRANSLATORS: This is used on printouts of elevations, with %s
1217           * replaced by something like "123°".  The bearing is the direction
1218           * we’re looking. */
1219          s.Printf(wmsg(/*Elevation facing %s*/169), angle.c_str());
1220      } else {
1221          wxString a2 = format_angle(ANGLE2_FMT, l->tilt);
1222          /* TRANSLATORS: This is used on printouts of tilted elevations, with
1223           * the first %s replaced by something like "123°", and the second by
1224           * something like "-45°".  The bearing is the direction we’re
1225           * looking. */
1226          s.Printf(wmsg(/*Elevation facing %s, tilted %s*/284), angle.c_str(), a2.c_str());
1227      }
1228      MOVEMM(2, 12); WriteString(s);
1229      break;
1230    }
1231    case layout::EXTELEV:
1232      pdc->SetTextForeground(colour_text);
1233      MOVEMM(2, 12);
1234      /* TRANSLATORS: This is used on printouts of extended elevations. */
1235      WriteString(wmsg(/*Extended elevation*/191));
1236      break;
1237   }
1238
1239   MOVEMM(2, boxheight - 8); WriteString(l->title);
1240
1241   MOVEMM(2, 2);
1242   // FIXME: "Original Scale" better?
1243   WriteString(wxString::Format(wmsg(/*Scale*/154) + wxT(" 1:%.0f"),
1244                                l->Scale));
1245
1246   /* This used to be a copyright line, but it was occasionally
1247    * mis-interpreted as us claiming copyright on the survey, so let's
1248    * give the website URL instead */
1249   MOVEMM(boxwidth + 2, 2);
1250   WriteString(wxT("Survex " VERSION " - https://survex.com/"));
1251
1252   draw_scale_bar(boxwidth + 10.0, 17.0, l->PaperWidth - boxwidth - 18.0);
1253}
1254
1255/* Draw fancy scale bar with bottom left at (x,y) (both in mm) and at most */
1256/* MaxLength mm long. The scaling in use is 1:scale */
1257void
1258svxPrintout::draw_scale_bar(double x, double y, double MaxLength)
1259{
1260   double StepEst, d;
1261   int E, Step, n, c;
1262   wxString buf;
1263   /* Limit scalebar to 20cm to stop people with A0 plotters complaining */
1264   if (MaxLength > 200.0) MaxLength = 200.0;
1265
1266#define dmin 10.0      /* each division >= dmin mm long */
1267#define StepMax 5      /* number in steps of at most StepMax (x 10^N) */
1268#define epsilon (1e-4) /* fudge factor to prevent rounding problems */
1269
1270   E = (int)ceil(log10((dmin * 0.001 * m_layout->Scale) / StepMax));
1271   StepEst = pow(10.0, -(double)E) * (dmin * 0.001) * m_layout->Scale - epsilon;
1272
1273   /* Force labelling to be in multiples of 1, 2, or 5 */
1274   Step = (StepEst <= 1.0 ? 1 : (StepEst <= 2.0 ? 2 : 5));
1275
1276   /* Work out actual length of each scale bar division */
1277   d = Step * pow(10.0, (double)E) / m_layout->Scale * 1000.0;
1278
1279   /* FIXME: Non-metric units here... */
1280   /* Choose appropriate units, s.t. if possible E is >=0 and minimized */
1281   int units;
1282   if (E >= 3) {
1283      E -= 3;
1284      units = /*km*/423;
1285   } else if (E >= 0) {
1286      units = /*m*/424;
1287   } else {
1288      E += 2;
1289      units = /*cm*/425;
1290   }
1291
1292   buf = wmsg(/*Scale*/154);
1293
1294   /* Add units used - eg. "Scale (10m)" */
1295   double pow10_E = pow(10.0, (double)E);
1296   if (E >= 0) {
1297      buf += wxString::Format(wxT(" (%.f%s)"), pow10_E, wmsg(units).c_str());
1298   } else {
1299      int sf = -(int)floor(E);
1300      buf += wxString::Format(wxT(" (%.*f%s)"), sf, pow10_E, wmsg(units).c_str());
1301   }
1302   pdc->SetTextForeground(colour_text);
1303   MOVEMM(x, y + 4); WriteString(buf);
1304
1305   /* Work out how many divisions there will be */
1306   n = (int)(MaxLength / d);
1307
1308   pdc->SetPen(*pen_frame);
1309
1310   long Y = long(y * m_layout->scY);
1311   long Y2 = long((y + 3) * m_layout->scY);
1312   long X = long(x * m_layout->scX);
1313   long X2 = long((x + n * d) * m_layout->scX);
1314
1315   /* Draw top of scale bar */
1316   MoveTo(X2, Y2);
1317   DrawTo(X, Y2);
1318#if 0
1319   DrawTo(X2, Y);
1320   DrawTo(X, Y);
1321   MOVEMM(x + n * d, y); DRAWMM(x, y);
1322#endif
1323   /* Draw divisions and label them */
1324   for (c = 0; c <= n; c++) {
1325      pdc->SetPen(*pen_frame);
1326      X = long((x + c * d) * m_layout->scX);
1327      MoveTo(X, Y);
1328      DrawTo(X, Y2);
1329#if 0 // Don't waste toner!
1330      /* Draw a "zebra crossing" scale bar. */
1331      if (c < n && (c & 1) == 0) {
1332          X2 = long((x + (c + 1) * d) * m_layout->scX);
1333          SolidRectangle(X, Y, X2 - X, Y2 - Y);
1334      }
1335#endif
1336      buf.Printf(wxT("%d"), c * Step);
1337      pdc->SetTextForeground(colour_text);
1338      MOVEMM(x + c * d - buf.length(), y - 5);
1339      WriteString(buf);
1340   }
1341}
1342
1343#if 0
1344void
1345make_calibration(layout *l) {
1346      img_point pt = { 0.0, 0.0, 0.0 };
1347      l->xMax = l->yMax = 0.1;
1348      l->xMin = l->yMin = 0;
1349
1350      stack(l, img_MOVE, NULL, &pt);
1351      pt.x = 0.1;
1352      stack(l, img_LINE, NULL, &pt);
1353      pt.y = 0.1;
1354      stack(l, img_LINE, NULL, &pt);
1355      pt.x = 0.0;
1356      stack(l, img_LINE, NULL, &pt);
1357      pt.y = 0.0;
1358      stack(l, img_LINE, NULL, &pt);
1359      pt.x = 0.05;
1360      pt.y = 0.001;
1361      stack(l, img_LABEL, "10cm", &pt);
1362      pt.x = 0.001;
1363      pt.y = 0.05;
1364      stack(l, img_LABEL, "10cm", &pt);
1365      l->Scale = 1.0;
1366}
1367#endif
1368
1369int
1370svxPrintout::next_page(int *pstate, char **q, int pageLim)
1371{
1372   char *p;
1373   int page;
1374   int c;
1375   p = *q;
1376   if (*pstate > 0) {
1377      /* doing a range */
1378      (*pstate)++;
1379      wxASSERT(*p == '-');
1380      p++;
1381      while (isspace((unsigned char)*p)) p++;
1382      if (sscanf(p, "%u%n", &page, &c) > 0) {
1383         p += c;
1384      } else {
1385         page = pageLim;
1386      }
1387      if (*pstate > page) goto err;
1388      if (*pstate < page) return *pstate;
1389      *q = p;
1390      *pstate = 0;
1391      return page;
1392   }
1393
1394   while (isspace((unsigned char)*p) || *p == ',') p++;
1395
1396   if (!*p) return 0; /* done */
1397
1398   if (*p == '-') {
1399      *q = p;
1400      *pstate = 1;
1401      return 1; /* range with initial parameter omitted */
1402   }
1403   if (sscanf(p, "%u%n", &page, &c) > 0) {
1404      p += c;
1405      while (isspace((unsigned char)*p)) p++;
1406      *q = p;
1407      if (0 < page && page <= pageLim) {
1408         if (*p == '-') *pstate = page; /* range with start */
1409         return page;
1410      }
1411   }
1412   err:
1413   *pstate = -1;
1414   return 0;
1415}
1416
1417/* Draws in alignment marks on each page or borders on edge pages */
1418void
1419svxPrintout::drawticks(int tsize, int x, int y)
1420{
1421   long i;
1422   int s = tsize * 4;
1423   int o = s / 8;
1424   bool fAtCorner = false;
1425   pdc->SetPen(*pen_frame);
1426   if (x == 0 && m_layout->Border) {
1427      /* solid left border */
1428      MoveTo(clip.x_min, clip.y_min);
1429      DrawTo(clip.x_min, clip.y_max);
1430      fAtCorner = true;
1431   } else {
1432      if (x > 0 || y > 0) {
1433         MoveTo(clip.x_min, clip.y_min);
1434         DrawTo(clip.x_min, clip.y_min + tsize);
1435      }
1436      if (s && x > 0 && m_layout->Cutlines) {
1437         /* dashed left border */
1438         i = (clip.y_max - clip.y_min) -
1439             (tsize + ((clip.y_max - clip.y_min - tsize * 2L) % s) / 2);
1440         for ( ; i > tsize; i -= s) {
1441            MoveTo(clip.x_min, clip.y_max - (i + o));
1442            DrawTo(clip.x_min, clip.y_max - (i - o));
1443         }
1444      }
1445      if (x > 0 || y < m_layout->pagesY - 1) {
1446         MoveTo(clip.x_min, clip.y_max - tsize);
1447         DrawTo(clip.x_min, clip.y_max);
1448         fAtCorner = true;
1449      }
1450   }
1451
1452   if (y == m_layout->pagesY - 1 && m_layout->Border) {
1453      /* solid top border */
1454      if (!fAtCorner) MoveTo(clip.x_min, clip.y_max);
1455      DrawTo(clip.x_max, clip.y_max);
1456      fAtCorner = true;
1457   } else {
1458      if (y < m_layout->pagesY - 1 || x > 0) {
1459         if (!fAtCorner) MoveTo(clip.x_min, clip.y_max);
1460         DrawTo(clip.x_min + tsize, clip.y_max);
1461      }
1462      if (s && y < m_layout->pagesY - 1 && m_layout->Cutlines) {
1463         /* dashed top border */
1464         i = (clip.x_max - clip.x_min) -
1465             (tsize + ((clip.x_max - clip.x_min - tsize * 2L) % s) / 2);
1466         for ( ; i > tsize; i -= s) {
1467            MoveTo(clip.x_max - (i + o), clip.y_max);
1468            DrawTo(clip.x_max - (i - o), clip.y_max);
1469         }
1470      }
1471      if (y < m_layout->pagesY - 1 || x < m_layout->pagesX - 1) {
1472         MoveTo(clip.x_max - tsize, clip.y_max);
1473         DrawTo(clip.x_max, clip.y_max);
1474         fAtCorner = true;
1475      } else {
1476         fAtCorner = false;
1477      }
1478   }
1479
1480   if (x == m_layout->pagesX - 1 && m_layout->Border) {
1481      /* solid right border */
1482      if (!fAtCorner) MoveTo(clip.x_max, clip.y_max);
1483      DrawTo(clip.x_max, clip.y_min);
1484      fAtCorner = true;
1485   } else {
1486      if (x < m_layout->pagesX - 1 || y < m_layout->pagesY - 1) {
1487         if (!fAtCorner) MoveTo(clip.x_max, clip.y_max);
1488         DrawTo(clip.x_max, clip.y_max - tsize);
1489      }
1490      if (s && x < m_layout->pagesX - 1 && m_layout->Cutlines) {
1491         /* dashed right border */
1492         i = (clip.y_max - clip.y_min) -
1493             (tsize + ((clip.y_max - clip.y_min - tsize * 2L) % s) / 2);
1494         for ( ; i > tsize; i -= s) {
1495            MoveTo(clip.x_max, clip.y_min + (i + o));
1496            DrawTo(clip.x_max, clip.y_min + (i - o));
1497         }
1498      }
1499      if (x < m_layout->pagesX - 1 || y > 0) {
1500         MoveTo(clip.x_max, clip.y_min + tsize);
1501         DrawTo(clip.x_max, clip.y_min);
1502         fAtCorner = true;
1503      } else {
1504         fAtCorner = false;
1505      }
1506   }
1507
1508   if (y == 0 && m_layout->Border) {
1509      /* solid bottom border */
1510      if (!fAtCorner) MoveTo(clip.x_max, clip.y_min);
1511      DrawTo(clip.x_min, clip.y_min);
1512   } else {
1513      if (y > 0 || x < m_layout->pagesX - 1) {
1514         if (!fAtCorner) MoveTo(clip.x_max, clip.y_min);
1515         DrawTo(clip.x_max - tsize, clip.y_min);
1516      }
1517      if (s && y > 0 && m_layout->Cutlines) {
1518         /* dashed bottom border */
1519         i = (clip.x_max - clip.x_min) -
1520             (tsize + ((clip.x_max - clip.x_min - tsize * 2L) % s) / 2);
1521         for ( ; i > tsize; i -= s) {
1522            MoveTo(clip.x_min + (i + o), clip.y_min);
1523            DrawTo(clip.x_min + (i - o), clip.y_min);
1524         }
1525      }
1526      if (y > 0 || x > 0) {
1527         MoveTo(clip.x_min + tsize, clip.y_min);
1528         DrawTo(clip.x_min, clip.y_min);
1529      }
1530   }
1531}
1532
1533bool
1534svxPrintout::OnPrintPage(int pageNum) {
1535    GetPageSizePixels(&xpPageWidth, &ypPageDepth);
1536    pdc = GetDC();
1537    pdc->SetBackgroundMode(wxTRANSPARENT);
1538#ifdef AVEN_PRINT_PREVIEW
1539    if (IsPreview()) {
1540        int dcx, dcy;
1541        pdc->GetSize(&dcx, &dcy);
1542        pdc->SetUserScale((double)dcx / xpPageWidth, (double)dcy / ypPageDepth);
1543    }
1544#endif
1545
1546    layout * l = m_layout;
1547    {
1548        int pwidth, pdepth;
1549        GetPageSizeMM(&pwidth, &pdepth);
1550        l->scX = (double)xpPageWidth / pwidth;
1551        l->scY = (double)ypPageDepth / pdepth;
1552        font_scaling_x = l->scX * (25.4 / 72.0);
1553        font_scaling_y = l->scY * (25.4 / 72.0);
1554        long MarginLeft = m_data->GetMarginTopLeft().x;
1555        long MarginTop = m_data->GetMarginTopLeft().y;
1556        long MarginBottom = m_data->GetMarginBottomRight().y;
1557        long MarginRight = m_data->GetMarginBottomRight().x;
1558        xpPageWidth -= (int)(l->scX * (MarginLeft + MarginRight));
1559        ypPageDepth -= (int)(l->scY * (FOOTER_HEIGHT_MM + MarginBottom + MarginTop));
1560        // xpPageWidth -= 1;
1561        pdepth -= FOOTER_HEIGHT_MM;
1562        x_offset = (long)(l->scX * MarginLeft);
1563        y_offset = (long)(l->scY * MarginTop);
1564        l->PaperWidth = pwidth -= MarginLeft + MarginRight;
1565        l->PaperDepth = pdepth -= MarginTop + MarginBottom;
1566    }
1567
1568    double SIN = sin(rad(l->rot));
1569    double COS = cos(rad(l->rot));
1570    double SINT = sin(rad(l->tilt));
1571    double COST = cos(rad(l->tilt));
1572
1573    NewPage(pageNum, l->pagesX, l->pagesY);
1574
1575    if (l->Legend && pageNum == (l->pagesY - 1) * l->pagesX + 1) {
1576        SetFont(font_default);
1577        draw_info_box();
1578    }
1579
1580    pdc->SetClippingRegion(x_offset, y_offset, xpPageWidth + 1, ypPageDepth + 1);
1581
1582    const double Sc = 1000 / l->Scale;
1583
1584    const SurveyFilter* filter = mainfrm->GetTreeFilter();
1585    int show_mask = l->get_effective_show_mask();
1586    if (show_mask & (LEGS|SURF)) {
1587        for (int f = 0; f != 8; ++f) {
1588            if ((show_mask & (f & img_FLAG_SURFACE) ? SURF : LEGS) == 0) {
1589                // Not showing traverse because of surface/underground status.
1590                continue;
1591            }
1592            if ((f & img_FLAG_SPLAY) && (show_mask & SPLAYS) == 0) {
1593                // Not showing because it's a splay.
1594                continue;
1595            }
1596            if (f & img_FLAG_SPLAY) {
1597                pdc->SetPen(*pen_splay);
1598            } else if (f & img_FLAG_SURFACE) {
1599                pdc->SetPen(*pen_surface_leg);
1600            } else {
1601                pdc->SetPen(*pen_leg);
1602            }
1603            list<traverse>::const_iterator trav = mainfrm->traverses_begin(f, filter);
1604            list<traverse>::const_iterator tend = mainfrm->traverses_end(f);
1605            for ( ; trav != tend; trav = mainfrm->traverses_next(f, filter, trav)) {
1606                vector<PointInfo>::const_iterator pos = trav->begin();
1607                vector<PointInfo>::const_iterator end = trav->end();
1608                for ( ; pos != end; ++pos) {
1609                    double x = pos->GetX();
1610                    double y = pos->GetY();
1611                    double z = pos->GetZ();
1612                    double X = x * COS - y * SIN;
1613                    double Y = z * COST - (x * SIN + y * COS) * SINT;
1614                    long px = (long)((X * Sc + l->xOrg) * l->scX);
1615                    long py = (long)((Y * Sc + l->yOrg) * l->scY);
1616                    if (pos == trav->begin()) {
1617                        MoveTo(px, py);
1618                    } else {
1619                        DrawTo(px, py);
1620                    }
1621                }
1622            }
1623        }
1624    }
1625
1626    if ((show_mask & XSECT) &&
1627        (l->tilt == 0.0 || l->tilt == 90.0 || l->tilt == -90.0)) {
1628        pdc->SetPen(*pen_splay);
1629        list<vector<XSect>>::const_iterator trav = mainfrm->tubes_begin();
1630        list<vector<XSect>>::const_iterator tend = mainfrm->tubes_end();
1631        for ( ; trav != tend; ++trav) {
1632            if (l->tilt == 0.0) {
1633                PlotUD(*trav);
1634            } else {
1635                // m_layout.tilt is 90.0 or -90.0 due to check above.
1636                PlotLR(*trav);
1637            }
1638        }
1639    }
1640
1641    if (show_mask & (LABELS|STNS)) {
1642        if (show_mask & LABELS) SetFont(font_labels);
1643        for (auto label = mainfrm->GetLabels();
1644             label != mainfrm->GetLabelsEnd();
1645             ++label) {
1646            if (filter && !filter->CheckVisible((*label)->GetText()))
1647                continue;
1648            double px = (*label)->GetX();
1649            double py = (*label)->GetY();
1650            double pz = (*label)->GetZ();
1651            if ((show_mask & SURF) || (*label)->IsUnderground()) {
1652                double X = px * COS - py * SIN;
1653                double Y = pz * COST - (px * SIN + py * COS) * SINT;
1654                long xnew, ynew;
1655                xnew = (long)((X * Sc + l->xOrg) * l->scX);
1656                ynew = (long)((Y * Sc + l->yOrg) * l->scY);
1657                if (show_mask & STNS) {
1658                    pdc->SetPen(*pen_cross);
1659                    DrawCross(xnew, ynew);
1660                }
1661                if (show_mask & LABELS) {
1662                    pdc->SetTextForeground(colour_labels);
1663                    MoveTo(xnew, ynew);
1664                    WriteString((*label)->GetText());
1665                }
1666            }
1667        }
1668    }
1669
1670    return true;
1671}
1672
1673void
1674svxPrintout::GetPageInfo(int *minPage, int *maxPage,
1675                         int *pageFrom, int *pageTo)
1676{
1677    *minPage = *pageFrom = 1;
1678    *maxPage = *pageTo = m_layout->pages;
1679}
1680
1681bool
1682svxPrintout::HasPage(int pageNum) {
1683    return (pageNum <= m_layout->pages);
1684}
1685
1686void
1687svxPrintout::OnBeginPrinting() {
1688    /* Initialise printer routines */
1689    fontsize_labels = 10;
1690    fontsize = 10;
1691
1692    colour_text = colour_labels = *wxBLACK;
1693
1694    wxColour colour_frame, colour_cross, colour_leg, colour_surface_leg;
1695    colour_frame = colour_cross = colour_leg = colour_surface_leg = *wxBLACK;
1696
1697    pen_frame = new wxPen(colour_frame);
1698    pen_cross = new wxPen(colour_cross);
1699    pen_leg = new wxPen(colour_leg);
1700    pen_surface_leg = new wxPen(colour_surface_leg);
1701    pen_splay = new wxPen(wxColour(128, 128, 128));
1702
1703    m_layout->scX = 1;
1704    m_layout->scY = 1;
1705
1706    font_labels = new wxFont(fontsize_labels, wxFONTFAMILY_DEFAULT,
1707                             wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL,
1708                             false, wxString(fontname_labels, wxConvUTF8),
1709                             wxFONTENCODING_ISO8859_1);
1710    font_default = new wxFont(fontsize, wxFONTFAMILY_DEFAULT,
1711                              wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL,
1712                              false, wxString(fontname, wxConvUTF8),
1713                              wxFONTENCODING_ISO8859_1);
1714}
1715
1716void
1717svxPrintout::OnEndPrinting() {
1718    delete font_labels;
1719    delete font_default;
1720    delete pen_frame;
1721    delete pen_cross;
1722    delete pen_leg;
1723    delete pen_surface_leg;
1724    delete pen_splay;
1725}
1726
1727int
1728svxPrintout::check_intersection(long x_p, long y_p)
1729{
1730#define U 1
1731#define D 2
1732#define L 4
1733#define R 8
1734   int mask_p = 0, mask_t = 0;
1735   if (x_p < 0)
1736      mask_p = L;
1737   else if (x_p > xpPageWidth)
1738      mask_p = R;
1739
1740   if (y_p < 0)
1741      mask_p |= D;
1742   else if (y_p > ypPageDepth)
1743      mask_p |= U;
1744
1745   if (x_t < 0)
1746      mask_t = L;
1747   else if (x_t > xpPageWidth)
1748      mask_t = R;
1749
1750   if (y_t < 0)
1751      mask_t |= D;
1752   else if (y_t > ypPageDepth)
1753      mask_t |= U;
1754
1755#if 0
1756   /* approximation to correct answer */
1757   return !(mask_t & mask_p);
1758#else
1759   /* One end of the line is on the page */
1760   if (!mask_t || !mask_p) return 1;
1761
1762   /* whole line is above, left, right, or below page */
1763   if (mask_t & mask_p) return 0;
1764
1765   if (mask_t == 0) mask_t = mask_p;
1766   if (mask_t & U) {
1767      double v = (double)(y_p - ypPageDepth) / (y_p - y_t);
1768      return v >= 0 && v <= 1;
1769   }
1770   if (mask_t & D) {
1771      double v = (double)y_p / (y_p - y_t);
1772      return v >= 0 && v <= 1;
1773   }
1774   if (mask_t & R) {
1775      double v = (double)(x_p - xpPageWidth) / (x_p - x_t);
1776      return v >= 0 && v <= 1;
1777   }
1778   wxASSERT(mask_t & L);
1779   {
1780      double v = (double)x_p / (x_p - x_t);
1781      return v >= 0 && v <= 1;
1782   }
1783#endif
1784#undef U
1785#undef D
1786#undef L
1787#undef R
1788}
1789
1790void
1791svxPrintout::MoveTo(long x, long y)
1792{
1793    x_t = x_offset + x - clip.x_min;
1794    y_t = y_offset + clip.y_max - y;
1795}
1796
1797void
1798svxPrintout::DrawTo(long x, long y)
1799{
1800    long x_p = x_t, y_p = y_t;
1801    x_t = x_offset + x - clip.x_min;
1802    y_t = y_offset + clip.y_max - y;
1803    if (!scan_for_blank_pages) {
1804        pdc->DrawLine(x_p, y_p, x_t, y_t);
1805    } else {
1806        if (check_intersection(x_p, y_p)) fBlankPage = false;
1807    }
1808}
1809
1810#define PWX_CROSS_SIZE (int)(2 * m_layout->scX / POINTS_PER_MM)
1811
1812void
1813svxPrintout::DrawCross(long x, long y)
1814{
1815   if (!scan_for_blank_pages) {
1816      MoveTo(x - PWX_CROSS_SIZE, y - PWX_CROSS_SIZE);
1817      DrawTo(x + PWX_CROSS_SIZE, y + PWX_CROSS_SIZE);
1818      MoveTo(x + PWX_CROSS_SIZE, y - PWX_CROSS_SIZE);
1819      DrawTo(x - PWX_CROSS_SIZE, y + PWX_CROSS_SIZE);
1820      MoveTo(x, y);
1821   } else {
1822      if ((x + PWX_CROSS_SIZE > clip.x_min &&
1823           x - PWX_CROSS_SIZE < clip.x_max) ||
1824          (y + PWX_CROSS_SIZE > clip.y_min &&
1825           y - PWX_CROSS_SIZE < clip.y_max)) {
1826         fBlankPage = false;
1827      }
1828   }
1829}
1830
1831void
1832svxPrintout::WriteString(const wxString & s)
1833{
1834    double xsc, ysc;
1835    pdc->GetUserScale(&xsc, &ysc);
1836    pdc->SetUserScale(xsc * font_scaling_x, ysc * font_scaling_y);
1837    if (!scan_for_blank_pages) {
1838        pdc->DrawText(s,
1839                      long(x_t / font_scaling_x),
1840                      long(y_t / font_scaling_y) - pdc->GetCharHeight());
1841    } else {
1842        int w, h;
1843        pdc->GetTextExtent(s, &w, &h);
1844        if ((y_t + h > 0 && y_t - h < clip.y_max - clip.y_min) ||
1845            (x_t < clip.x_max - clip.x_min && x_t + w > 0)) {
1846            fBlankPage = false;
1847        }
1848    }
1849    pdc->SetUserScale(xsc, ysc);
1850}
1851
1852void
1853svxPrintout::DrawEllipse(long x, long y, long r, long R)
1854{
1855    if (!scan_for_blank_pages) {
1856        x_t = x_offset + x - clip.x_min;
1857        y_t = y_offset + clip.y_max - y;
1858        const wxBrush & save_brush = pdc->GetBrush();
1859        pdc->SetBrush(*wxTRANSPARENT_BRUSH);
1860        pdc->DrawEllipse(x_t - r, y_t - R, 2 * r, 2 * R);
1861        pdc->SetBrush(save_brush);
1862    } else {
1863        /* No need to check - this is only used in the legend. */
1864    }
1865}
1866
1867void
1868svxPrintout::SolidRectangle(long x, long y, long w, long h)
1869{
1870    long X = x_offset + x - clip.x_min;
1871    long Y = y_offset + clip.y_max - y;
1872    pdc->SetBrush(*wxBLACK_BRUSH);
1873    pdc->DrawRectangle(X, Y - h, w, h);
1874}
1875
1876void
1877svxPrintout::NewPage(int pg, int pagesX, int pagesY)
1878{
1879    pdc->DestroyClippingRegion();
1880
1881    int x, y;
1882    x = (pg - 1) % pagesX;
1883    y = pagesY - 1 - ((pg - 1) / pagesX);
1884
1885    clip.x_min = (long)x * xpPageWidth;
1886    clip.y_min = (long)y * ypPageDepth;
1887    clip.x_max = clip.x_min + xpPageWidth; /* dm/pcl/ps had -1; */
1888    clip.y_max = clip.y_min + ypPageDepth; /* dm/pcl/ps had -1; */
1889
1890    const int FOOTERS = 4;
1891    wxString footer[FOOTERS];
1892    footer[0] = m_layout->title;
1893
1894    double rot = m_layout->rot;
1895    double tilt = m_layout->tilt;
1896    double scale = m_layout->Scale;
1897    switch (m_layout->view) {
1898        case layout::PLAN:
1899            // TRANSLATORS: Used in the footer of printouts to compactly
1900            // indicate this is a plan view and what the viewing angle is.
1901            // Aven will replace %s with the bearing, and %.0f with the scale.
1902            //
1903            // This message probably doesn't need translating for most languages.
1904            footer[1].Printf(wmsg(/*↑%s 1:%.0f*/233),
1905                    format_angle(ANGLE_FMT, rot).c_str(),
1906                    scale);
1907            break;
1908        case layout::ELEV:
1909            // TRANSLATORS: Used in the footer of printouts to compactly
1910            // indicate this is an elevation view and what the viewing angle
1911            // is.  Aven will replace the %s codes with the bearings to the
1912            // left and right of the viewer, and %.0f with the scale.
1913            //
1914            // This message probably doesn't need translating for most languages.
1915            footer[1].Printf(wmsg(/*%s↔%s 1:%.0f*/235),
1916                    format_angle(ANGLE_FMT, fmod(rot + 270.0, 360.0)).c_str(),
1917                    format_angle(ANGLE_FMT, fmod(rot + 90.0, 360.0)).c_str(),
1918                    scale);
1919            break;
1920        case layout::TILT:
1921            // TRANSLATORS: Used in the footer of printouts to compactly
1922            // indicate this is a tilted elevation view and what the viewing
1923            // angles are.  Aven will replace the %s codes with the bearings to
1924            // the left and right of the viewer and the angle the view is
1925            // tilted at, and %.0f with the scale.
1926            //
1927            // This message probably doesn't need translating for most languages.
1928            footer[1].Printf(wmsg(/*%s↔%s ∡%s 1:%.0f*/236),
1929                    format_angle(ANGLE_FMT, fmod(rot + 270.0, 360.0)).c_str(),
1930                    format_angle(ANGLE_FMT, fmod(rot + 90.0, 360.0)).c_str(),
1931                    format_angle(ANGLE2_FMT, tilt).c_str(),
1932                    scale);
1933            break;
1934        case layout::EXTELEV:
1935            // TRANSLATORS: Used in the footer of printouts to compactly
1936            // indicate this is an extended elevation view.  Aven will replace
1937            // %.0f with the scale.
1938            //
1939            // Try to keep the translation short (for example, in English we
1940            // use "Extended" not "Extended elevation") - there is limited room
1941            // in the footer, and the details there are mostly to make it easy
1942            // to check that you have corresponding pages from a multiple page
1943            // printout.
1944            footer[1].Printf(wmsg(/*Extended 1:%.0f*/244), scale);
1945            break;
1946    }
1947
1948    // TRANSLATORS: N/M meaning page N of M in the page footer of a printout.
1949    footer[2].Printf(wmsg(/*%d/%d*/232), pg, m_layout->pagesX * m_layout->pagesY);
1950
1951    wxString datestamp = m_layout->datestamp;
1952    if (!datestamp.empty()) {
1953        // Remove any timezone suffix (e.g. " UTC" or " +1200").
1954        wxChar ch = datestamp[datestamp.size() - 1];
1955        if (ch >= 'A' && ch <= 'Z') {
1956            for (size_t i = datestamp.size() - 1; i; --i) {
1957                ch = datestamp[i];
1958                if (ch < 'A' || ch > 'Z') {
1959                    if (ch == ' ') datestamp.resize(i);
1960                    break;
1961                }
1962            }
1963        } else if (ch >= '0' && ch <= '9') {
1964            for (size_t i = datestamp.size() - 1; i; --i) {
1965                ch = datestamp[i];
1966                if (ch < '0' || ch > '9') {
1967                    if ((ch == '-' || ch == '+') && datestamp[--i] == ' ')
1968                        datestamp.resize(i);
1969                    break;
1970                }
1971            }
1972        }
1973
1974        // Remove any day prefix (e.g. "Mon,").
1975        for (size_t i = 0; i != datestamp.size(); ++i) {
1976            if (datestamp[i] == ',' && i + 1 != datestamp.size()) {
1977                // Also skip a space after the comma.
1978                if (datestamp[i + 1] == ' ') ++i;
1979                datestamp.erase(0, i + 1);
1980                break;
1981            }
1982        }
1983    }
1984
1985    // TRANSLATORS: Used in the footer of printouts to compactly indicate that
1986    // the date which follows is the date that the survey data was processed.
1987    //
1988    // Aven will replace %s with a string giving the date and time (e.g.
1989    // "2015-06-09 12:40:44").
1990    footer[3].Printf(wmsg(/*Processed: %s*/167), datestamp.c_str());
1991
1992    const wxChar * footer_sep = wxT("    ");
1993    int fontsize_footer = fontsize_labels;
1994    wxFont * font_footer;
1995    font_footer = new wxFont(fontsize_footer, wxFONTFAMILY_DEFAULT,
1996                             wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL,
1997                             false, wxString(fontname_labels, wxConvUTF8),
1998                             wxFONTENCODING_UTF8);
1999    font_footer->Scale(font_scaling_x);
2000    SetFont(font_footer);
2001    int w[FOOTERS], ws, h;
2002    pdc->GetTextExtent(footer_sep, &ws, &h);
2003    int wtotal = ws * (FOOTERS - 1);
2004    for (int i = 0; i < FOOTERS; ++i) {
2005        pdc->GetTextExtent(footer[i], &w[i], &h);
2006        wtotal += w[i];
2007    }
2008
2009    long X = x_offset;
2010    long Y = y_offset + ypPageDepth + (long)(7 * m_layout->scY) - pdc->GetCharHeight();
2011
2012    if (wtotal > xpPageWidth) {
2013        // Rescale the footer so it fits.
2014        double rescale = double(wtotal) / xpPageWidth;
2015        double xsc, ysc;
2016        pdc->GetUserScale(&xsc, &ysc);
2017        pdc->SetUserScale(xsc / rescale, ysc / rescale);
2018        SetFont(font_footer);
2019        wxString fullfooter = footer[0];
2020        for (int i = 1; i < FOOTERS - 1; ++i) {
2021            fullfooter += footer_sep;
2022            fullfooter += footer[i];
2023        }
2024        pdc->DrawText(fullfooter, X * rescale, Y * rescale);
2025        // Draw final item right aligned to avoid misaligning.
2026        wxRect rect(x_offset * rescale, Y * rescale,
2027                    xpPageWidth * rescale, pdc->GetCharHeight() * rescale);
2028        pdc->DrawLabel(footer[FOOTERS - 1], rect, wxALIGN_RIGHT|wxALIGN_TOP);
2029        pdc->SetUserScale(xsc, ysc);
2030    } else {
2031        // Space out the elements of the footer to fill the line.
2032        double extra = double(xpPageWidth - wtotal) / (FOOTERS - 1);
2033        for (int i = 0; i < FOOTERS - 1; ++i) {
2034            pdc->DrawText(footer[i], X + extra * i, Y);
2035            X += ws + w[i];
2036        }
2037        // Draw final item right aligned to avoid misaligning.
2038        wxRect rect(x_offset, Y, xpPageWidth, pdc->GetCharHeight());
2039        pdc->DrawLabel(footer[FOOTERS - 1], rect, wxALIGN_RIGHT|wxALIGN_TOP);
2040    }
2041    drawticks((int)(9 * m_layout->scX / POINTS_PER_MM), x, y);
2042}
2043
2044void
2045svxPrintout::PlotLR(const vector<XSect> & centreline)
2046{
2047    const SurveyFilter* filter = mainfrm->GetTreeFilter();
2048    assert(centreline.size() > 1);
2049    const XSect* prev_pt_v = NULL;
2050    Vector3 last_right(1.0, 0.0, 0.0);
2051
2052    const double Sc = 1000 / m_layout->Scale;
2053    const double SIN = sin(rad(m_layout->rot));
2054    const double COS = cos(rad(m_layout->rot));
2055
2056    vector<XSect>::const_iterator i = centreline.begin();
2057    vector<XSect>::size_type segment = 0;
2058    while (i != centreline.end()) {
2059        // get the coordinates of this vertex
2060        const XSect & pt_v = *i++;
2061
2062        Vector3 right;
2063
2064        const Vector3 up_v(0.0, 0.0, 1.0);
2065
2066        if (segment == 0) {
2067            assert(i != centreline.end());
2068            // first segment
2069
2070            // get the coordinates of the next vertex
2071            const XSect & next_pt_v = *i;
2072
2073            // calculate vector from this pt to the next one
2074            Vector3 leg_v = next_pt_v - pt_v;
2075
2076            // obtain a vector in the LRUD plane
2077            right = leg_v * up_v;
2078            if (right.magnitude() == 0) {
2079                right = last_right;
2080            } else {
2081                last_right = right;
2082            }
2083        } else if (segment + 1 == centreline.size()) {
2084            // last segment
2085
2086            // Calculate vector from the previous pt to this one.
2087            Vector3 leg_v = pt_v - *prev_pt_v;
2088
2089            // Obtain a horizontal vector in the LRUD plane.
2090            right = leg_v * up_v;
2091            if (right.magnitude() == 0) {
2092                right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
2093            } else {
2094                last_right = right;
2095            }
2096        } else {
2097            assert(i != centreline.end());
2098            // Intermediate segment.
2099
2100            // Get the coordinates of the next vertex.
2101            const XSect & next_pt_v = *i;
2102
2103            // Calculate vectors from this vertex to the
2104            // next vertex, and from the previous vertex to
2105            // this one.
2106            Vector3 leg1_v = pt_v - *prev_pt_v;
2107            Vector3 leg2_v = next_pt_v - pt_v;
2108
2109            // Obtain horizontal vectors perpendicular to
2110            // both legs, then normalise and average to get
2111            // a horizontal bisector.
2112            Vector3 r1 = leg1_v * up_v;
2113            Vector3 r2 = leg2_v * up_v;
2114            r1.normalise();
2115            r2.normalise();
2116            right = r1 + r2;
2117            if (right.magnitude() == 0) {
2118                // This is the "mid-pitch" case...
2119                right = last_right;
2120            }
2121            last_right = right;
2122        }
2123
2124        // Scale to unit vectors in the LRUD plane.
2125        right.normalise();
2126
2127        double l = pt_v.GetL();
2128        double r = pt_v.GetR();
2129
2130        if (l >= 0 || r >= 0) {
2131            if (!filter || filter->CheckVisible(pt_v.GetLabel())) {
2132                // Get the x and y coordinates of the survey station
2133                double pt_X = pt_v.GetX() * COS - pt_v.GetY() * SIN;
2134                double pt_Y = pt_v.GetX() * SIN + pt_v.GetY() * COS;
2135                long pt_x = (long)((pt_X * Sc + m_layout->xOrg) * m_layout->scX);
2136                long pt_y = (long)((pt_Y * Sc + m_layout->yOrg) * m_layout->scY);
2137
2138                // Calculate dimensions for the right arrow
2139                double COSR = right.GetX();
2140                double SINR = right.GetY();
2141                long CROSS_MAJOR = (COSR + SINR) * PWX_CROSS_SIZE;
2142                long CROSS_MINOR = (COSR - SINR) * PWX_CROSS_SIZE;
2143
2144                if (l >= 0) {
2145                    // Get the x and y coordinates of the end of the left arrow
2146                    Vector3 p = pt_v.GetPoint() - right * l;
2147                    double X = p.GetX() * COS - p.GetY() * SIN;
2148                    double Y = (p.GetX() * SIN + p.GetY() * COS);
2149                    long x = (long)((X * Sc + m_layout->xOrg) * m_layout->scX);
2150                    long y = (long)((Y * Sc + m_layout->yOrg) * m_layout->scY);
2151
2152                    // Draw the arrow stem
2153                    MoveTo(pt_x, pt_y);
2154                    DrawTo(x, y);
2155
2156                    // Rotate the arrow by the page rotation
2157                    long dx1 = (+CROSS_MINOR) * COS - (+CROSS_MAJOR) * SIN;
2158                    long dy1 = (+CROSS_MINOR) * SIN + (+CROSS_MAJOR) * COS;
2159                    long dx2 = (+CROSS_MAJOR) * COS - (-CROSS_MINOR) * SIN;
2160                    long dy2 = (+CROSS_MAJOR) * SIN + (-CROSS_MINOR) * COS;
2161
2162                    // Draw the arrow
2163                    MoveTo(x + dx1, y + dy1);
2164                    DrawTo(x, y);
2165                    DrawTo(x + dx2, y + dy2);
2166                }
2167
2168                if (r >= 0) {
2169                    // Get the x and y coordinates of the end of the right arrow
2170                    Vector3 p = pt_v.GetPoint() + right * r;
2171                    double X = p.GetX() * COS - p.GetY() * SIN;
2172                    double Y = (p.GetX() * SIN + p.GetY() * COS);
2173                    long x = (long)((X * Sc + m_layout->xOrg) * m_layout->scX);
2174                    long y = (long)((Y * Sc + m_layout->yOrg) * m_layout->scY);
2175
2176                    // Draw the arrow stem
2177                    MoveTo(pt_x, pt_y);
2178                    DrawTo(x, y);
2179
2180                    // Rotate the arrow by the page rotation
2181                    long dx1 = (-CROSS_MINOR) * COS - (-CROSS_MAJOR) * SIN;
2182                    long dy1 = (-CROSS_MINOR) * SIN + (-CROSS_MAJOR) * COS;
2183                    long dx2 = (-CROSS_MAJOR) * COS - (+CROSS_MINOR) * SIN;
2184                    long dy2 = (-CROSS_MAJOR) * SIN + (+CROSS_MINOR) * COS;
2185
2186                    // Draw the arrow
2187                    MoveTo(x + dx1, y + dy1);
2188                    DrawTo(x, y);
2189                    DrawTo(x + dx2, y + dy2);
2190                }
2191            }
2192        }
2193
2194        prev_pt_v = &pt_v;
2195
2196        ++segment;
2197    }
2198}
2199
2200void
2201svxPrintout::PlotUD(const vector<XSect> & centreline)
2202{
2203    const SurveyFilter* filter = mainfrm->GetTreeFilter();
2204    assert(centreline.size() > 1);
2205    const double Sc = 1000 / m_layout->Scale;
2206
2207    vector<XSect>::const_iterator i = centreline.begin();
2208    while (i != centreline.end()) {
2209        // get the coordinates of this vertex
2210        const XSect & pt_v = *i++;
2211
2212        double u = pt_v.GetU();
2213        double d = pt_v.GetD();
2214
2215        if (u >= 0 || d >= 0) {
2216            if (filter && !filter->CheckVisible(pt_v.GetLabel()))
2217                continue;
2218
2219            // Get the coordinates of the survey point
2220            Vector3 p = pt_v.GetPoint();
2221            double SIN = sin(rad(m_layout->rot));
2222            double COS = cos(rad(m_layout->rot));
2223            double X = p.GetX() * COS - p.GetY() * SIN;
2224            double Y = p.GetZ();
2225            long x = (long)((X * Sc + m_layout->xOrg) * m_layout->scX);
2226            long pt_y = (long)((Y * Sc + m_layout->yOrg) * m_layout->scX);
2227
2228            if (u >= 0) {
2229                // Get the y coordinate of the up arrow
2230                long y = (long)(((Y + u) * Sc + m_layout->yOrg) * m_layout->scY);
2231
2232                // Draw the arrow stem
2233                MoveTo(x, pt_y);
2234                DrawTo(x, y);
2235
2236                // Draw the up arrow
2237                MoveTo(x - PWX_CROSS_SIZE, y - PWX_CROSS_SIZE);
2238                DrawTo(x, y);
2239                DrawTo(x + PWX_CROSS_SIZE, y - PWX_CROSS_SIZE);
2240            }
2241
2242            if (d >= 0) {
2243                // Get the y coordinate of the down arrow
2244                long y = (long)(((Y - d) * Sc + m_layout->yOrg) * m_layout->scY);
2245
2246                // Draw the arrow stem
2247                MoveTo(x, pt_y);
2248                DrawTo(x, y);
2249
2250                // Draw the down arrow
2251                MoveTo(x - PWX_CROSS_SIZE, y + PWX_CROSS_SIZE);
2252                DrawTo(x, y);
2253                DrawTo(x + PWX_CROSS_SIZE, y + PWX_CROSS_SIZE);
2254            }
2255        }
2256    }
2257}
Note: See TracBrowser for help on using the repository browser.