source: git/src/printing.cc @ 04078a7

faster-cavernloglog-selectwalls-datawalls-data-hanging-as-warning
Last change on this file since 04078a7 was 63d4f07, checked in by Olly Betts <olly@…>, 3 months ago

Use stdbool.h

We've required C99 since 1.4.2.

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