source: git/src/printing.cc @ 4e7fb5e

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

Support scaling for HPGL export

Previous the export was always at 1:40000.

  • Property mode set to 100644
File size: 67.7 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, *font_default;
174    // Currently unused, but "skip blank pages" would use it.
175    bool scan_for_blank_pages;
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};
290
291static_assert(sizeof(formats) == FMT_MAX_PLUS_ONE_ * sizeof(formats[0]),
292              "formats[] matches enum export_format");
293
294// We discriminate as "One page" isn't valid for exporting.
295static wxString default_scale_print;
296static wxString default_scale_export;
297
298svxPrintDlg::svxPrintDlg(MainFrm* mainfrm_, const wxString & filename,
299                         const wxString & title,
300                         const wxString & datestamp,
301                         double angle, double tilt_angle,
302                         bool labels, bool crosses, bool legs, bool surf,
303                         bool splays, bool tubes, bool ents, bool fixes,
304                         bool exports, bool printing, bool close_after_)
305        : wxDialog(mainfrm_, wxID_ANY,
306                   wxString(printing ? /* TRANSLATORS: Title of the print
307                                        * dialog */
308                                       wmsg(/*Print*/399) :
309                                       /* TRANSLATORS: Title of the export
310                                        * dialog */
311                                       wmsg(/*Export*/383))),
312          m_layout(printing ? wxGetApp().GetPageSetupDialogData() : NULL),
313          m_File(filename), mainfrm(mainfrm_), close_after(close_after_)
314{
315    m_scale = NULL;
316    m_printSize = NULL;
317    m_bearing = NULL;
318    m_tilt = NULL;
319    m_format = NULL;
320    int show_mask = 0;
321    if (labels)
322        show_mask |= LABELS;
323    if (crosses)
324        show_mask |= STNS;
325    if (legs)
326        show_mask |= LEGS;
327    if (surf)
328        show_mask |= SURF;
329    if (splays)
330        show_mask |= SPLAYS;
331    if (tubes)
332        show_mask |= XSECT|WALLS|PASG;
333    if (ents)
334        show_mask |= ENTS;
335    if (fixes)
336        show_mask |= FIXES;
337    if (exports)
338        show_mask |= EXPORTS;
339    m_layout.show_mask = show_mask;
340    m_layout.datestamp = datestamp;
341    m_layout.rot = angle;
342    m_layout.title = title;
343    if (mainfrm->IsExtendedElevation()) {
344        m_layout.view = layout::EXTELEV;
345        if (m_layout.rot != 0.0 && m_layout.rot != 180.0) m_layout.rot = 0;
346        m_layout.tilt = 0;
347    } else {
348        m_layout.tilt = tilt_angle;
349        if (m_layout.tilt == -90.0) {
350            m_layout.view = layout::PLAN;
351        } else if (m_layout.tilt == 0.0) {
352            m_layout.view = layout::ELEV;
353        } else {
354            m_layout.view = layout::TILT;
355        }
356    }
357
358    /* setup our print dialog*/
359    wxBoxSizer* v1 = new wxBoxSizer(wxVERTICAL);
360    wxBoxSizer* h1 = new wxBoxSizer(wxHORIZONTAL); // holds controls
361    /* TRANSLATORS: Used as a label for the surrounding box for the "Bearing"
362     * and "Tilt angle" fields, and the "Plan view" and "Elevation" buttons in
363     * the "what to print/export" dialog. */
364    m_viewbox = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, wmsg(/*View*/283)), wxVERTICAL);
365    /* TRANSLATORS: Used as a label for the surrounding box for the "survey
366     * legs" "stations" "names" etc checkboxes in the "what to print" dialog.
367     * "Elements" isn’t a good name for this but nothing better has yet come to
368     * mind! */
369    wxBoxSizer* v2 = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, wmsg(/*Elements*/256)), wxVERTICAL);
370    wxBoxSizer* h2 = new wxBoxSizer(wxHORIZONTAL); // holds buttons
371
372    if (!printing) {
373        wxStaticText* label;
374        label = new wxStaticText(this, wxID_ANY, wxString(wmsg(/*Export format*/410)));
375        const size_t n_formats = sizeof(formats) / sizeof(formats[0]);
376        m_format = new wxChoice(this, svx_FORMAT,
377                                wxDefaultPosition, wxDefaultSize,
378                                n_formats, formats);
379        unsigned current_format = 0;
380        wxConfigBase * cfg = wxConfigBase::Get();
381        wxString s;
382        if (cfg->Read(wxT("export_format"), &s, wxString())) {
383            for (unsigned i = 0; i != n_formats; ++i) {
384                if (s == formats[i]) {
385                    current_format = i;
386                    break;
387                }
388            }
389        }
390        m_format->SetSelection(current_format);
391        wxBoxSizer* formatbox = new wxBoxSizer(wxHORIZONTAL);
392        formatbox->Add(label, 0, wxALIGN_CENTRE_VERTICAL|wxALL, 5);
393        formatbox->Add(m_format, 0, wxALIGN_CENTRE_VERTICAL|wxALL, 5);
394
395        v1->Add(formatbox, 0, wxALIGN_LEFT|wxALL, 0);
396    }
397
398    if (scales[SCALES_INDEX_MM_TO_FEET][0] == '\0') {
399        scales[SCALES_INDEX_MM_TO_FEET] = wxString::FromDouble(304.8) + wxT(" (1mm:1ft)");
400    }
401    wxStaticText* label;
402    label = new wxStaticText(this, wxID_ANY, wxString(wmsg(/*Scale*/154)) + wxT(" 1:"));
403    if (printing && scales[0].empty()) {
404        /* TRANSLATORS: used in the scale drop down selector in the print
405         * dialog the implicit meaning is "choose a suitable scale to fit
406         * the plot on a single page", but we need something shorter */
407        scales[0].assign(wmsg(/*One page*/258));
408    }
409    wxString default_scale;
410    if (printing) {
411        default_scale = default_scale_print;
412        if (default_scale.empty()) default_scale = scales[0];
413    } else {
414        default_scale = default_scale_export;
415        if (default_scale.empty()) default_scale = wxT("1000");
416    }
417    const wxString* scale_list = scales;
418    size_t n_scales = sizeof(scales) / sizeof(scales[0]);
419    if (!printing) {
420        ++scale_list;
421        --n_scales;
422    }
423    m_scale = new wxComboBox(this, svx_SCALE, default_scale, wxDefaultPosition,
424                             wxDefaultSize, n_scales, scale_list);
425    m_scalebox = new wxBoxSizer(wxHORIZONTAL);
426    m_scalebox->Add(label, 0, wxALIGN_CENTRE_VERTICAL|wxALL, 5);
427    m_scalebox->Add(m_scale, 0, wxALIGN_CENTRE_VERTICAL|wxALL, 5);
428
429    m_viewbox->Add(m_scalebox, 0, wxALIGN_LEFT|wxALL, 0);
430
431    if (printing) {
432        // Make the dummy string wider than any sane value and use that to
433        // fix the width of the control so the sizers allow space for bigger
434        // page layouts.
435        m_printSize = new wxStaticText(this, wxID_ANY, wxString::Format(wmsg(/*%d pages (%dx%d)*/257), 9604, 98, 98));
436        m_viewbox->Add(m_printSize, 0, wxALIGN_LEFT|wxALL, 5);
437    }
438
439    if (m_layout.view != layout::EXTELEV) {
440        wxFlexGridSizer* anglebox = new wxFlexGridSizer(2);
441        wxStaticText * brg_label, * tilt_label;
442        brg_label = new wxStaticText(this, wxID_ANY, wmsg(/*Bearing*/259));
443        anglebox->Add(brg_label, 0, wxALIGN_CENTRE_VERTICAL|wxALIGN_LEFT|wxALL, 5);
444        // wSP_WRAP means that you can scroll past 360 to 0, and vice versa.
445        m_bearing = new wxSpinCtrlDouble(this, svx_BEARING, wxEmptyString,
446                wxDefaultPosition, wxDefaultSize,
447                wxSP_ARROW_KEYS|wxALIGN_RIGHT|wxSP_WRAP);
448        m_bearing->SetRange(0.0, 360.0);
449        m_bearing->SetDigits(ANGLE_DP);
450        anglebox->Add(m_bearing, 0, wxALIGN_CENTRE|wxALL, 5);
451        /* TRANSLATORS: Used in the print dialog: */
452        tilt_label = new wxStaticText(this, wxID_ANY, wmsg(/*Tilt angle*/263));
453        anglebox->Add(tilt_label, 0, wxALIGN_CENTRE_VERTICAL|wxALIGN_LEFT|wxALL, 5);
454        m_tilt = new wxSpinCtrlDouble(this, svx_TILT, wxEmptyString,
455                wxDefaultPosition, wxDefaultSize,
456                wxSP_ARROW_KEYS|wxALIGN_RIGHT);
457        m_tilt->SetRange(-90.0, 90.0);
458        m_tilt->SetDigits(ANGLE_DP);
459        anglebox->Add(m_tilt, 0, wxALIGN_CENTRE|wxALL, 5);
460
461        m_viewbox->Add(anglebox, 0, wxALIGN_LEFT|wxALL, 0);
462
463        wxBoxSizer * planelevsizer = new wxBoxSizer(wxHORIZONTAL);
464        planelevsizer->Add(new wxButton(this, svx_PLAN, wmsg(/*P&lan view*/117)),
465                           0, wxALIGN_CENTRE_VERTICAL|wxALL, 5);
466        planelevsizer->Add(new wxButton(this, svx_ELEV, wmsg(/*&Elevation*/285)),
467                           0, wxALIGN_CENTRE_VERTICAL|wxALL, 5);
468
469        m_viewbox->Add(planelevsizer, 0, wxALIGN_LEFT|wxALL, 5);
470    }
471
472    /* TRANSLATORS: Here a "survey leg" is a set of measurements between two
473     * "survey stations". */
474    v2->Add(new wxCheckBox(this, svx_LEGS, wmsg(/*Underground Survey Legs*/262),
475                           wxDefaultPosition, wxDefaultSize, 0,
476                           BitValidator(&m_layout.show_mask, LEGS)),
477            0, wxALIGN_LEFT|wxALL, 2);
478    /* TRANSLATORS: Here a "survey leg" is a set of measurements between two
479     * "survey stations". */
480    v2->Add(new wxCheckBox(this, svx_SURFACE, wmsg(/*Sur&face Survey Legs*/403),
481                           wxDefaultPosition, wxDefaultSize, 0,
482                           BitValidator(&m_layout.show_mask, SURF)),
483            0, wxALIGN_LEFT|wxALL, 2);
484    v2->Add(new wxCheckBox(this, svx_SPLAYS, wmsg(/*Spla&y Legs*/406),
485                           wxDefaultPosition, wxDefaultSize, 0,
486                           BitValidator(&m_layout.show_mask, SPLAYS)),
487            0, wxALIGN_LEFT|wxALL, 2);
488    v2->Add(new wxCheckBox(this, svx_STATIONS, wmsg(/*Crosses*/261),
489                           wxDefaultPosition, wxDefaultSize, 0,
490                           BitValidator(&m_layout.show_mask, STNS)),
491            0, wxALIGN_LEFT|wxALL, 2);
492    v2->Add(new wxCheckBox(this, svx_NAMES, wmsg(/*Station Names*/260),
493                           wxDefaultPosition, wxDefaultSize, 0,
494                           BitValidator(&m_layout.show_mask, LABELS)),
495            0, wxALIGN_LEFT|wxALL, 2);
496    v2->Add(new wxCheckBox(this, svx_ENTS, wmsg(/*Entrances*/418),
497                           wxDefaultPosition, wxDefaultSize, 0,
498                           BitValidator(&m_layout.show_mask, ENTS)),
499            0, wxALIGN_LEFT|wxALL, 2);
500    v2->Add(new wxCheckBox(this, svx_FIXES, wmsg(/*Fixed Points*/419),
501                           wxDefaultPosition, wxDefaultSize, 0,
502                           BitValidator(&m_layout.show_mask, FIXES)),
503            0, wxALIGN_LEFT|wxALL, 2);
504    v2->Add(new wxCheckBox(this, svx_EXPORTS, wmsg(/*Exported Stations*/420),
505                           wxDefaultPosition, wxDefaultSize, 0,
506                           BitValidator(&m_layout.show_mask, EXPORTS)),
507            0, wxALIGN_LEFT|wxALL, 2);
508    v2->Add(new wxCheckBox(this, svx_XSECT, wmsg(/*Cross-sections*/393),
509                           wxDefaultPosition, wxDefaultSize, 0,
510                           BitValidator(&m_layout.show_mask, XSECT)),
511            0, wxALIGN_LEFT|wxALL, 2);
512    if (!printing) {
513        v2->Add(new wxCheckBox(this, svx_WALLS, wmsg(/*Walls*/394),
514                               wxDefaultPosition, wxDefaultSize, 0,
515                               BitValidator(&m_layout.show_mask, WALLS)),
516                0, wxALIGN_LEFT|wxALL, 2);
517        // TRANSLATORS: Label for checkbox which controls whether there's a
518        // layer in the exported file (for formats such as DXF and SVG)
519        // containing polygons for the inside of cave passages).
520        v2->Add(new wxCheckBox(this, svx_PASSAGES, wmsg(/*Passages*/395),
521                               wxDefaultPosition, wxDefaultSize, 0,
522                               BitValidator(&m_layout.show_mask, PASG)),
523                0, wxALIGN_LEFT|wxALL, 2);
524        v2->Add(new wxCheckBox(this, svx_CENTRED, wmsg(/*Origin in centre*/421),
525                               wxDefaultPosition, wxDefaultSize, 0,
526                               BitValidator(&m_layout.show_mask, CENTRED)),
527                0, wxALIGN_LEFT|wxALL, 2);
528        v2->Add(new wxCheckBox(this, svx_FULLCOORDS, wmsg(/*Full coordinates*/422),
529                               wxDefaultPosition, wxDefaultSize, 0,
530                               BitValidator(&m_layout.show_mask, FULL_COORDS)),
531                0, wxALIGN_LEFT|wxALL, 2);
532        v2->Add(new wxCheckBox(this, svx_CLAMP_TO_GROUND, wmsg(/*Clamp to ground*/477),
533                               wxDefaultPosition, wxDefaultSize, 0,
534                               BitValidator(&m_layout.show_mask, CLAMP_TO_GROUND)),
535                0, wxALIGN_LEFT|wxALL, 2);
536    }
537    if (printing) {
538        /* TRANSLATORS: used in the print dialog - controls drawing lines
539         * around each page */
540        v2->Add(new wxCheckBox(this, svx_BORDERS, wmsg(/*Page Borders*/264),
541                               wxDefaultPosition, wxDefaultSize, 0,
542                               wxGenericValidator(&m_layout.Border)),
543                0, wxALIGN_LEFT|wxALL, 2);
544        /* TRANSLATORS: will be used in the print dialog - check this to print
545         * blank pages (otherwise they’ll be skipped to save paper) */
546//      m_blanks = new wxCheckBox(this, svx_BLANKS, wmsg(/*Blank Pages*/266));
547//      v2->Add(m_blanks, 0, wxALIGN_LEFT|wxALL, 2);
548        /* TRANSLATORS: As in the legend on a map.  Used in the print dialog -
549         * controls drawing the box at the lower left with survey name, view
550         * angles, etc */
551        v2->Add(new wxCheckBox(this, svx_LEGEND, wmsg(/*Legend*/265),
552                               wxDefaultPosition, wxDefaultSize, 0,
553                               wxGenericValidator(&m_layout.Legend)),
554                0, wxALIGN_LEFT|wxALL, 2);
555    }
556
557    h1->Add(v2, 0, wxALIGN_LEFT|wxALL, 5);
558    h1->Add(m_viewbox, 0, wxALIGN_LEFT|wxLEFT, 5);
559
560    v1->Add(h1, 0, wxALIGN_LEFT|wxALL, 5);
561
562    // When we enable/disable checkboxes in the export dialog, ideally we'd
563    // like the dialog to resize, but not sure how to achieve that, so we
564    // add a stretchable spacer here so at least the buttons stay in the
565    // lower right corner.
566    v1->AddStretchSpacer();
567
568    wxButton * but;
569    but = new wxButton(this, wxID_CANCEL);
570    h2->Add(but, 0, wxALL, 5);
571    if (printing) {
572#ifdef AVEN_PRINT_PREVIEW
573        but = new wxButton(this, wxID_PREVIEW);
574        h2->Add(but, 0, wxALL, 5);
575        but = new wxButton(this, wxID_PRINT);
576#else
577        but = new wxButton(this, wxID_PRINT, wmsg(/*&Print...*/400));
578#endif
579    } else {
580        /* TRANSLATORS: The text on the action button in the "Export" settings
581         * dialog */
582        but = new wxButton(this, svx_EXPORT, wmsg(/*&Export...*/230));
583    }
584    but->SetDefault();
585    h2->Add(but, 0, wxALL, 5);
586    v1->Add(h2, 0, wxALIGN_RIGHT|wxALL, 5);
587
588    SetAutoLayout(true);
589    SetSizer(v1);
590    v1->SetSizeHints(this);
591
592    LayoutToUI();
593    SomethingChanged(0);
594}
595
596void
597svxPrintDlg::OnPrint(wxCommandEvent&) {
598    SomethingChanged(0);
599    TransferDataFromWindow();
600    wxPageSetupDialogData * psdd = wxGetApp().GetPageSetupDialogData();
601    wxPrintDialogData pd(psdd->GetPrintData());
602    wxPrinter pr(&pd);
603    svxPrintout po(mainfrm, &m_layout, psdd, m_File);
604    if (m_layout.SkipBlank) {
605        // FIXME: wx's printing requires a contiguous range of valid page
606        // numbers.  To achieve that, we need to run a scan for blank pages
607        // here, so that GetPageInfo() knows what range to return, and so
608        // that OnPrintPage() can map a page number back to where in the
609        // MxN multi-page layout.
610#if 0
611        po.scan_for_blank_pages = true;
612        for (int page = 1; page <= m_layout->pages; ++page) {
613            po.fBlankPage = true;
614            po.OnPrintPage(page);
615            // FIXME: Do something with po.fBlankPage
616        }
617        po.scan_for_blank_pages = false;
618#endif
619    }
620    if (pr.Print(this, &po, true)) {
621        // Close the print dialog if printing succeeded.
622        Destroy();
623    }
624}
625
626void
627svxPrintDlg::OnExport(wxCommandEvent&) {
628    UIToLayout();
629    TransferDataFromWindow();
630    wxString leaf;
631    wxFileName::SplitPath(m_File, NULL, NULL, &leaf, NULL, wxPATH_NATIVE);
632    unsigned format_idx = ((wxChoice*)FindWindow(svx_FORMAT))->GetSelection();
633    const auto& info = export_format_info[format_idx];
634    leaf += wxString::FromUTF8(info.extension);
635
636    wxString filespec = wmsg(info.msg_filetype);
637    filespec += wxT("|*");
638    filespec += wxString::FromUTF8(info.extension);
639    filespec += wxT("|");
640    filespec += wmsg(/*All files*/208);
641    filespec += wxT("|");
642    filespec += wxFileSelectorDefaultWildcardStr;
643
644    /* TRANSLATORS: Title of file dialog to choose name and type of exported
645     * file. */
646    wxFileDialog dlg(this, wmsg(/*Export as:*/401), wxString(), leaf,
647                     filespec, wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
648    if (dlg.ShowModal() == wxID_OK) {
649        /* FIXME: Set up a way for the user to specify these: */
650        double grid = DEFAULT_GRID_SPACING; // metres
651        double text_height = DEFAULT_TEXT_HEIGHT;
652        double marker_size = DEFAULT_MARKER_SIZE;
653
654        try {
655            const wxString& export_fnm = dlg.GetPath();
656            unsigned mask = info.mask;
657            double rot, tilt;
658            if (mask & ORIENTABLE) {
659                rot = m_layout.rot;
660                tilt = m_layout.tilt;
661            } else {
662                rot = 0.0;
663                tilt = -90.0;
664            }
665            if (!Export(export_fnm, m_layout.title,
666                        m_layout.datestamp, *mainfrm, mainfrm->GetTreeFilter(),
667                        rot, tilt, m_layout.get_effective_show_mask(),
668                        export_format(format_idx),
669                        grid, text_height, marker_size, m_layout.Scale)) {
670                wxString m = wxString::Format(wmsg(/*Couldn’t write file “%s”*/402).c_str(),
671                                              export_fnm.c_str());
672                wxGetApp().ReportError(m);
673            }
674        } catch (const wxString & m) {
675            wxGetApp().ReportError(m);
676        }
677    }
678    Destroy();
679}
680
681#ifdef AVEN_PRINT_PREVIEW
682void
683svxPrintDlg::OnPreview(wxCommandEvent&) {
684    SomethingChanged(0);
685    TransferDataFromWindow();
686    wxPageSetupDialogData * psdd = wxGetApp().GetPageSetupDialogData();
687    wxPrintDialogData pd(psdd->GetPrintData());
688    wxPrintPreview* pv;
689    pv = new wxPrintPreview(new svxPrintout(mainfrm, &m_layout, psdd, m_File),
690                            new svxPrintout(mainfrm, &m_layout, psdd, m_File),
691                            &pd);
692    // TRANSLATORS: Title of the print preview dialog
693    wxPreviewFrame *frame = new wxPreviewFrame(pv, mainfrm, wmsg(/*Print Preview*/398));
694    frame->Initialize();
695
696    // Size preview frame so that all of the controlbar and canvas can be seen
697    // if possible.
698    int w, h;
699    // GetBestSize gives us the width needed to show the whole controlbar.
700    frame->GetBestSize(&w, &h);
701    if (h < w) {
702        // On wxGTK at least, GetBestSize() returns much too small a height.
703        h = w * 6 / 5;
704    }
705    // Ensure that we don't make the window bigger than the screen.
706    // Use wxGetClientDisplayRect() so we don't cover the MS Windows
707    // task bar either.
708    wxRect disp = wxGetClientDisplayRect();
709    if (w > disp.GetWidth()) w = disp.GetWidth();
710    if (h > disp.GetHeight()) h = disp.GetHeight();
711    // Centre the window within the "ClientDisplayRect".
712    int x = disp.GetLeft() + (disp.GetWidth() - w) / 2;
713    int y = disp.GetTop() + (disp.GetHeight() - h) / 2;
714    frame->SetSize(x, y, w, h);
715
716    frame->Show();
717}
718#endif
719
720void
721svxPrintDlg::OnPlan(wxCommandEvent&) {
722    m_tilt->SetValue(-90.0);
723    SomethingChanged(svx_TILT);
724}
725
726void
727svxPrintDlg::OnElevation(wxCommandEvent&) {
728    m_tilt->SetValue(0.0);
729    SomethingChanged(svx_TILT);
730}
731
732void
733svxPrintDlg::OnPlanUpdate(wxUpdateUIEvent& e) {
734    e.Enable(m_tilt->GetValue() != -90.0);
735}
736
737void
738svxPrintDlg::OnElevationUpdate(wxUpdateUIEvent& e) {
739    e.Enable(m_tilt->GetValue() != 0.0);
740}
741
742void
743svxPrintDlg::OnChangeSpin(wxSpinDoubleEvent& e) {
744    SomethingChanged(e.GetId());
745}
746
747void
748svxPrintDlg::OnChange(wxCommandEvent& e) {
749    SomethingChanged(e.GetId());
750}
751
752void
753svxPrintDlg::OnChangeScale(wxCommandEvent& e) {
754    // Seems to be needed on macOS.
755    if (!m_scale) return;
756    wxString value = m_scale->GetValue();
757    if (value == "...") {
758        m_scale->SetValue("");
759        m_scale->SetFocus();
760    } else {
761        default_scale_print = value;
762        if (default_scale_print != scales[0]) {
763            // Don't store "One page" for use when exporting.
764            default_scale_export = default_scale_print;
765        }
766    }
767    SomethingChanged(e.GetId());
768}
769
770void
771svxPrintDlg::OnCancel(wxCommandEvent&) {
772    if (close_after)
773        mainfrm->Close();
774    Destroy();
775}
776
777void
778svxPrintDlg::SomethingChanged(int control_id) {
779    if ((control_id == 0 || control_id == svx_FORMAT) && m_format) {
780        // Update the shown/hidden fields for the newly selected export filter.
781        int new_filter_idx = m_format->GetSelection();
782        if (new_filter_idx != wxNOT_FOUND) {
783            unsigned mask = export_format_info[new_filter_idx].mask;
784            static const struct { int id; unsigned mask; } controls[] = {
785                { svx_LEGS, LEGS },
786                { svx_SURFACE, SURF },
787                { svx_SPLAYS, SPLAYS },
788                { svx_STATIONS, STNS },
789                { svx_NAMES, LABELS },
790                { svx_XSECT, XSECT },
791                { svx_WALLS, WALLS },
792                { svx_PASSAGES, PASG },
793                { svx_ENTS, ENTS },
794                { svx_FIXES, FIXES },
795                { svx_EXPORTS, EXPORTS },
796                { svx_CENTRED, CENTRED },
797                { svx_FULLCOORDS, FULL_COORDS },
798                { svx_CLAMP_TO_GROUND, CLAMP_TO_GROUND },
799            };
800            static unsigned n_controls = sizeof(controls) / sizeof(controls[0]);
801            for (unsigned i = 0; i != n_controls; ++i) {
802                wxWindow * control = FindWindow(controls[i].id);
803                if (control) control->Show(mask & controls[i].mask);
804            }
805            m_scalebox->Show(bool(mask & SCALE));
806            m_viewbox->Show(bool(mask & ORIENTABLE));
807            GetSizer()->Layout();
808            // Force the window to resize to match the updated layout.
809            if (control_id) SetSizerAndFit(GetSizer());
810            if (control_id == svx_FORMAT) {
811                wxConfigBase * cfg = wxConfigBase::Get();
812                cfg->Write(wxT("export_format"), formats[new_filter_idx]);
813            }
814        }
815    }
816
817    UIToLayout();
818
819    if (m_printSize || m_scale) {
820        // Update the bounding box.
821        RecalcBounds();
822
823        if (m_scale) {
824            // Remove the comment part (e.g. `(1":20')`).
825            wxString value = m_scale->GetValue();
826            auto comment = value.find('(');
827            if (comment != value.npos) value.resize(comment);
828            // Strip spaces as trailing spaces cause wxWidgets to fail to
829            // parse.
830            value.Replace(" ", "");
831            // Convert `,` to `.` and parse with ToCDouble() so either decimal
832            // separator works regardless of locale settings.
833            value.Replace(",", ".");
834            if (!value.ToCDouble(&(m_layout.Scale)) ||
835                m_layout.Scale == 0.0) {
836                m_layout.pick_scale(1, 1);
837            }
838        }
839    }
840
841    if (m_printSize && m_layout.xMax >= m_layout.xMin) {
842        m_layout.pages_required();
843        m_printSize->SetLabel(wxString::Format(wmsg(/*%d pages (%dx%d)*/257), m_layout.pages, m_layout.pagesX, m_layout.pagesY));
844    }
845}
846
847void
848svxPrintDlg::LayoutToUI()
849{
850//    m_blanks->SetValue(m_layout.SkipBlank);
851    if (m_layout.view != layout::EXTELEV) {
852        m_tilt->SetValue(m_layout.tilt);
853        m_bearing->SetValue(m_layout.rot);
854    }
855
856    if (m_scale && m_layout.Scale != 0) {
857        // Do this last as it causes an OnChange message which calls UIToLayout
858        wxString temp;
859        temp << m_layout.Scale;
860        m_scale->SetValue(temp);
861    }
862}
863
864void
865svxPrintDlg::UIToLayout()
866{
867//    m_layout.SkipBlank = m_blanks->IsChecked();
868
869    if (m_layout.view != layout::EXTELEV && m_tilt) {
870        m_layout.tilt = m_tilt->GetValue();
871        if (m_layout.tilt == -90.0) {
872            m_layout.view = layout::PLAN;
873        } else if (m_layout.tilt == 0.0) {
874            m_layout.view = layout::ELEV;
875        } else {
876            m_layout.view = layout::TILT;
877        }
878
879        bool enable_passage_opts = (m_layout.view != layout::TILT);
880        wxWindow * win;
881        win = FindWindow(svx_XSECT);
882        if (win) win->Enable(enable_passage_opts);
883        win = FindWindow(svx_WALLS);
884        if (win) win->Enable(enable_passage_opts);
885        win = FindWindow(svx_PASSAGES);
886        if (win) win->Enable(enable_passage_opts);
887
888        m_layout.rot = m_bearing->GetValue();
889    }
890}
891
892void
893svxPrintDlg::RecalcBounds()
894{
895    m_layout.yMax = m_layout.xMax = -DBL_MAX;
896    m_layout.yMin = m_layout.xMin = DBL_MAX;
897
898    double SIN = sin(rad(m_layout.rot));
899    double COS = cos(rad(m_layout.rot));
900    double SINT = sin(rad(m_layout.tilt));
901    double COST = cos(rad(m_layout.tilt));
902
903    const SurveyFilter* filter = mainfrm->GetTreeFilter();
904    int show_mask = m_layout.get_effective_show_mask();
905    if (show_mask & LEGS) {
906        for (int f = 0; f != 8; ++f) {
907            if ((show_mask & (f & img_FLAG_SURFACE) ? SURF : LEGS) == 0) {
908                // Not showing traverse because of surface/underground status.
909                continue;
910            }
911            if ((f & img_FLAG_SPLAY) && (show_mask & SPLAYS) == 0) {
912                // Not showing because it's a splay.
913                continue;
914            }
915            list<traverse>::const_iterator trav = mainfrm->traverses_begin(f, filter);
916            list<traverse>::const_iterator tend = mainfrm->traverses_end(f);
917            for ( ; trav != tend; trav = mainfrm->traverses_next(f, filter, trav)) {
918                vector<PointInfo>::const_iterator pos = trav->begin();
919                vector<PointInfo>::const_iterator end = trav->end();
920                for ( ; pos != end; ++pos) {
921                    double x = pos->GetX();
922                    double y = pos->GetY();
923                    double z = pos->GetZ();
924                    double X = x * COS - y * SIN;
925                    if (X > m_layout.xMax) m_layout.xMax = X;
926                    if (X < m_layout.xMin) m_layout.xMin = X;
927                    double Y = z * COST - (x * SIN + y * COS) * SINT;
928                    if (Y > m_layout.yMax) m_layout.yMax = Y;
929                    if (Y < m_layout.yMin) m_layout.yMin = Y;
930                }
931            }
932        }
933    }
934
935    if ((show_mask & XSECT) &&
936        (m_layout.tilt == 0.0 || m_layout.tilt == 90.0 || m_layout.tilt == -90.0)) {
937        list<vector<XSect>>::const_iterator trav = mainfrm->tubes_begin();
938        list<vector<XSect>>::const_iterator tend = mainfrm->tubes_end();
939        for ( ; trav != tend; ++trav) {
940            const XSect* prev_pt_v = NULL;
941            Vector3 last_right(1.0, 0.0, 0.0);
942
943            vector<XSect>::const_iterator i = trav->begin();
944            vector<XSect>::size_type segment = 0;
945            while (i != trav->end()) {
946                // get the coordinates of this vertex
947                const XSect & pt_v = *i++;
948                if (m_layout.tilt == 0.0) {
949                    double u = pt_v.GetU();
950                    double d = pt_v.GetD();
951
952                    if (u >= 0 || d >= 0) {
953                        if (filter && !filter->CheckVisible(pt_v.GetLabel()))
954                            continue;
955
956                        double x = pt_v.GetX();
957                        double y = pt_v.GetY();
958                        double z = pt_v.GetZ();
959                        double X = x * COS - y * SIN;
960                        double Y = z * COST - (x * SIN + y * COS) * SINT;
961
962                        if (X > m_layout.xMax) m_layout.xMax = X;
963                        if (X < m_layout.xMin) m_layout.xMin = X;
964                        double U = Y + max(0.0, pt_v.GetU());
965                        if (U > m_layout.yMax) m_layout.yMax = U;
966                        double D = Y - max(0.0, pt_v.GetD());
967                        if (D < m_layout.yMin) m_layout.yMin = D;
968                    }
969                } else {
970                    // More complex, and this duplicates the algorithm from
971                    // PlotLR() - we should try to share that, maybe via a
972                    // template.
973                    Vector3 right;
974
975                    const Vector3 up_v(0.0, 0.0, 1.0);
976
977                    if (segment == 0) {
978                        assert(i != trav->end());
979                        // first segment
980
981                        // get the coordinates of the next vertex
982                        const XSect & next_pt_v = *i;
983
984                        // calculate vector from this pt to the next one
985                        Vector3 leg_v = next_pt_v - pt_v;
986
987                        // obtain a vector in the LRUD plane
988                        right = leg_v * up_v;
989                        if (right.magnitude() == 0) {
990                            right = last_right;
991                        } else {
992                            last_right = right;
993                        }
994                    } else if (segment + 1 == trav->size()) {
995                        // last segment
996
997                        // Calculate vector from the previous pt to this one.
998                        Vector3 leg_v = pt_v - *prev_pt_v;
999
1000                        // Obtain a horizontal vector in the LRUD plane.
1001                        right = leg_v * up_v;
1002                        if (right.magnitude() == 0) {
1003                            right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
1004                        } else {
1005                            last_right = right;
1006                        }
1007                    } else {
1008                        assert(i != trav->end());
1009                        // Intermediate segment.
1010
1011                        // Get the coordinates of the next vertex.
1012                        const XSect & next_pt_v = *i;
1013
1014                        // Calculate vectors from this vertex to the
1015                        // next vertex, and from the previous vertex to
1016                        // this one.
1017                        Vector3 leg1_v = pt_v - *prev_pt_v;
1018                        Vector3 leg2_v = next_pt_v - pt_v;
1019
1020                        // Obtain horizontal vectors perpendicular to
1021                        // both legs, then normalise and average to get
1022                        // a horizontal bisector.
1023                        Vector3 r1 = leg1_v * up_v;
1024                        Vector3 r2 = leg2_v * up_v;
1025                        r1.normalise();
1026                        r2.normalise();
1027                        right = r1 + r2;
1028                        if (right.magnitude() == 0) {
1029                            // This is the "mid-pitch" case...
1030                            right = last_right;
1031                        }
1032                        last_right = right;
1033                    }
1034
1035                    // Scale to unit vectors in the LRUD plane.
1036                    right.normalise();
1037
1038                    double l = pt_v.GetL();
1039                    double r = pt_v.GetR();
1040
1041                    if (l >= 0 || r >= 0) {
1042                        if (!filter || filter->CheckVisible(pt_v.GetLabel())) {
1043                            // Get the x and y coordinates of the survey station
1044                            double pt_X = pt_v.GetX() * COS - pt_v.GetY() * SIN;
1045                            double pt_Y = pt_v.GetX() * SIN + pt_v.GetY() * COS;
1046
1047                            double X, Y;
1048                            if (l >= 0) {
1049                                // Get the x and y coordinates of the end of the left arrow
1050                                Vector3 p = pt_v.GetPoint() - right * l;
1051                                X = p.GetX() * COS - p.GetY() * SIN;
1052                                Y = (p.GetX() * SIN + p.GetY() * COS);
1053                            } else {
1054                                X = pt_X;
1055                                Y = pt_Y;
1056                            }
1057                            if (X > m_layout.xMax) m_layout.xMax = X;
1058                            if (X < m_layout.xMin) m_layout.xMin = X;
1059                            if (Y > m_layout.yMax) m_layout.yMax = Y;
1060                            if (Y < m_layout.yMin) m_layout.yMin = Y;
1061
1062                            if (r >= 0) {
1063                                // Get the x and y coordinates of the end of the right arrow
1064                                Vector3 p = pt_v.GetPoint() + right * r;
1065                                X = p.GetX() * COS - p.GetY() * SIN;
1066                                Y = (p.GetX() * SIN + p.GetY() * COS);
1067                            } else {
1068                                X = pt_X;
1069                                Y = pt_Y;
1070                            }
1071                            if (X > m_layout.xMax) m_layout.xMax = X;
1072                            if (X < m_layout.xMin) m_layout.xMin = X;
1073                            if (Y > m_layout.yMax) m_layout.yMax = Y;
1074                            if (Y < m_layout.yMin) m_layout.yMin = Y;
1075                        }
1076                    }
1077
1078                    prev_pt_v = &pt_v;
1079
1080                    ++segment;
1081                }
1082            }
1083        }
1084    }
1085
1086    if (show_mask & (LABELS|STNS)) {
1087        for (auto label = mainfrm->GetLabels();
1088             label != mainfrm->GetLabelsEnd();
1089             ++label) {
1090            if (filter && !filter->CheckVisible((*label)->GetText()))
1091                continue;
1092            double x = (*label)->GetX();
1093            double y = (*label)->GetY();
1094            double z = (*label)->GetZ();
1095            if ((show_mask & SURF) || (*label)->IsUnderground()) {
1096                double X = x * COS - y * SIN;
1097                if (X > m_layout.xMax) m_layout.xMax = X;
1098                if (X < m_layout.xMin) m_layout.xMin = X;
1099                double Y = z * COST - (x * SIN + y * COS) * SINT;
1100                if (Y > m_layout.yMax) m_layout.yMax = Y;
1101                if (Y < m_layout.yMin) m_layout.yMin = Y;
1102            }
1103        }
1104    }
1105}
1106
1107static int xpPageWidth, ypPageDepth;
1108static long x_offset, y_offset;
1109static int fontsize, fontsize_labels;
1110
1111/* FIXME: allow the font to be set */
1112
1113static const char *fontname = "Arial", *fontname_labels = "Arial";
1114
1115svxPrintout::svxPrintout(MainFrm *mainfrm_, layout *l,
1116                         wxPageSetupDialogData *data, const wxString & title)
1117    : wxPrintout(title), font_labels(NULL), font_default(NULL),
1118      scan_for_blank_pages(false)
1119{
1120    mainfrm = mainfrm_;
1121    m_layout = l;
1122    m_data = data;
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.