source: git/src/printing.cc @ f809c9e

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

Add ability to export as Survex 3d

This is useful as you can filter to a subset of surveys, filter
out splays, convert from other formats the img library can read,
etc.

This is a bit rough and ready currently. Please report issues.

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