source: git/src/printing.cc @ 269106c

debug-cidebug-ci-sanitisersfaster-cavernloglog-selectstereo-2025walls-datawalls-data-hanging-as-warningwarn-only-for-hanging-survey
Last change on this file since 269106c was 23a2fe9, checked in by Olly Betts <olly@…>, 2 years ago

Make it obvious you can enter a custom scale

Add a "..." entry to scale combobox - selecting this clears the
value and gives focus to the combo box text entry.

This control has always supported clicking to enter a custom scale, but
there wasn't really any indication that this was possible before.

Partly addresses #132, reported by Eric C. Landgraf.

  • Property mode set to 100644
File size: 66.8 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 = fTrue;
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    wxString value = m_scale->GetValue();
746    if (value == "...") {
747        m_scale->SetValue("");
748        m_scale->SetFocus();
749    } else {
750        default_scale_print = value;
751        if (default_scale_print != scales[0]) {
752            // Don't store "One page" for use when exporting.
753            default_scale_export = default_scale_print;
754        }
755    }
756    SomethingChanged(e.GetId());
757}
758
759void
760svxPrintDlg::OnCancel(wxCommandEvent&) {
761    if (close_after)
762        mainfrm->Close();
763    Destroy();
764}
765
766void
767svxPrintDlg::SomethingChanged(int control_id) {
768    if ((control_id == 0 || control_id == svx_FORMAT) && m_format) {
769        // Update the shown/hidden fields for the newly selected export filter.
770        int new_filter_idx = m_format->GetSelection();
771        if (new_filter_idx != wxNOT_FOUND) {
772            unsigned mask = export_format_info[new_filter_idx].mask;
773            static const struct { int id; unsigned mask; } controls[] = {
774                { svx_LEGS, LEGS },
775                { svx_SURFACE, SURF },
776                { svx_SPLAYS, SPLAYS },
777                { svx_STATIONS, STNS },
778                { svx_NAMES, LABELS },
779                { svx_XSECT, XSECT },
780                { svx_WALLS, WALLS },
781                { svx_PASSAGES, PASG },
782                { svx_ENTS, ENTS },
783                { svx_FIXES, FIXES },
784                { svx_EXPORTS, EXPORTS },
785                { svx_CENTRED, CENTRED },
786                { svx_FULLCOORDS, FULL_COORDS },
787                { svx_CLAMP_TO_GROUND, CLAMP_TO_GROUND },
788            };
789            static unsigned n_controls = sizeof(controls) / sizeof(controls[0]);
790            for (unsigned i = 0; i != n_controls; ++i) {
791                wxWindow * control = FindWindow(controls[i].id);
792                if (control) control->Show(mask & controls[i].mask);
793            }
794            m_scalebox->Show(bool(mask & SCALE));
795            m_viewbox->Show(bool(mask & ORIENTABLE));
796            GetSizer()->Layout();
797            if (control_id == svx_FORMAT) {
798                wxConfigBase * cfg = wxConfigBase::Get();
799                cfg->Write(wxT("export_format"), formats[new_filter_idx]);
800            }
801        }
802    }
803
804    UIToLayout();
805
806    if (m_printSize || m_scale) {
807        // Update the bounding box.
808        RecalcBounds();
809
810        if (m_scale) {
811            if (!(m_scale->GetValue()).ToDouble(&(m_layout.Scale)) ||
812                m_layout.Scale == 0.0) {
813                m_layout.pick_scale(1, 1);
814            }
815        }
816    }
817
818    if (m_printSize && m_layout.xMax >= m_layout.xMin) {
819        m_layout.pages_required();
820        m_printSize->SetLabel(wxString::Format(wmsg(/*%d pages (%dx%d)*/257), m_layout.pages, m_layout.pagesX, m_layout.pagesY));
821    }
822}
823
824void
825svxPrintDlg::LayoutToUI()
826{
827//    m_blanks->SetValue(m_layout.SkipBlank);
828    if (m_layout.view != layout::EXTELEV) {
829        m_tilt->SetValue(m_layout.tilt);
830        m_bearing->SetValue(m_layout.rot);
831    }
832
833    if (m_scale && m_layout.Scale != 0) {
834        // Do this last as it causes an OnChange message which calls UIToLayout
835        wxString temp;
836        temp << m_layout.Scale;
837        m_scale->SetValue(temp);
838    }
839}
840
841void
842svxPrintDlg::UIToLayout()
843{
844//    m_layout.SkipBlank = m_blanks->IsChecked();
845
846    if (m_layout.view != layout::EXTELEV && m_tilt) {
847        m_layout.tilt = m_tilt->GetValue();
848        if (m_layout.tilt == -90.0) {
849            m_layout.view = layout::PLAN;
850        } else if (m_layout.tilt == 0.0) {
851            m_layout.view = layout::ELEV;
852        } else {
853            m_layout.view = layout::TILT;
854        }
855
856        bool enable_passage_opts = (m_layout.view != layout::TILT);
857        wxWindow * win;
858        win = FindWindow(svx_XSECT);
859        if (win) win->Enable(enable_passage_opts);
860        win = FindWindow(svx_WALLS);
861        if (win) win->Enable(enable_passage_opts);
862        win = FindWindow(svx_PASSAGES);
863        if (win) win->Enable(enable_passage_opts);
864
865        m_layout.rot = m_bearing->GetValue();
866    }
867}
868
869void
870svxPrintDlg::RecalcBounds()
871{
872    m_layout.yMax = m_layout.xMax = -DBL_MAX;
873    m_layout.yMin = m_layout.xMin = DBL_MAX;
874
875    double SIN = sin(rad(m_layout.rot));
876    double COS = cos(rad(m_layout.rot));
877    double SINT = sin(rad(m_layout.tilt));
878    double COST = cos(rad(m_layout.tilt));
879
880    const SurveyFilter* filter = mainfrm->GetTreeFilter();
881    int show_mask = m_layout.get_effective_show_mask();
882    if (show_mask & LEGS) {
883        for (int f = 0; f != 8; ++f) {
884            if ((show_mask & (f & img_FLAG_SURFACE) ? SURF : LEGS) == 0) {
885                // Not showing traverse because of surface/underground status.
886                continue;
887            }
888            if ((f & img_FLAG_SPLAY) && (show_mask & SPLAYS) == 0) {
889                // Not showing because it's a splay.
890                continue;
891            }
892            list<traverse>::const_iterator trav = mainfrm->traverses_begin(f, filter);
893            list<traverse>::const_iterator tend = mainfrm->traverses_end(f);
894            for ( ; trav != tend; trav = mainfrm->traverses_next(f, filter, trav)) {
895                vector<PointInfo>::const_iterator pos = trav->begin();
896                vector<PointInfo>::const_iterator end = trav->end();
897                for ( ; pos != end; ++pos) {
898                    double x = pos->GetX();
899                    double y = pos->GetY();
900                    double z = pos->GetZ();
901                    double X = x * COS - y * SIN;
902                    if (X > m_layout.xMax) m_layout.xMax = X;
903                    if (X < m_layout.xMin) m_layout.xMin = X;
904                    double Y = z * COST - (x * SIN + y * COS) * SINT;
905                    if (Y > m_layout.yMax) m_layout.yMax = Y;
906                    if (Y < m_layout.yMin) m_layout.yMin = Y;
907                }
908            }
909        }
910    }
911
912    if ((show_mask & XSECT) &&
913        (m_layout.tilt == 0.0 || m_layout.tilt == 90.0 || m_layout.tilt == -90.0)) {
914        list<vector<XSect>>::const_iterator trav = mainfrm->tubes_begin();
915        list<vector<XSect>>::const_iterator tend = mainfrm->tubes_end();
916        for ( ; trav != tend; ++trav) {
917            const XSect* prev_pt_v = NULL;
918            Vector3 last_right(1.0, 0.0, 0.0);
919
920            vector<XSect>::const_iterator i = trav->begin();
921            vector<XSect>::size_type segment = 0;
922            while (i != trav->end()) {
923                // get the coordinates of this vertex
924                const XSect & pt_v = *i++;
925                if (m_layout.tilt == 0.0) {
926                    Double u = pt_v.GetU();
927                    Double d = pt_v.GetD();
928
929                    if (u >= 0 || d >= 0) {
930                        if (filter && !filter->CheckVisible(pt_v.GetLabel()))
931                            continue;
932
933                        double x = pt_v.GetX();
934                        double y = pt_v.GetY();
935                        double z = pt_v.GetZ();
936                        double X = x * COS - y * SIN;
937                        double Y = z * COST - (x * SIN + y * COS) * SINT;
938
939                        if (X > m_layout.xMax) m_layout.xMax = X;
940                        if (X < m_layout.xMin) m_layout.xMin = X;
941                        double U = Y + max(0.0, pt_v.GetU());
942                        if (U > m_layout.yMax) m_layout.yMax = U;
943                        double D = Y - max(0.0, pt_v.GetD());
944                        if (D < m_layout.yMin) m_layout.yMin = D;
945                    }
946                } else {
947                    // More complex, and this duplicates the algorithm from
948                    // PlotLR() - we should try to share that, maybe via a
949                    // template.
950                    Vector3 right;
951
952                    const Vector3 up_v(0.0, 0.0, 1.0);
953
954                    if (segment == 0) {
955                        assert(i != trav->end());
956                        // first segment
957
958                        // get the coordinates of the next vertex
959                        const XSect & next_pt_v = *i;
960
961                        // calculate vector from this pt to the next one
962                        Vector3 leg_v = next_pt_v - pt_v;
963
964                        // obtain a vector in the LRUD plane
965                        right = leg_v * up_v;
966                        if (right.magnitude() == 0) {
967                            right = last_right;
968                        } else {
969                            last_right = right;
970                        }
971                    } else if (segment + 1 == trav->size()) {
972                        // last segment
973
974                        // Calculate vector from the previous pt to this one.
975                        Vector3 leg_v = pt_v - *prev_pt_v;
976
977                        // Obtain a horizontal vector in the LRUD plane.
978                        right = leg_v * up_v;
979                        if (right.magnitude() == 0) {
980                            right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
981                        } else {
982                            last_right = right;
983                        }
984                    } else {
985                        assert(i != trav->end());
986                        // Intermediate segment.
987
988                        // Get the coordinates of the next vertex.
989                        const XSect & next_pt_v = *i;
990
991                        // Calculate vectors from this vertex to the
992                        // next vertex, and from the previous vertex to
993                        // this one.
994                        Vector3 leg1_v = pt_v - *prev_pt_v;
995                        Vector3 leg2_v = next_pt_v - pt_v;
996
997                        // Obtain horizontal vectors perpendicular to
998                        // both legs, then normalise and average to get
999                        // a horizontal bisector.
1000                        Vector3 r1 = leg1_v * up_v;
1001                        Vector3 r2 = leg2_v * up_v;
1002                        r1.normalise();
1003                        r2.normalise();
1004                        right = r1 + r2;
1005                        if (right.magnitude() == 0) {
1006                            // This is the "mid-pitch" case...
1007                            right = last_right;
1008                        }
1009                        last_right = right;
1010                    }
1011
1012                    // Scale to unit vectors in the LRUD plane.
1013                    right.normalise();
1014
1015                    Double l = pt_v.GetL();
1016                    Double r = pt_v.GetR();
1017
1018                    if (l >= 0 || r >= 0) {
1019                        if (!filter || filter->CheckVisible(pt_v.GetLabel())) {
1020                            // Get the x and y coordinates of the survey station
1021                            double pt_X = pt_v.GetX() * COS - pt_v.GetY() * SIN;
1022                            double pt_Y = pt_v.GetX() * SIN + pt_v.GetY() * COS;
1023
1024                            double X, Y;
1025                            if (l >= 0) {
1026                                // Get the x and y coordinates of the end of the left arrow
1027                                Vector3 p = pt_v.GetPoint() - right * l;
1028                                X = p.GetX() * COS - p.GetY() * SIN;
1029                                Y = (p.GetX() * SIN + p.GetY() * COS);
1030                            } else {
1031                                X = pt_X;
1032                                Y = pt_Y;
1033                            }
1034                            if (X > m_layout.xMax) m_layout.xMax = X;
1035                            if (X < m_layout.xMin) m_layout.xMin = X;
1036                            if (Y > m_layout.yMax) m_layout.yMax = Y;
1037                            if (Y < m_layout.yMin) m_layout.yMin = Y;
1038
1039                            if (r >= 0) {
1040                                // Get the x and y coordinates of the end of the right arrow
1041                                Vector3 p = pt_v.GetPoint() + right * r;
1042                                X = p.GetX() * COS - p.GetY() * SIN;
1043                                Y = (p.GetX() * SIN + p.GetY() * COS);
1044                            } else {
1045                                X = pt_X;
1046                                Y = pt_Y;
1047                            }
1048                            if (X > m_layout.xMax) m_layout.xMax = X;
1049                            if (X < m_layout.xMin) m_layout.xMin = X;
1050                            if (Y > m_layout.yMax) m_layout.yMax = Y;
1051                            if (Y < m_layout.yMin) m_layout.yMin = Y;
1052                        }
1053                    }
1054
1055                    prev_pt_v = &pt_v;
1056
1057                    ++segment;
1058                }
1059            }
1060        }
1061    }
1062
1063    if (show_mask & (LABELS|STNS)) {
1064        for (auto label = mainfrm->GetLabels();
1065             label != mainfrm->GetLabelsEnd();
1066             ++label) {
1067            if (filter && !filter->CheckVisible((*label)->GetText()))
1068                continue;
1069            double x = (*label)->GetX();
1070            double y = (*label)->GetY();
1071            double z = (*label)->GetZ();
1072            if ((show_mask & SURF) || (*label)->IsUnderground()) {
1073                double X = x * COS - y * SIN;
1074                if (X > m_layout.xMax) m_layout.xMax = X;
1075                if (X < m_layout.xMin) m_layout.xMin = X;
1076                double Y = z * COST - (x * SIN + y * COS) * SINT;
1077                if (Y > m_layout.yMax) m_layout.yMax = Y;
1078                if (Y < m_layout.yMin) m_layout.yMin = Y;
1079            }
1080        }
1081    }
1082}
1083
1084static int xpPageWidth, ypPageDepth;
1085static long x_offset, y_offset;
1086static int fontsize, fontsize_labels;
1087
1088/* FIXME: allow the font to be set */
1089
1090static const char *fontname = "Arial", *fontname_labels = "Arial";
1091
1092svxPrintout::svxPrintout(MainFrm *mainfrm_, layout *l,
1093                         wxPageSetupDialogData *data, const wxString & title)
1094    : wxPrintout(title), font_labels(NULL), font_default(NULL),
1095      scan_for_blank_pages(false)
1096{
1097    mainfrm = mainfrm_;
1098    m_layout = l;
1099    m_data = data;
1100}
1101
1102void
1103svxPrintout::draw_info_box()
1104{
1105   layout *l = m_layout;
1106   int boxwidth = 70;
1107   int boxheight = 30;
1108
1109   pdc->SetPen(*pen_frame);
1110
1111   int div = boxwidth;
1112   if (l->view != layout::EXTELEV) {
1113      boxwidth += boxheight;
1114      MOVEMM(div, boxheight);
1115      DRAWMM(div, 0);
1116      MOVEMM(0, 30); DRAWMM(div, 30);
1117   }
1118
1119   MOVEMM(0, boxheight);
1120   DRAWMM(boxwidth, boxheight);
1121   DRAWMM(boxwidth, 0);
1122   if (!l->Border) {
1123      DRAWMM(0, 0);
1124      DRAWMM(0, boxheight);
1125   }
1126
1127   MOVEMM(0, 20); DRAWMM(div, 20);
1128   MOVEMM(0, 10); DRAWMM(div, 10);
1129
1130   switch (l->view) {
1131    case layout::PLAN: {
1132      long ax, ay, bx, by, cx, cy, dx, dy;
1133
1134      long xc = boxwidth - boxheight / 2;
1135      long yc = boxheight / 2;
1136      const double RADIUS = boxheight / 3;
1137      DrawEllipse(long(xc * l->scX), long(yc * l->scY),
1138                  long(RADIUS * l->scX), long(RADIUS * l->scY));
1139
1140      ax = (long)((xc - (RADIUS - 1) * sin(rad(000.0 + l->rot))) * l->scX);
1141      ay = (long)((yc + (RADIUS - 1) * cos(rad(000.0 + l->rot))) * l->scY);
1142      bx = (long)((xc - RADIUS * 0.5 * sin(rad(180.0 + l->rot))) * l->scX);
1143      by = (long)((yc + RADIUS * 0.5 * cos(rad(180.0 + l->rot))) * l->scY);
1144      cx = (long)((xc - (RADIUS - 1) * sin(rad(160.0 + l->rot))) * l->scX);
1145      cy = (long)((yc + (RADIUS - 1) * cos(rad(160.0 + l->rot))) * l->scY);
1146      dx = (long)((xc - (RADIUS - 1) * sin(rad(200.0 + l->rot))) * l->scX);
1147      dy = (long)((yc + (RADIUS - 1) * cos(rad(200.0 + l->rot))) * l->scY);
1148
1149      MoveTo(ax, ay);
1150      DrawTo(bx, by);
1151      DrawTo(cx, cy);
1152      DrawTo(ax, ay);
1153      DrawTo(dx, dy);
1154      DrawTo(bx, by);
1155
1156      pdc->SetTextForeground(colour_text);
1157      MOVEMM(div + 0.5, boxheight - 5.5);
1158      WriteString(wmsg(/*North*/115));
1159
1160      wxString angle = format_angle(ANGLE_FMT, l->rot);
1161      wxString s;
1162      /* TRANSLATORS: This is used on printouts of plans, with %s replaced by
1163       * something like "123°".  The bearing is up the page. */
1164      s.Printf(wmsg(/*Plan view, %s up page*/168), angle.c_str());
1165      MOVEMM(2, 12); WriteString(s);
1166      break;
1167    }
1168    case layout::ELEV: case layout::TILT: {
1169      const int L = div + 2;
1170      const int R = boxwidth - 2;
1171      const int H = boxheight / 2;
1172      MOVEMM(L, H); DRAWMM(L + 5, H - 3); DRAWMM(L + 3, H); DRAWMM(L + 5, H + 3);
1173
1174      DRAWMM(L, H); DRAWMM(R, H);
1175
1176      DRAWMM(R - 5, H + 3); DRAWMM(R - 3, H); DRAWMM(R - 5, H - 3); DRAWMM(R, H);
1177
1178      MOVEMM((L + R) / 2, H - 2); DRAWMM((L + R) / 2, H + 2);
1179
1180      pdc->SetTextForeground(colour_text);
1181      MOVEMM(div + 2, boxheight - 8);
1182      /* TRANSLATORS: "Elevation on" 020 <-> 200 degrees */
1183      WriteString(wmsg(/*Elevation on*/116));
1184
1185      MOVEMM(L, 2);
1186      WriteString(format_angle(ANGLE_FMT, fmod(l->rot + 270.0, 360.0)));
1187      MOVEMM(R - 10, 2);
1188      WriteString(format_angle(ANGLE_FMT, fmod(l->rot + 90.0, 360.0)));
1189
1190      wxString angle = format_angle(ANGLE_FMT, l->rot);
1191      wxString s;
1192      if (l->view == layout::ELEV) {
1193          /* TRANSLATORS: This is used on printouts of elevations, with %s
1194           * replaced by something like "123°".  The bearing is the direction
1195           * we’re looking. */
1196          s.Printf(wmsg(/*Elevation facing %s*/169), angle.c_str());
1197      } else {
1198          wxString a2 = format_angle(ANGLE2_FMT, l->tilt);
1199          /* TRANSLATORS: This is used on printouts of tilted elevations, with
1200           * the first %s replaced by something like "123°", and the second by
1201           * something like "-45°".  The bearing is the direction we’re
1202           * looking. */
1203          s.Printf(wmsg(/*Elevation facing %s, tilted %s*/284), angle.c_str(), a2.c_str());
1204      }
1205      MOVEMM(2, 12); WriteString(s);
1206      break;
1207    }
1208    case layout::EXTELEV:
1209      pdc->SetTextForeground(colour_text);
1210      MOVEMM(2, 12);
1211      /* TRANSLATORS: This is used on printouts of extended elevations. */
1212      WriteString(wmsg(/*Extended elevation*/191));
1213      break;
1214   }
1215
1216   MOVEMM(2, boxheight - 8); WriteString(l->title);
1217
1218   MOVEMM(2, 2);
1219   // FIXME: "Original Scale" better?
1220   WriteString(wxString::Format(wmsg(/*Scale*/154) + wxT(" 1:%.0f"),
1221                                l->Scale));
1222
1223   /* This used to be a copyright line, but it was occasionally
1224    * mis-interpreted as us claiming copyright on the survey, so let's
1225    * give the website URL instead */
1226   MOVEMM(boxwidth + 2, 2);
1227   WriteString(wxT("Survex " VERSION " - https://survex.com/"));
1228
1229   draw_scale_bar(boxwidth + 10.0, 17.0, l->PaperWidth - boxwidth - 18.0);
1230}
1231
1232/* Draw fancy scale bar with bottom left at (x,y) (both in mm) and at most */
1233/* MaxLength mm long. The scaling in use is 1:scale */
1234void
1235svxPrintout::draw_scale_bar(double x, double y, double MaxLength)
1236{
1237   double StepEst, d;
1238   int E, Step, n, c;
1239   wxString buf;
1240   /* Limit scalebar to 20cm to stop people with A0 plotters complaining */
1241   if (MaxLength > 200.0) MaxLength = 200.0;
1242
1243#define dmin 10.0      /* each division >= dmin mm long */
1244#define StepMax 5      /* number in steps of at most StepMax (x 10^N) */
1245#define epsilon (1e-4) /* fudge factor to prevent rounding problems */
1246
1247   E = (int)ceil(log10((dmin * 0.001 * m_layout->Scale) / StepMax));
1248   StepEst = pow(10.0, -(double)E) * (dmin * 0.001) * m_layout->Scale - epsilon;
1249
1250   /* Force labelling to be in multiples of 1, 2, or 5 */
1251   Step = (StepEst <= 1.0 ? 1 : (StepEst <= 2.0 ? 2 : 5));
1252
1253   /* Work out actual length of each scale bar division */
1254   d = Step * pow(10.0, (double)E) / m_layout->Scale * 1000.0;
1255
1256   /* FIXME: Non-metric units here... */
1257   /* Choose appropriate units, s.t. if possible E is >=0 and minimized */
1258   int units;
1259   if (E >= 3) {
1260      E -= 3;
1261      units = /*km*/423;
1262   } else if (E >= 0) {
1263      units = /*m*/424;
1264   } else {
1265      E += 2;
1266      units = /*cm*/425;
1267   }
1268
1269   buf = wmsg(/*Scale*/154);
1270
1271   /* Add units used - eg. "Scale (10m)" */
1272   double pow10_E = pow(10.0, (double)E);
1273   if (E >= 0) {
1274      buf += wxString::Format(wxT(" (%.f%s)"), pow10_E, wmsg(units).c_str());
1275   } else {
1276      int sf = -(int)floor(E);
1277      buf += wxString::Format(wxT(" (%.*f%s)"), sf, pow10_E, wmsg(units).c_str());
1278   }
1279   pdc->SetTextForeground(colour_text);
1280   MOVEMM(x, y + 4); WriteString(buf);
1281
1282   /* Work out how many divisions there will be */
1283   n = (int)(MaxLength / d);
1284
1285   pdc->SetPen(*pen_frame);
1286
1287   long Y = long(y * m_layout->scY);
1288   long Y2 = long((y + 3) * m_layout->scY);
1289   long X = long(x * m_layout->scX);
1290   long X2 = long((x + n * d) * m_layout->scX);
1291
1292   /* Draw top of scale bar */
1293   MoveTo(X2, Y2);
1294   DrawTo(X, Y2);
1295#if 0
1296   DrawTo(X2, Y);
1297   DrawTo(X, Y);
1298   MOVEMM(x + n * d, y); DRAWMM(x, y);
1299#endif
1300   /* Draw divisions and label them */
1301   for (c = 0; c <= n; c++) {
1302      pdc->SetPen(*pen_frame);
1303      X = long((x + c * d) * m_layout->scX);
1304      MoveTo(X, Y);
1305      DrawTo(X, Y2);
1306#if 0 // Don't waste toner!
1307      /* Draw a "zebra crossing" scale bar. */
1308      if (c < n && (c & 1) == 0) {
1309          X2 = long((x + (c + 1) * d) * m_layout->scX);
1310          SolidRectangle(X, Y, X2 - X, Y2 - Y);
1311      }
1312#endif
1313      buf.Printf(wxT("%d"), c * Step);
1314      pdc->SetTextForeground(colour_text);
1315      MOVEMM(x + c * d - buf.length(), y - 5);
1316      WriteString(buf);
1317   }
1318}
1319
1320#if 0
1321void
1322make_calibration(layout *l) {
1323      img_point pt = { 0.0, 0.0, 0.0 };
1324      l->xMax = l->yMax = 0.1;
1325      l->xMin = l->yMin = 0;
1326
1327      stack(l, img_MOVE, NULL, &pt);
1328      pt.x = 0.1;
1329      stack(l, img_LINE, NULL, &pt);
1330      pt.y = 0.1;
1331      stack(l, img_LINE, NULL, &pt);
1332      pt.x = 0.0;
1333      stack(l, img_LINE, NULL, &pt);
1334      pt.y = 0.0;
1335      stack(l, img_LINE, NULL, &pt);
1336      pt.x = 0.05;
1337      pt.y = 0.001;
1338      stack(l, img_LABEL, "10cm", &pt);
1339      pt.x = 0.001;
1340      pt.y = 0.05;
1341      stack(l, img_LABEL, "10cm", &pt);
1342      l->Scale = 1.0;
1343}
1344#endif
1345
1346int
1347svxPrintout::next_page(int *pstate, char **q, int pageLim)
1348{
1349   char *p;
1350   int page;
1351   int c;
1352   p = *q;
1353   if (*pstate > 0) {
1354      /* doing a range */
1355      (*pstate)++;
1356      wxASSERT(*p == '-');
1357      p++;
1358      while (isspace((unsigned char)*p)) p++;
1359      if (sscanf(p, "%u%n", &page, &c) > 0) {
1360         p += c;
1361      } else {
1362         page = pageLim;
1363      }
1364      if (*pstate > page) goto err;
1365      if (*pstate < page) return *pstate;
1366      *q = p;
1367      *pstate = 0;
1368      return page;
1369   }
1370
1371   while (isspace((unsigned char)*p) || *p == ',') p++;
1372
1373   if (!*p) return 0; /* done */
1374
1375   if (*p == '-') {
1376      *q = p;
1377      *pstate = 1;
1378      return 1; /* range with initial parameter omitted */
1379   }
1380   if (sscanf(p, "%u%n", &page, &c) > 0) {
1381      p += c;
1382      while (isspace((unsigned char)*p)) p++;
1383      *q = p;
1384      if (0 < page && page <= pageLim) {
1385         if (*p == '-') *pstate = page; /* range with start */
1386         return page;
1387      }
1388   }
1389   err:
1390   *pstate = -1;
1391   return 0;
1392}
1393
1394/* Draws in alignment marks on each page or borders on edge pages */
1395void
1396svxPrintout::drawticks(int tsize, int x, int y)
1397{
1398   long i;
1399   int s = tsize * 4;
1400   int o = s / 8;
1401   bool fAtCorner = fFalse;
1402   pdc->SetPen(*pen_frame);
1403   if (x == 0 && m_layout->Border) {
1404      /* solid left border */
1405      MoveTo(clip.x_min, clip.y_min);
1406      DrawTo(clip.x_min, clip.y_max);
1407      fAtCorner = fTrue;
1408   } else {
1409      if (x > 0 || y > 0) {
1410         MoveTo(clip.x_min, clip.y_min);
1411         DrawTo(clip.x_min, clip.y_min + tsize);
1412      }
1413      if (s && x > 0 && m_layout->Cutlines) {
1414         /* dashed left border */
1415         i = (clip.y_max - clip.y_min) -
1416             (tsize + ((clip.y_max - clip.y_min - tsize * 2L) % s) / 2);
1417         for ( ; i > tsize; i -= s) {
1418            MoveTo(clip.x_min, clip.y_max - (i + o));
1419            DrawTo(clip.x_min, clip.y_max - (i - o));
1420         }
1421      }
1422      if (x > 0 || y < m_layout->pagesY - 1) {
1423         MoveTo(clip.x_min, clip.y_max - tsize);
1424         DrawTo(clip.x_min, clip.y_max);
1425         fAtCorner = fTrue;
1426      }
1427   }
1428
1429   if (y == m_layout->pagesY - 1 && m_layout->Border) {
1430      /* solid top border */
1431      if (!fAtCorner) MoveTo(clip.x_min, clip.y_max);
1432      DrawTo(clip.x_max, clip.y_max);
1433      fAtCorner = fTrue;
1434   } else {
1435      if (y < m_layout->pagesY - 1 || x > 0) {
1436         if (!fAtCorner) MoveTo(clip.x_min, clip.y_max);
1437         DrawTo(clip.x_min + tsize, clip.y_max);
1438      }
1439      if (s && y < m_layout->pagesY - 1 && m_layout->Cutlines) {
1440         /* dashed top border */
1441         i = (clip.x_max - clip.x_min) -
1442             (tsize + ((clip.x_max - clip.x_min - tsize * 2L) % s) / 2);
1443         for ( ; i > tsize; i -= s) {
1444            MoveTo(clip.x_max - (i + o), clip.y_max);
1445            DrawTo(clip.x_max - (i - o), clip.y_max);
1446         }
1447      }
1448      if (y < m_layout->pagesY - 1 || x < m_layout->pagesX - 1) {
1449         MoveTo(clip.x_max - tsize, clip.y_max);
1450         DrawTo(clip.x_max, clip.y_max);
1451         fAtCorner = fTrue;
1452      } else {
1453         fAtCorner = fFalse;
1454      }
1455   }
1456
1457   if (x == m_layout->pagesX - 1 && m_layout->Border) {
1458      /* solid right border */
1459      if (!fAtCorner) MoveTo(clip.x_max, clip.y_max);
1460      DrawTo(clip.x_max, clip.y_min);
1461      fAtCorner = fTrue;
1462   } else {
1463      if (x < m_layout->pagesX - 1 || y < m_layout->pagesY - 1) {
1464         if (!fAtCorner) MoveTo(clip.x_max, clip.y_max);
1465         DrawTo(clip.x_max, clip.y_max - tsize);
1466      }
1467      if (s && x < m_layout->pagesX - 1 && m_layout->Cutlines) {
1468         /* dashed right border */
1469         i = (clip.y_max - clip.y_min) -
1470             (tsize + ((clip.y_max - clip.y_min - tsize * 2L) % s) / 2);
1471         for ( ; i > tsize; i -= s) {
1472            MoveTo(clip.x_max, clip.y_min + (i + o));
1473            DrawTo(clip.x_max, clip.y_min + (i - o));
1474         }
1475      }
1476      if (x < m_layout->pagesX - 1 || y > 0) {
1477         MoveTo(clip.x_max, clip.y_min + tsize);
1478         DrawTo(clip.x_max, clip.y_min);
1479         fAtCorner = fTrue;
1480      } else {
1481         fAtCorner = fFalse;
1482      }
1483   }
1484
1485   if (y == 0 && m_layout->Border) {
1486      /* solid bottom border */
1487      if (!fAtCorner) MoveTo(clip.x_max, clip.y_min);
1488      DrawTo(clip.x_min, clip.y_min);
1489   } else {
1490      if (y > 0 || x < m_layout->pagesX - 1) {
1491         if (!fAtCorner) MoveTo(clip.x_max, clip.y_min);
1492         DrawTo(clip.x_max - tsize, clip.y_min);
1493      }
1494      if (s && y > 0 && m_layout->Cutlines) {
1495         /* dashed bottom border */
1496         i = (clip.x_max - clip.x_min) -
1497             (tsize + ((clip.x_max - clip.x_min - tsize * 2L) % s) / 2);
1498         for ( ; i > tsize; i -= s) {
1499            MoveTo(clip.x_min + (i + o), clip.y_min);
1500            DrawTo(clip.x_min + (i - o), clip.y_min);
1501         }
1502      }
1503      if (y > 0 || x > 0) {
1504         MoveTo(clip.x_min + tsize, clip.y_min);
1505         DrawTo(clip.x_min, clip.y_min);
1506      }
1507   }
1508}
1509
1510bool
1511svxPrintout::OnPrintPage(int pageNum) {
1512    GetPageSizePixels(&xpPageWidth, &ypPageDepth);
1513    pdc = GetDC();
1514    pdc->SetBackgroundMode(wxTRANSPARENT);
1515#ifdef AVEN_PRINT_PREVIEW
1516    if (IsPreview()) {
1517        int dcx, dcy;
1518        pdc->GetSize(&dcx, &dcy);
1519        pdc->SetUserScale((double)dcx / xpPageWidth, (double)dcy / ypPageDepth);
1520    }
1521#endif
1522
1523    layout * l = m_layout;
1524    {
1525        int pwidth, pdepth;
1526        GetPageSizeMM(&pwidth, &pdepth);
1527        l->scX = (double)xpPageWidth / pwidth;
1528        l->scY = (double)ypPageDepth / pdepth;
1529        font_scaling_x = l->scX * (25.4 / 72.0);
1530        font_scaling_y = l->scY * (25.4 / 72.0);
1531        long MarginLeft = m_data->GetMarginTopLeft().x;
1532        long MarginTop = m_data->GetMarginTopLeft().y;
1533        long MarginBottom = m_data->GetMarginBottomRight().y;
1534        long MarginRight = m_data->GetMarginBottomRight().x;
1535        xpPageWidth -= (int)(l->scX * (MarginLeft + MarginRight));
1536        ypPageDepth -= (int)(l->scY * (FOOTER_HEIGHT_MM + MarginBottom + MarginTop));
1537        // xpPageWidth -= 1;
1538        pdepth -= FOOTER_HEIGHT_MM;
1539        x_offset = (long)(l->scX * MarginLeft);
1540        y_offset = (long)(l->scY * MarginTop);
1541        l->PaperWidth = pwidth -= MarginLeft + MarginRight;
1542        l->PaperDepth = pdepth -= MarginTop + MarginBottom;
1543    }
1544
1545    double SIN = sin(rad(l->rot));
1546    double COS = cos(rad(l->rot));
1547    double SINT = sin(rad(l->tilt));
1548    double COST = cos(rad(l->tilt));
1549
1550    NewPage(pageNum, l->pagesX, l->pagesY);
1551
1552    if (l->Legend && pageNum == (l->pagesY - 1) * l->pagesX + 1) {
1553        SetFont(font_default);
1554        draw_info_box();
1555    }
1556
1557    pdc->SetClippingRegion(x_offset, y_offset, xpPageWidth + 1, ypPageDepth + 1);
1558
1559    const double Sc = 1000 / l->Scale;
1560
1561    const SurveyFilter* filter = mainfrm->GetTreeFilter();
1562    int show_mask = l->get_effective_show_mask();
1563    if (show_mask & (LEGS|SURF)) {
1564        for (int f = 0; f != 8; ++f) {
1565            if ((show_mask & (f & img_FLAG_SURFACE) ? SURF : LEGS) == 0) {
1566                // Not showing traverse because of surface/underground status.
1567                continue;
1568            }
1569            if ((f & img_FLAG_SPLAY) && (show_mask & SPLAYS) == 0) {
1570                // Not showing because it's a splay.
1571                continue;
1572            }
1573            if (f & img_FLAG_SPLAY) {
1574                pdc->SetPen(*pen_splay);
1575            } else if (f & img_FLAG_SURFACE) {
1576                pdc->SetPen(*pen_surface_leg);
1577            } else {
1578                pdc->SetPen(*pen_leg);
1579            }
1580            list<traverse>::const_iterator trav = mainfrm->traverses_begin(f, filter);
1581            list<traverse>::const_iterator tend = mainfrm->traverses_end(f);
1582            for ( ; trav != tend; trav = mainfrm->traverses_next(f, filter, trav)) {
1583                vector<PointInfo>::const_iterator pos = trav->begin();
1584                vector<PointInfo>::const_iterator end = trav->end();
1585                for ( ; pos != end; ++pos) {
1586                    double x = pos->GetX();
1587                    double y = pos->GetY();
1588                    double z = pos->GetZ();
1589                    double X = x * COS - y * SIN;
1590                    double Y = z * COST - (x * SIN + y * COS) * SINT;
1591                    long px = (long)((X * Sc + l->xOrg) * l->scX);
1592                    long py = (long)((Y * Sc + l->yOrg) * l->scY);
1593                    if (pos == trav->begin()) {
1594                        MoveTo(px, py);
1595                    } else {
1596                        DrawTo(px, py);
1597                    }
1598                }
1599            }
1600        }
1601    }
1602
1603    if ((show_mask & XSECT) &&
1604        (l->tilt == 0.0 || l->tilt == 90.0 || l->tilt == -90.0)) {
1605        pdc->SetPen(*pen_splay);
1606        list<vector<XSect>>::const_iterator trav = mainfrm->tubes_begin();
1607        list<vector<XSect>>::const_iterator tend = mainfrm->tubes_end();
1608        for ( ; trav != tend; ++trav) {
1609            if (l->tilt == 0.0) {
1610                PlotUD(*trav);
1611            } else {
1612                // m_layout.tilt is 90.0 or -90.0 due to check above.
1613                PlotLR(*trav);
1614            }
1615        }
1616    }
1617
1618    if (show_mask & (LABELS|STNS)) {
1619        if (show_mask & LABELS) SetFont(font_labels);
1620        for (auto label = mainfrm->GetLabels();
1621             label != mainfrm->GetLabelsEnd();
1622             ++label) {
1623            if (filter && !filter->CheckVisible((*label)->GetText()))
1624                continue;
1625            double px = (*label)->GetX();
1626            double py = (*label)->GetY();
1627            double pz = (*label)->GetZ();
1628            if ((show_mask & SURF) || (*label)->IsUnderground()) {
1629                double X = px * COS - py * SIN;
1630                double Y = pz * COST - (px * SIN + py * COS) * SINT;
1631                long xnew, ynew;
1632                xnew = (long)((X * Sc + l->xOrg) * l->scX);
1633                ynew = (long)((Y * Sc + l->yOrg) * l->scY);
1634                if (show_mask & STNS) {
1635                    pdc->SetPen(*pen_cross);
1636                    DrawCross(xnew, ynew);
1637                }
1638                if (show_mask & LABELS) {
1639                    pdc->SetTextForeground(colour_labels);
1640                    MoveTo(xnew, ynew);
1641                    WriteString((*label)->GetText());
1642                }
1643            }
1644        }
1645    }
1646
1647    return true;
1648}
1649
1650void
1651svxPrintout::GetPageInfo(int *minPage, int *maxPage,
1652                         int *pageFrom, int *pageTo)
1653{
1654    *minPage = *pageFrom = 1;
1655    *maxPage = *pageTo = m_layout->pages;
1656}
1657
1658bool
1659svxPrintout::HasPage(int pageNum) {
1660    return (pageNum <= m_layout->pages);
1661}
1662
1663void
1664svxPrintout::OnBeginPrinting() {
1665    /* Initialise printer routines */
1666    fontsize_labels = 10;
1667    fontsize = 10;
1668
1669    colour_text = colour_labels = *wxBLACK;
1670
1671    wxColour colour_frame, colour_cross, colour_leg, colour_surface_leg;
1672    colour_frame = colour_cross = colour_leg = colour_surface_leg = *wxBLACK;
1673
1674    pen_frame = new wxPen(colour_frame);
1675    pen_cross = new wxPen(colour_cross);
1676    pen_leg = new wxPen(colour_leg);
1677    pen_surface_leg = new wxPen(colour_surface_leg);
1678    pen_splay = new wxPen(wxColour(128, 128, 128));
1679
1680    m_layout->scX = 1;
1681    m_layout->scY = 1;
1682
1683    font_labels = new wxFont(fontsize_labels, wxFONTFAMILY_DEFAULT,
1684                             wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL,
1685                             false, wxString(fontname_labels, wxConvUTF8),
1686                             wxFONTENCODING_ISO8859_1);
1687    font_default = new wxFont(fontsize, wxFONTFAMILY_DEFAULT,
1688                              wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL,
1689                              false, wxString(fontname, wxConvUTF8),
1690                              wxFONTENCODING_ISO8859_1);
1691}
1692
1693void
1694svxPrintout::OnEndPrinting() {
1695    delete font_labels;
1696    delete font_default;
1697    delete pen_frame;
1698    delete pen_cross;
1699    delete pen_leg;
1700    delete pen_surface_leg;
1701    delete pen_splay;
1702}
1703
1704int
1705svxPrintout::check_intersection(long x_p, long y_p)
1706{
1707#define U 1
1708#define D 2
1709#define L 4
1710#define R 8
1711   int mask_p = 0, mask_t = 0;
1712   if (x_p < 0)
1713      mask_p = L;
1714   else if (x_p > xpPageWidth)
1715      mask_p = R;
1716
1717   if (y_p < 0)
1718      mask_p |= D;
1719   else if (y_p > ypPageDepth)
1720      mask_p |= U;
1721
1722   if (x_t < 0)
1723      mask_t = L;
1724   else if (x_t > xpPageWidth)
1725      mask_t = R;
1726
1727   if (y_t < 0)
1728      mask_t |= D;
1729   else if (y_t > ypPageDepth)
1730      mask_t |= U;
1731
1732#if 0
1733   /* approximation to correct answer */
1734   return !(mask_t & mask_p);
1735#else
1736   /* One end of the line is on the page */
1737   if (!mask_t || !mask_p) return 1;
1738
1739   /* whole line is above, left, right, or below page */
1740   if (mask_t & mask_p) return 0;
1741
1742   if (mask_t == 0) mask_t = mask_p;
1743   if (mask_t & U) {
1744      double v = (double)(y_p - ypPageDepth) / (y_p - y_t);
1745      return v >= 0 && v <= 1;
1746   }
1747   if (mask_t & D) {
1748      double v = (double)y_p / (y_p - y_t);
1749      return v >= 0 && v <= 1;
1750   }
1751   if (mask_t & R) {
1752      double v = (double)(x_p - xpPageWidth) / (x_p - x_t);
1753      return v >= 0 && v <= 1;
1754   }
1755   wxASSERT(mask_t & L);
1756   {
1757      double v = (double)x_p / (x_p - x_t);
1758      return v >= 0 && v <= 1;
1759   }
1760#endif
1761#undef U
1762#undef D
1763#undef L
1764#undef R
1765}
1766
1767void
1768svxPrintout::MoveTo(long x, long y)
1769{
1770    x_t = x_offset + x - clip.x_min;
1771    y_t = y_offset + clip.y_max - y;
1772}
1773
1774void
1775svxPrintout::DrawTo(long x, long y)
1776{
1777    long x_p = x_t, y_p = y_t;
1778    x_t = x_offset + x - clip.x_min;
1779    y_t = y_offset + clip.y_max - y;
1780    if (!scan_for_blank_pages) {
1781        pdc->DrawLine(x_p, y_p, x_t, y_t);
1782    } else {
1783        if (check_intersection(x_p, y_p)) fBlankPage = fFalse;
1784    }
1785}
1786
1787#define POINTS_PER_INCH 72.0
1788#define POINTS_PER_MM (POINTS_PER_INCH / MM_PER_INCH)
1789#define PWX_CROSS_SIZE (int)(2 * m_layout->scX / POINTS_PER_MM)
1790
1791void
1792svxPrintout::DrawCross(long x, long y)
1793{
1794   if (!scan_for_blank_pages) {
1795      MoveTo(x - PWX_CROSS_SIZE, y - PWX_CROSS_SIZE);
1796      DrawTo(x + PWX_CROSS_SIZE, y + PWX_CROSS_SIZE);
1797      MoveTo(x + PWX_CROSS_SIZE, y - PWX_CROSS_SIZE);
1798      DrawTo(x - PWX_CROSS_SIZE, y + PWX_CROSS_SIZE);
1799      MoveTo(x, y);
1800   } else {
1801      if ((x + PWX_CROSS_SIZE > clip.x_min &&
1802           x - PWX_CROSS_SIZE < clip.x_max) ||
1803          (y + PWX_CROSS_SIZE > clip.y_min &&
1804           y - PWX_CROSS_SIZE < clip.y_max)) {
1805         fBlankPage = fFalse;
1806      }
1807   }
1808}
1809
1810void
1811svxPrintout::WriteString(const wxString & s)
1812{
1813    double xsc, ysc;
1814    pdc->GetUserScale(&xsc, &ysc);
1815    pdc->SetUserScale(xsc * font_scaling_x, ysc * font_scaling_y);
1816    if (!scan_for_blank_pages) {
1817        pdc->DrawText(s,
1818                      long(x_t / font_scaling_x),
1819                      long(y_t / font_scaling_y) - pdc->GetCharHeight());
1820    } else {
1821        int w, h;
1822        pdc->GetTextExtent(s, &w, &h);
1823        if ((y_t + h > 0 && y_t - h < clip.y_max - clip.y_min) ||
1824            (x_t < clip.x_max - clip.x_min && x_t + w > 0)) {
1825            fBlankPage = fFalse;
1826        }
1827    }
1828    pdc->SetUserScale(xsc, ysc);
1829}
1830
1831void
1832svxPrintout::DrawEllipse(long x, long y, long r, long R)
1833{
1834    if (!scan_for_blank_pages) {
1835        x_t = x_offset + x - clip.x_min;
1836        y_t = y_offset + clip.y_max - y;
1837        const wxBrush & save_brush = pdc->GetBrush();
1838        pdc->SetBrush(*wxTRANSPARENT_BRUSH);
1839        pdc->DrawEllipse(x_t - r, y_t - R, 2 * r, 2 * R);
1840        pdc->SetBrush(save_brush);
1841    } else {
1842        /* No need to check - this is only used in the legend. */
1843    }
1844}
1845
1846void
1847svxPrintout::SolidRectangle(long x, long y, long w, long h)
1848{
1849    long X = x_offset + x - clip.x_min;
1850    long Y = y_offset + clip.y_max - y;
1851    pdc->SetBrush(*wxBLACK_BRUSH);
1852    pdc->DrawRectangle(X, Y - h, w, h);
1853}
1854
1855void
1856svxPrintout::NewPage(int pg, int pagesX, int pagesY)
1857{
1858    pdc->DestroyClippingRegion();
1859
1860    int x, y;
1861    x = (pg - 1) % pagesX;
1862    y = pagesY - 1 - ((pg - 1) / pagesX);
1863
1864    clip.x_min = (long)x * xpPageWidth;
1865    clip.y_min = (long)y * ypPageDepth;
1866    clip.x_max = clip.x_min + xpPageWidth; /* dm/pcl/ps had -1; */
1867    clip.y_max = clip.y_min + ypPageDepth; /* dm/pcl/ps had -1; */
1868
1869    const int FOOTERS = 4;
1870    wxString footer[FOOTERS];
1871    footer[0] = m_layout->title;
1872
1873    double rot = m_layout->rot;
1874    double tilt = m_layout->tilt;
1875    double scale = m_layout->Scale;
1876    switch (m_layout->view) {
1877        case layout::PLAN:
1878            // TRANSLATORS: Used in the footer of printouts to compactly
1879            // indicate this is a plan view and what the viewing angle is.
1880            // Aven will replace %s with the bearing, and %.0f with the scale.
1881            //
1882            // This message probably doesn't need translating for most languages.
1883            footer[1].Printf(wmsg(/*↑%s 1:%.0f*/233),
1884                    format_angle(ANGLE_FMT, rot).c_str(),
1885                    scale);
1886            break;
1887        case layout::ELEV:
1888            // TRANSLATORS: Used in the footer of printouts to compactly
1889            // indicate this is an elevation view and what the viewing angle
1890            // is.  Aven will replace the %s codes with the bearings to the
1891            // left and right of the viewer, and %.0f with the scale.
1892            //
1893            // This message probably doesn't need translating for most languages.
1894            footer[1].Printf(wmsg(/*%s↔%s 1:%.0f*/235),
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                    scale);
1898            break;
1899        case layout::TILT:
1900            // TRANSLATORS: Used in the footer of printouts to compactly
1901            // indicate this is a tilted elevation view and what the viewing
1902            // angles are.  Aven will replace the %s codes with the bearings to
1903            // the left and right of the viewer and the angle the view is
1904            // tilted at, and %.0f with the scale.
1905            //
1906            // This message probably doesn't need translating for most languages.
1907            footer[1].Printf(wmsg(/*%s↔%s ∡%s 1:%.0f*/236),
1908                    format_angle(ANGLE_FMT, fmod(rot + 270.0, 360.0)).c_str(),
1909                    format_angle(ANGLE_FMT, fmod(rot + 90.0, 360.0)).c_str(),
1910                    format_angle(ANGLE2_FMT, tilt).c_str(),
1911                    scale);
1912            break;
1913        case layout::EXTELEV:
1914            // TRANSLATORS: Used in the footer of printouts to compactly
1915            // indicate this is an extended elevation view.  Aven will replace
1916            // %.0f with the scale.
1917            //
1918            // Try to keep the translation short (for example, in English we
1919            // use "Extended" not "Extended elevation") - there is limited room
1920            // in the footer, and the details there are mostly to make it easy
1921            // to check that you have corresponding pages from a multiple page
1922            // printout.
1923            footer[1].Printf(wmsg(/*Extended 1:%.0f*/244), scale);
1924            break;
1925    }
1926
1927    // TRANSLATORS: N/M meaning page N of M in the page footer of a printout.
1928    footer[2].Printf(wmsg(/*%d/%d*/232), pg, m_layout->pagesX * m_layout->pagesY);
1929
1930    wxString datestamp = m_layout->datestamp;
1931    if (!datestamp.empty()) {
1932        // Remove any timezone suffix (e.g. " UTC" or " +1200").
1933        wxChar ch = datestamp[datestamp.size() - 1];
1934        if (ch >= 'A' && ch <= 'Z') {
1935            for (size_t i = datestamp.size() - 1; i; --i) {
1936                ch = datestamp[i];
1937                if (ch < 'A' || ch > 'Z') {
1938                    if (ch == ' ') datestamp.resize(i);
1939                    break;
1940                }
1941            }
1942        } else if (ch >= '0' && ch <= '9') {
1943            for (size_t i = datestamp.size() - 1; i; --i) {
1944                ch = datestamp[i];
1945                if (ch < '0' || ch > '9') {
1946                    if ((ch == '-' || ch == '+') && datestamp[--i] == ' ')
1947                        datestamp.resize(i);
1948                    break;
1949                }
1950            }
1951        }
1952
1953        // Remove any day prefix (e.g. "Mon,").
1954        for (size_t i = 0; i != datestamp.size(); ++i) {
1955            if (datestamp[i] == ',' && i + 1 != datestamp.size()) {
1956                // Also skip a space after the comma.
1957                if (datestamp[i + 1] == ' ') ++i;
1958                datestamp.erase(0, i + 1);
1959                break;
1960            }
1961        }
1962    }
1963
1964    // TRANSLATORS: Used in the footer of printouts to compactly indicate that
1965    // the date which follows is the date that the survey data was processed.
1966    //
1967    // Aven will replace %s with a string giving the date and time (e.g.
1968    // "2015-06-09 12:40:44").
1969    footer[3].Printf(wmsg(/*Processed: %s*/167), datestamp.c_str());
1970
1971    const wxChar * footer_sep = wxT("    ");
1972    int fontsize_footer = fontsize_labels;
1973    wxFont * font_footer;
1974    font_footer = new wxFont(fontsize_footer, wxFONTFAMILY_DEFAULT,
1975                             wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL,
1976                             false, wxString(fontname_labels, wxConvUTF8),
1977                             wxFONTENCODING_UTF8);
1978    font_footer->Scale(font_scaling_x);
1979    SetFont(font_footer);
1980    int w[FOOTERS], ws, h;
1981    pdc->GetTextExtent(footer_sep, &ws, &h);
1982    int wtotal = ws * (FOOTERS - 1);
1983    for (int i = 0; i < FOOTERS; ++i) {
1984        pdc->GetTextExtent(footer[i], &w[i], &h);
1985        wtotal += w[i];
1986    }
1987
1988    long X = x_offset;
1989    long Y = y_offset + ypPageDepth + (long)(7 * m_layout->scY) - pdc->GetCharHeight();
1990
1991    if (wtotal > xpPageWidth) {
1992        // Rescale the footer so it fits.
1993        double rescale = double(wtotal) / xpPageWidth;
1994        double xsc, ysc;
1995        pdc->GetUserScale(&xsc, &ysc);
1996        pdc->SetUserScale(xsc / rescale, ysc / rescale);
1997        SetFont(font_footer);
1998        wxString fullfooter = footer[0];
1999        for (int i = 1; i < FOOTERS - 1; ++i) {
2000            fullfooter += footer_sep;
2001            fullfooter += footer[i];
2002        }
2003        pdc->DrawText(fullfooter, X * rescale, Y * rescale);
2004        // Draw final item right aligned to avoid misaligning.
2005        wxRect rect(x_offset * rescale, Y * rescale,
2006                    xpPageWidth * rescale, pdc->GetCharHeight() * rescale);
2007        pdc->DrawLabel(footer[FOOTERS - 1], rect, wxALIGN_RIGHT|wxALIGN_TOP);
2008        pdc->SetUserScale(xsc, ysc);
2009    } else {
2010        // Space out the elements of the footer to fill the line.
2011        double extra = double(xpPageWidth - wtotal) / (FOOTERS - 1);
2012        for (int i = 0; i < FOOTERS - 1; ++i) {
2013            pdc->DrawText(footer[i], X + extra * i, Y);
2014            X += ws + w[i];
2015        }
2016        // Draw final item right aligned to avoid misaligning.
2017        wxRect rect(x_offset, Y, xpPageWidth, pdc->GetCharHeight());
2018        pdc->DrawLabel(footer[FOOTERS - 1], rect, wxALIGN_RIGHT|wxALIGN_TOP);
2019    }
2020    drawticks((int)(9 * m_layout->scX / POINTS_PER_MM), x, y);
2021}
2022
2023void
2024svxPrintout::PlotLR(const vector<XSect> & centreline)
2025{
2026    const SurveyFilter* filter = mainfrm->GetTreeFilter();
2027    assert(centreline.size() > 1);
2028    const XSect* prev_pt_v = NULL;
2029    Vector3 last_right(1.0, 0.0, 0.0);
2030
2031    const double Sc = 1000 / m_layout->Scale;
2032    const double SIN = sin(rad(m_layout->rot));
2033    const double COS = cos(rad(m_layout->rot));
2034
2035    vector<XSect>::const_iterator i = centreline.begin();
2036    vector<XSect>::size_type segment = 0;
2037    while (i != centreline.end()) {
2038        // get the coordinates of this vertex
2039        const XSect & pt_v = *i++;
2040
2041        Vector3 right;
2042
2043        const Vector3 up_v(0.0, 0.0, 1.0);
2044
2045        if (segment == 0) {
2046            assert(i != centreline.end());
2047            // first segment
2048
2049            // get the coordinates of the next vertex
2050            const XSect & next_pt_v = *i;
2051
2052            // calculate vector from this pt to the next one
2053            Vector3 leg_v = next_pt_v - pt_v;
2054
2055            // obtain a vector in the LRUD plane
2056            right = leg_v * up_v;
2057            if (right.magnitude() == 0) {
2058                right = last_right;
2059            } else {
2060                last_right = right;
2061            }
2062        } else if (segment + 1 == centreline.size()) {
2063            // last segment
2064
2065            // Calculate vector from the previous pt to this one.
2066            Vector3 leg_v = pt_v - *prev_pt_v;
2067
2068            // Obtain a horizontal vector in the LRUD plane.
2069            right = leg_v * up_v;
2070            if (right.magnitude() == 0) {
2071                right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
2072            } else {
2073                last_right = right;
2074            }
2075        } else {
2076            assert(i != centreline.end());
2077            // Intermediate segment.
2078
2079            // Get the coordinates of the next vertex.
2080            const XSect & next_pt_v = *i;
2081
2082            // Calculate vectors from this vertex to the
2083            // next vertex, and from the previous vertex to
2084            // this one.
2085            Vector3 leg1_v = pt_v - *prev_pt_v;
2086            Vector3 leg2_v = next_pt_v - pt_v;
2087
2088            // Obtain horizontal vectors perpendicular to
2089            // both legs, then normalise and average to get
2090            // a horizontal bisector.
2091            Vector3 r1 = leg1_v * up_v;
2092            Vector3 r2 = leg2_v * up_v;
2093            r1.normalise();
2094            r2.normalise();
2095            right = r1 + r2;
2096            if (right.magnitude() == 0) {
2097                // This is the "mid-pitch" case...
2098                right = last_right;
2099            }
2100            last_right = right;
2101        }
2102
2103        // Scale to unit vectors in the LRUD plane.
2104        right.normalise();
2105
2106        Double l = pt_v.GetL();
2107        Double r = pt_v.GetR();
2108
2109        if (l >= 0 || r >= 0) {
2110            if (!filter || filter->CheckVisible(pt_v.GetLabel())) {
2111                // Get the x and y coordinates of the survey station
2112                double pt_X = pt_v.GetX() * COS - pt_v.GetY() * SIN;
2113                double pt_Y = pt_v.GetX() * SIN + pt_v.GetY() * COS;
2114                long pt_x = (long)((pt_X * Sc + m_layout->xOrg) * m_layout->scX);
2115                long pt_y = (long)((pt_Y * Sc + m_layout->yOrg) * m_layout->scY);
2116
2117                // Calculate dimensions for the right arrow
2118                double COSR = right.GetX();
2119                double SINR = right.GetY();
2120                long CROSS_MAJOR = (COSR + SINR) * PWX_CROSS_SIZE;
2121                long CROSS_MINOR = (COSR - SINR) * PWX_CROSS_SIZE;
2122
2123                if (l >= 0) {
2124                    // Get the x and y coordinates of the end of the left arrow
2125                    Vector3 p = pt_v.GetPoint() - right * l;
2126                    double X = p.GetX() * COS - p.GetY() * SIN;
2127                    double Y = (p.GetX() * SIN + p.GetY() * COS);
2128                    long x = (long)((X * Sc + m_layout->xOrg) * m_layout->scX);
2129                    long y = (long)((Y * Sc + m_layout->yOrg) * m_layout->scY);
2130
2131                    // Draw the arrow stem
2132                    MoveTo(pt_x, pt_y);
2133                    DrawTo(x, y);
2134
2135                    // Rotate the arrow by the page rotation
2136                    long dx1 = (+CROSS_MINOR) * COS - (+CROSS_MAJOR) * SIN;
2137                    long dy1 = (+CROSS_MINOR) * SIN + (+CROSS_MAJOR) * COS;
2138                    long dx2 = (+CROSS_MAJOR) * COS - (-CROSS_MINOR) * SIN;
2139                    long dy2 = (+CROSS_MAJOR) * SIN + (-CROSS_MINOR) * COS;
2140
2141                    // Draw the arrow
2142                    MoveTo(x + dx1, y + dy1);
2143                    DrawTo(x, y);
2144                    DrawTo(x + dx2, y + dy2);
2145                }
2146
2147                if (r >= 0) {
2148                    // Get the x and y coordinates of the end of the right arrow
2149                    Vector3 p = pt_v.GetPoint() + right * r;
2150                    double X = p.GetX() * COS - p.GetY() * SIN;
2151                    double Y = (p.GetX() * SIN + p.GetY() * COS);
2152                    long x = (long)((X * Sc + m_layout->xOrg) * m_layout->scX);
2153                    long y = (long)((Y * Sc + m_layout->yOrg) * m_layout->scY);
2154
2155                    // Draw the arrow stem
2156                    MoveTo(pt_x, pt_y);
2157                    DrawTo(x, y);
2158
2159                    // Rotate the arrow by the page rotation
2160                    long dx1 = (-CROSS_MINOR) * COS - (-CROSS_MAJOR) * SIN;
2161                    long dy1 = (-CROSS_MINOR) * SIN + (-CROSS_MAJOR) * COS;
2162                    long dx2 = (-CROSS_MAJOR) * COS - (+CROSS_MINOR) * SIN;
2163                    long dy2 = (-CROSS_MAJOR) * SIN + (+CROSS_MINOR) * COS;
2164
2165                    // Draw the arrow
2166                    MoveTo(x + dx1, y + dy1);
2167                    DrawTo(x, y);
2168                    DrawTo(x + dx2, y + dy2);
2169                }
2170            }
2171        }
2172
2173        prev_pt_v = &pt_v;
2174
2175        ++segment;
2176    }
2177}
2178
2179void
2180svxPrintout::PlotUD(const vector<XSect> & centreline)
2181{
2182    const SurveyFilter* filter = mainfrm->GetTreeFilter();
2183    assert(centreline.size() > 1);
2184    const double Sc = 1000 / m_layout->Scale;
2185
2186    vector<XSect>::const_iterator i = centreline.begin();
2187    while (i != centreline.end()) {
2188        // get the coordinates of this vertex
2189        const XSect & pt_v = *i++;
2190
2191        Double u = pt_v.GetU();
2192        Double d = pt_v.GetD();
2193
2194        if (u >= 0 || d >= 0) {
2195            if (filter && !filter->CheckVisible(pt_v.GetLabel()))
2196                continue;
2197
2198            // Get the coordinates of the survey point
2199            Vector3 p = pt_v.GetPoint();
2200            double SIN = sin(rad(m_layout->rot));
2201            double COS = cos(rad(m_layout->rot));
2202            double X = p.GetX() * COS - p.GetY() * SIN;
2203            double Y = p.GetZ();
2204            long x = (long)((X * Sc + m_layout->xOrg) * m_layout->scX);
2205            long pt_y = (long)((Y * Sc + m_layout->yOrg) * m_layout->scX);
2206
2207            if (u >= 0) {
2208                // Get the y coordinate of the up arrow
2209                long y = (long)(((Y + u) * Sc + m_layout->yOrg) * m_layout->scY);
2210
2211                // Draw the arrow stem
2212                MoveTo(x, pt_y);
2213                DrawTo(x, y);
2214
2215                // Draw the up arrow
2216                MoveTo(x - PWX_CROSS_SIZE, y - PWX_CROSS_SIZE);
2217                DrawTo(x, y);
2218                DrawTo(x + PWX_CROSS_SIZE, y - PWX_CROSS_SIZE);
2219            }
2220
2221            if (d >= 0) {
2222                // Get the y coordinate of the down arrow
2223                long y = (long)(((Y - d) * Sc + m_layout->yOrg) * m_layout->scY);
2224
2225                // Draw the arrow stem
2226                MoveTo(x, pt_y);
2227                DrawTo(x, y);
2228
2229                // Draw the down arrow
2230                MoveTo(x - PWX_CROSS_SIZE, y + PWX_CROSS_SIZE);
2231                DrawTo(x, y);
2232                DrawTo(x + PWX_CROSS_SIZE, y + PWX_CROSS_SIZE);
2233            }
2234        }
2235    }
2236}
Note: See TracBrowser for help on using the repository browser.