source: git/src/printing.cc @ 9fcc81a

RELEASE/1.2debug-cidebug-ci-sanitiserswalls-data
Last change on this file since 9fcc81a was 13bfd7b, checked in by Olly Betts <olly@…>, 5 years ago

Fix typo in UI (CVS should be CSV)

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