source: git/src/printwx.cc @ 1fe107a

line_contentsstereotravis-osx
Last change on this file since 1fe107a was 1fe107a, checked in by Olly Betts <olly@…>, 5 years ago

src/: Add JSON export.

  • Property mode set to 100644
File size: 58.9 KB
Line 
1/* printwx.cc */
2/* wxWidgets specific parts of Survex wxWidgets printing code */
3/* Copyright (C) 1993-2003,2004,2005,2006,2010,2011,2012,2013,2014,2015 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 "debug.h" /* for BUG and SVX_ASSERT */
45#include "export.h"
46#include "filelist.h"
47#include "filename.h"
48#include "ini.h"
49#include "message.h"
50#include "useful.h"
51
52#include "aven.h"
53#include "avenprcore.h"
54#include "mainfrm.h"
55#include "printwx.h"
56
57using namespace std;
58
59enum {
60        svx_EXPORT = 1200,
61        svx_FORMAT,
62        svx_SCALE,
63        svx_BEARING,
64        svx_TILT,
65        svx_LEGS,
66        svx_STATIONS,
67        svx_NAMES,
68        svx_XSECT,
69        svx_WALLS,
70        svx_PASSAGES,
71        svx_BORDERS,
72        svx_BLANKS,
73        svx_LEGEND,
74        svx_SURFACE,
75        svx_PLAN,
76        svx_ELEV,
77        svx_ENTS,
78        svx_FIXES,
79        svx_EXPORTS,
80        svx_PROJ_LABEL,
81        svx_PROJ,
82        svx_GRID,
83        svx_TEXT_HEIGHT,
84        svx_MARKER_SIZE,
85        svx_CENTRED,
86        svx_FULLCOORDS
87};
88
89class BitValidator : public wxValidator {
90    // Disallow assignment.
91    BitValidator & operator=(const BitValidator&);
92
93  protected:
94    int * val;
95
96    int mask;
97
98  public:
99    BitValidator(int * val_, int mask_)
100        : val(val_), mask(mask_) { }
101
102    BitValidator(const BitValidator &o) : wxValidator() {
103        Copy(o);
104    }
105
106    ~BitValidator() { }
107
108    wxObject *Clone() const { return new BitValidator(val, mask); }
109
110    bool Copy(const BitValidator& o) {
111        wxValidator::Copy(o);
112        val = o.val;
113        mask = o.mask;
114        return true;
115    }
116
117    bool Validate(wxWindow *) { return true; }
118
119    bool TransferToWindow() {
120        if (!m_validatorWindow->IsKindOf(CLASSINFO(wxCheckBox)))
121            return false;
122        ((wxCheckBox*)m_validatorWindow)->SetValue(*val & mask);
123        return true;
124    }
125
126    bool TransferFromWindow() {
127        if (!m_validatorWindow->IsKindOf(CLASSINFO(wxCheckBox)))
128            return false;
129        if (((wxCheckBox*)m_validatorWindow)->IsChecked())
130            *val |= mask;
131        else
132            *val &= ~mask;
133        return true;
134    }
135};
136
137class svxPrintout : public wxPrintout {
138    MainFrm *mainfrm;
139    layout *m_layout;
140    wxPageSetupDialogData* m_data;
141    wxDC* pdc;
142    // Currently unused, but "skip blank pages" would use it.
143    static const int cur_pass = 0;
144
145    wxPen *pen_frame, *pen_cross, *pen_surface_leg, *pen_leg;
146    wxColour colour_text, colour_labels, colour_frame, colour_leg;
147    wxColour colour_cross,colour_surface_leg;
148
149    long x_t, y_t;
150    double font_scaling_x, font_scaling_y;
151    wxFont * current_font;
152
153    int check_intersection(long x_p, long y_p);
154    void draw_info_box();
155    void draw_scale_bar(double x, double y, double MaxLength);
156    int next_page(int *pstate, char **q, int pageLim);
157    void drawticks(border clip, int tsize, int x, int y);
158
159    void MOVEMM(double X, double Y) {
160        MoveTo((long)(X * m_layout->scX), (long)(Y * m_layout->scY));
161    }
162    void DRAWMM(double X, double Y) {
163        DrawTo((long)(X * m_layout->scX), (long)(Y * m_layout->scY));
164    }
165    void MoveTo(long x, long y);
166    void DrawTo(long x, long y);
167    void DrawCross(long x, long y);
168    void SetFont(int fontcode);
169    void SetColour(int colourcode);
170    void WriteString(const wxString & s);
171    void DrawEllipse(long x, long y, long r, long R);
172    void SolidRectangle(long x, long y, long w, long h);
173    int Pre();
174    void NewPage(int pg, int pagesX, int pagesY);
175    void PlotLR(const vector<XSect> & centreline);
176    void PlotUD(const vector<XSect> & centreline);
177    char * Init(FILE **fh_list, bool fCalibrate);
178  public:
179    svxPrintout(MainFrm *mainfrm, layout *l, wxPageSetupDialogData *data, const wxString & title);
180    bool OnPrintPage(int pageNum);
181    void GetPageInfo(int *minPage, int *maxPage,
182                     int *pageFrom, int *pageTo);
183    bool HasPage(int pageNum);
184    void OnBeginPrinting();
185    void OnEndPrinting();
186};
187
188BEGIN_EVENT_TABLE(svxPrintDlg, wxDialog)
189    EVT_CHOICE(svx_FORMAT, svxPrintDlg::OnChange)
190    EVT_TEXT(svx_SCALE, svxPrintDlg::OnChange)
191    EVT_COMBOBOX(svx_SCALE, svxPrintDlg::OnChange)
192    EVT_SPINCTRL(svx_BEARING, svxPrintDlg::OnChangeSpin)
193    EVT_SPINCTRL(svx_TILT, svxPrintDlg::OnChangeSpin)
194    EVT_BUTTON(wxID_PRINT, svxPrintDlg::OnPrint)
195    EVT_BUTTON(svx_EXPORT, svxPrintDlg::OnExport)
196    EVT_BUTTON(wxID_CANCEL, svxPrintDlg::OnCancel)
197#ifdef AVEN_PRINT_PREVIEW
198    EVT_BUTTON(wxID_PREVIEW, svxPrintDlg::OnPreview)
199#endif
200    EVT_BUTTON(svx_PLAN, svxPrintDlg::OnPlan)
201    EVT_BUTTON(svx_ELEV, svxPrintDlg::OnElevation)
202    EVT_UPDATE_UI(svx_PLAN, svxPrintDlg::OnPlanUpdate)
203    EVT_UPDATE_UI(svx_ELEV, svxPrintDlg::OnElevationUpdate)
204    EVT_CHECKBOX(svx_LEGS, svxPrintDlg::OnChange)
205    EVT_CHECKBOX(svx_STATIONS, svxPrintDlg::OnChange)
206    EVT_CHECKBOX(svx_NAMES, svxPrintDlg::OnChange)
207    EVT_CHECKBOX(svx_SURFACE, svxPrintDlg::OnChange)
208    EVT_CHECKBOX(svx_ENTS, svxPrintDlg::OnChange)
209    EVT_CHECKBOX(svx_FIXES, svxPrintDlg::OnChange)
210    EVT_CHECKBOX(svx_EXPORTS, svxPrintDlg::OnChange)
211END_EVENT_TABLE()
212
213static wxString scales[] = {
214    wxT(""),
215    wxT("25"),
216    wxT("50"),
217    wxT("100"),
218    wxT("250"),
219    wxT("500"),
220    wxT("1000"),
221    wxT("2500"),
222    wxT("5000"),
223    wxT("10000"),
224    wxT("25000"),
225    wxT("50000"),
226    wxT("100000")
227};
228
229static wxString formats[] = {
230    wxT("DXF"),
231    wxT("EPS"),
232    wxT("GPX"),
233    wxT("HPGL"),
234    wxT("JSON"),
235    wxT("KML"),
236    wxT("Plot"),
237    wxT("Skencil"),
238    wxT("SVG")
239};
240
241#if 0
242static wxString projs[] = {
243    /* CUCC Austria: */
244    wxT("+proj=tmerc +lat_0=0 +lon_0=13d20 +k=1 +x_0=0 +y_0=-5200000 +ellps=bessel +towgs84=577.326,90.129,463.919,5.137,1.474,5.297,2.4232"),
245    /* British grid SD (Yorkshire): */
246    wxT("+proj=tmerc +lat_0=49d +lon_0=-2d +k=0.999601 +x_0=100000 +y_0=-500000 +ellps=airy +towgs84=375,-111,431,0,0,0,0"),
247    /* British full grid reference: */
248    wxT("+proj=tmerc +lat_0=49d +lon_0=-2d +k=0.999601 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=375,-111,431,0,0,0,0")
249};
250#endif
251
252static unsigned format_info[] = {
253    LABELS|LEGS|SURF|STNS|PASG|XSECT|WALLS|MARKER_SIZE|TEXT_HEIGHT|GRID|FULL_COORDS,
254    LABELS|LEGS|SURF|STNS,
255    LABELS|LEGS|SURF|ENTS|FIXES|EXPORTS|PROJ|EXPORT_3D,
256    LABELS|LEGS|SURF|STNS|CENTRED,
257    LEGS|CENTRED|EXPORT_3D,
258    LABELS|ENTS|FIXES|EXPORTS|PROJ|EXPORT_3D,
259    LABELS|LEGS|SURF,
260    LABELS|LEGS|SURF|STNS|MARKER_SIZE|GRID|SCALE,
261    LABELS|LEGS|SURF|STNS|PASG|XSECT|WALLS|MARKER_SIZE|TEXT_HEIGHT|SCALE
262};
263
264static const char * extension[] = {
265    ".dxf",
266    ".eps",
267    ".gpx",
268    ".hpgl",
269    ".json",
270    ".kml",
271    ".plt",
272    ".sk",
273    ".svg"
274};
275
276static int msg_filetype[] = {
277    /*DXF files*/411,
278    /*EPS files*/412,
279    /*GPX files*/413,
280    /* TRANSLATORS: Here "plotter" refers to a machine which draws a printout
281     * on a (usually large) sheet of paper using a pen mounted in a motorised
282     * mechanism. */
283    /*HPGL for plotters*/414,
284    /*JSON files*/445,
285    /*KML files*/444,
286    /* TRANSLATORS: "Compass" and "Carto" are the names of software packages,
287     * so should not be translated:
288     * http://www.fountainware.com/compass/
289     * http://www.psc-cavers.org/carto/ */
290    /*Compass PLT for use with Carto*/415,
291    /* TRANSLATORS: "Skencil" is the name of a software package, so should not be
292     * translated: http://www.skencil.org/ */
293    /*Skencil files*/416,
294    /*SVG files*/417
295};
296
297// there are three jobs to do here...
298// User <-> wx - this should possibly be done in a separate file
299svxPrintDlg::svxPrintDlg(MainFrm* mainfrm_, const wxString & filename,
300                         const wxString & title, const wxString & cs_proj,
301                         const wxString & datestamp, time_t datestamp_numeric,
302                         double angle, double tilt_angle,
303                         bool labels, bool crosses, bool legs, bool surf,
304                         bool tubes, bool ents, bool fixes, bool exports,
305                         bool printing, bool close_after_)
306        : wxDialog(mainfrm_, -1, wxString(printing ?
307                                          /* TRANSLATORS: Title of the print
308                                           * dialog */
309                                          wmsg(/*Print*/399) :
310                                          /* TRANSLATORS: Title of the export
311                                           * dialog */
312                                          wmsg(/*Export*/383))),
313          m_layout(printing ? wxGetApp().GetPageSetupDialogData() : NULL),
314          m_File(filename), mainfrm(mainfrm_), close_after(close_after_)
315{
316    m_scale = NULL;
317    m_printSize = NULL;
318    m_bearing = NULL;
319    m_tilt = NULL;
320    m_format = NULL;
321    int show_mask = 0;
322    if (labels)
323        show_mask |= LABELS;
324    if (crosses)
325        show_mask |= STNS;
326    if (legs)
327        show_mask |= LEGS;
328    if (surf)
329        show_mask |= SURF;
330    if (tubes)
331        show_mask |= XSECT|WALLS|PASG;
332    if (ents)
333        show_mask |= ENTS;
334    if (fixes)
335        show_mask |= FIXES;
336    if (exports)
337        show_mask |= EXPORTS;
338    m_layout.show_mask = show_mask;
339    m_layout.datestamp = datestamp;
340    m_layout.datestamp_numeric = datestamp_numeric;
341    m_layout.rot = int(angle);
342    m_layout.title = title;
343    m_layout.cs_proj = cs_proj;
344    if (mainfrm->IsExtendedElevation()) {
345        m_layout.view = layout::EXTELEV;
346        if (m_layout.rot != 0 && m_layout.rot != 180) m_layout.rot = 0;
347        m_layout.tilt = 0;
348    } else {
349        // FIXME rot and tilt shouldn't be integers.
350        m_layout.tilt = int(tilt_angle);
351        if (m_layout.tilt == -90) {
352            m_layout.view = layout::PLAN;
353        } else if (m_layout.tilt == 0) {
354            m_layout.view = layout::ELEV;
355        } else {
356            m_layout.view = layout::TILT;
357        }
358    }
359
360    /* setup our print dialog*/
361    wxBoxSizer* v1 = new wxBoxSizer(wxVERTICAL);
362    wxBoxSizer* h1 = new wxBoxSizer(wxHORIZONTAL); // holds controls
363    /* TRANSLATORS: Used as a label for the surrounding box for the "Bearing"
364     * and "Tilt angle" fields, and the "Plan view" and "Elevation" buttons in
365     * the "what to print/export" dialog. */
366    m_viewbox = new wxStaticBoxSizer(new wxStaticBox(this, -1, wmsg(/*View*/283)), wxVERTICAL);
367    /* TRANSLATORS: Used as a label for the surrounding box for the "survey
368     * legs" "stations" "names" etc checkboxes in the "what to print" dialog.
369     * "Elements" isn’t a good name for this but nothing better has yet come to
370     * mind! */
371    wxBoxSizer* v3 = new wxStaticBoxSizer(new wxStaticBox(this, -1, wmsg(/*Elements*/256)), wxVERTICAL);
372    wxBoxSizer* h2 = new wxBoxSizer(wxHORIZONTAL);
373    wxBoxSizer* h3 = new wxBoxSizer(wxHORIZONTAL); // holds buttons
374
375    if (!printing) {
376        wxStaticText* label;
377        label = new wxStaticText(this, -1, wxString(wmsg(/*Export format*/410)));
378        const size_t n_formats = sizeof(formats) / sizeof(formats[0]);
379        m_format = new wxChoice(this, svx_FORMAT,
380                                wxDefaultPosition, wxDefaultSize,
381                                n_formats, formats);
382        unsigned current_format = 0;
383        wxConfigBase * cfg = wxConfigBase::Get();
384        wxString s;
385        if (cfg->Read(wxT("export_format"), &s, wxString())) {
386            for (unsigned i = 0; i != n_formats; ++i) {
387                if (s == formats[i]) {
388                    current_format = i;
389                    break;
390                }
391            }
392        }
393        m_format->SetSelection(current_format);
394        wxBoxSizer* formatbox = new wxBoxSizer(wxHORIZONTAL);
395        formatbox->Add(label, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
396        formatbox->Add(m_format, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
397
398        v1->Add(formatbox, 0, wxALIGN_LEFT|wxALL, 0);
399    }
400
401    wxStaticText* label;
402    label = new wxStaticText(this, -1, wxString(wmsg(/*Scale*/154)) + wxT(" 1:"));
403    if (scales[0].empty()) {
404        if (printing) {
405            /* TRANSLATORS: used in the scale drop down selector in the print
406             * dialog the implicit meaning is "choose a suitable scale to fit
407             * the plot on a single page", but we need something shorter */
408            scales[0].assign(wmsg(/*One page*/258));
409        } else {
410            scales[0].assign(wxT("1000"));
411        }
412    }
413    m_scale = new wxComboBox(this, svx_SCALE, scales[0], wxDefaultPosition,
414                             wxDefaultSize, sizeof(scales) / sizeof(scales[0]),
415                             scales);
416    m_scalebox = new wxBoxSizer(wxHORIZONTAL);
417    m_scalebox->Add(label, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
418    m_scalebox->Add(m_scale, 0, wxALIGN_CENTER_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    /* FIXME:
431     * svx_GRID, // double - spacing, default: 100m
432     * svx_TEXT_HEIGHT, // default 0.6
433     * svx_MARKER_SIZE // default 0.8
434     */
435
436    if (m_layout.view != layout::EXTELEV) {
437        wxFlexGridSizer* anglebox = new wxFlexGridSizer(2);
438        wxStaticText * brg_label, * tilt_label;
439        brg_label = new wxStaticText(this, -1, wmsg(/*Bearing*/259));
440        anglebox->Add(brg_label, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_LEFT|wxALL, 5);
441        m_bearing = new wxSpinCtrl(this, svx_BEARING);
442        m_bearing->SetRange(0, 359);
443        anglebox->Add(m_bearing, 0, wxALIGN_CENTER|wxALL, 5);
444        /* TRANSLATORS: Used in the print dialog: */
445        tilt_label = new wxStaticText(this, -1, wmsg(/*Tilt angle*/263));
446        anglebox->Add(tilt_label, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_LEFT|wxALL, 5);
447        m_tilt = new wxSpinCtrl(this, svx_TILT);
448        m_tilt->SetRange(-90, 90);
449        anglebox->Add(m_tilt, 0, wxALIGN_CENTER|wxALL, 5);
450
451        m_viewbox->Add(anglebox, 0, wxALIGN_LEFT|wxALL, 0);
452
453        wxBoxSizer * planelevsizer = new wxBoxSizer(wxHORIZONTAL);
454        planelevsizer->Add(new wxButton(this, svx_PLAN, wmsg(/*P&lan view*/117)),
455                           0, wxALIGN_CENTRE_VERTICAL|wxALL, 5);
456        planelevsizer->Add(new wxButton(this, svx_ELEV, wmsg(/*&Elevation*/285)),
457                           0, wxALIGN_CENTRE_VERTICAL|wxALL, 5);
458
459        m_viewbox->Add(planelevsizer, 0, wxALIGN_LEFT|wxALL, 5);
460    }
461
462    /* TRANSLATORS: Here a "survey leg" is a set of measurements between two
463     * "survey stations". */
464    v3->Add(new wxCheckBox(this, svx_LEGS, wmsg(/*Underground Survey Legs*/262),
465                           wxDefaultPosition, wxDefaultSize, 0,
466                           BitValidator(&m_layout.show_mask, LEGS)),
467            0, wxALIGN_LEFT|wxALL, 2);
468    /* TRANSLATORS: Here a "survey leg" is a set of measurements between two
469     * "survey stations". */
470    v3->Add(new wxCheckBox(this, svx_SURFACE, wmsg(/*Sur&face Survey Legs*/403),
471                           wxDefaultPosition, wxDefaultSize, 0,
472                           BitValidator(&m_layout.show_mask, SURF)),
473            0, wxALIGN_LEFT|wxALL, 2);
474    v3->Add(new wxCheckBox(this, svx_STATIONS, wmsg(/*Crosses*/261),
475                           wxDefaultPosition, wxDefaultSize, 0,
476                           BitValidator(&m_layout.show_mask, STNS)),
477            0, wxALIGN_LEFT|wxALL, 2);
478    v3->Add(new wxCheckBox(this, svx_NAMES, wmsg(/*Station Names*/260),
479                           wxDefaultPosition, wxDefaultSize, 0,
480                           BitValidator(&m_layout.show_mask, LABELS)),
481            0, wxALIGN_LEFT|wxALL, 2);
482    v3->Add(new wxCheckBox(this, svx_ENTS, wmsg(/*Entrances*/418),
483                           wxDefaultPosition, wxDefaultSize, 0,
484                           BitValidator(&m_layout.show_mask, ENTS)),
485            0, wxALIGN_LEFT|wxALL, 2);
486    v3->Add(new wxCheckBox(this, svx_FIXES, wmsg(/*Fixed Points*/419),
487                           wxDefaultPosition, wxDefaultSize, 0,
488                           BitValidator(&m_layout.show_mask, FIXES)),
489            0, wxALIGN_LEFT|wxALL, 2);
490    v3->Add(new wxCheckBox(this, svx_EXPORTS, wmsg(/*Exported Stations*/420),
491                           wxDefaultPosition, wxDefaultSize, 0,
492                           BitValidator(&m_layout.show_mask, EXPORTS)),
493            0, wxALIGN_LEFT|wxALL, 2);
494    v3->Add(new wxCheckBox(this, svx_XSECT, wmsg(/*Cross-sections*/393),
495                           wxDefaultPosition, wxDefaultSize, 0,
496                           BitValidator(&m_layout.show_mask, XSECT)),
497            0, wxALIGN_LEFT|wxALL, 2);
498    if (!printing) {
499        v3->Add(new wxCheckBox(this, svx_WALLS, wmsg(/*Walls*/394),
500                               wxDefaultPosition, wxDefaultSize, 0,
501                               BitValidator(&m_layout.show_mask, WALLS)),
502                0, wxALIGN_LEFT|wxALL, 2);
503        v3->Add(new wxCheckBox(this, svx_PASSAGES, wmsg(/*Passages*/395),
504                               wxDefaultPosition, wxDefaultSize, 0,
505                               BitValidator(&m_layout.show_mask, PASG)),
506                0, wxALIGN_LEFT|wxALL, 2);
507        v3->Add(new wxCheckBox(this, svx_CENTRED, wmsg(/*Origin in centre*/421),
508                               wxDefaultPosition, wxDefaultSize, 0,
509                               BitValidator(&m_layout.show_mask, CENTRED)),
510                0, wxALIGN_LEFT|wxALL, 2);
511        v3->Add(new wxCheckBox(this, svx_FULLCOORDS, wmsg(/*Full coordinates*/422),
512                               wxDefaultPosition, wxDefaultSize, 0,
513                               BitValidator(&m_layout.show_mask, FULL_COORDS)),
514                0, wxALIGN_LEFT|wxALL, 2);
515    }
516    if (printing) {
517        /* TRANSLATORS: used in the print dialog - controls drawing lines
518         * around each page */
519        v3->Add(new wxCheckBox(this, svx_BORDERS, wmsg(/*Page Borders*/264),
520                               wxDefaultPosition, wxDefaultSize, 0,
521                               wxGenericValidator(&m_layout.Border)),
522                0, wxALIGN_LEFT|wxALL, 2);
523        /* TRANSLATORS: will be used in the print dialog - check this to print
524         * blank pages (otherwise they’ll be skipped to save paper) */
525//      m_blanks = new wxCheckBox(this, svx_BLANKS, wmsg(/*Blank Pages*/266));
526//      v3->Add(m_blanks, 0, wxALIGN_LEFT|wxALL, 2);
527        /* TRANSLATORS: As in the legend on a map.  Used in the print dialog -
528         * controls drawing the box at the lower left with survey name, view
529         * angles, etc */
530        v3->Add(new wxCheckBox(this, svx_LEGEND, wmsg(/*Legend*/265),
531                               wxDefaultPosition, wxDefaultSize, 0,
532                               wxGenericValidator(&m_layout.Legend)),
533                0, wxALIGN_LEFT|wxALL, 2);
534    }
535
536    h1->Add(v3, 0, wxALIGN_LEFT|wxALL, 5);
537    h1->Add(m_viewbox, 0, wxALIGN_LEFT|wxLEFT, 5);
538
539    /* TRANSLATORS: The PROJ library is used to do coordinate transformations
540     * (https://trac.osgeo.org/proj/) - if the .3d file doesn't contain details
541     * of the coordinate projection in use, the user must specify it here for
542     * export formats which need to know it (e.g. GPX).
543     */
544    h2->Add(new wxStaticText(this, svx_PROJ_LABEL, wmsg(/*Coordinate projection*/440)),
545            0, wxLEFT|wxALIGN_CENTRE_VERTICAL, 5);
546    long style = 0;
547    if (!m_layout.cs_proj.empty()) {
548        // If the input file specified the coordinate system, don't let the
549        // user mess with it.
550        style = wxTE_READONLY;
551    } else {
552#if 0 // FIXME: Is it a good idea to save this?
553        wxConfigBase * cfg = wxConfigBase::Get();
554        wxString input_projection;
555        cfg->Read(wxT("input_projection"), &input_projection);
556        if (!input_projection.empty())
557            proj_edit.SetValue(input_projection);
558#endif
559    }
560    wxTextCtrl * proj_edit = new wxTextCtrl(this, svx_PROJ, m_layout.cs_proj,
561                                            wxDefaultPosition, wxDefaultSize,
562                                            style);
563    h2->Add(proj_edit, 1, wxALL|wxEXPAND|wxALIGN_CENTRE_VERTICAL, 5);
564    v1->Add(h2, 0, wxALIGN_LEFT|wxEXPAND, 5);
565
566    v1->Add(h1, 0, wxALIGN_LEFT|wxALL, 5);
567
568    // When we enable/disable checkboxes in the export dialog, ideally we'd
569    // like the dialog to resize, but not sure how to achieve that, so we
570    // add a stretchable spacer here so at least the buttons stay in the
571    // lower right corner.
572    v1->AddStretchSpacer();
573
574    wxButton * but;
575    but = new wxButton(this, wxID_CANCEL);
576    h3->Add(but, 0, wxALIGN_RIGHT|wxALL, 5);
577    if (printing) {
578#ifdef AVEN_PRINT_PREVIEW
579        but = new wxButton(this, wxID_PREVIEW);
580        h3->Add(but, 0, wxALIGN_RIGHT|wxALL, 5);
581        but = new wxButton(this, wxID_PRINT);
582#else
583        but = new wxButton(this, wxID_PRINT, wmsg(/*&Print…*/400));
584#endif
585    } else {
586        /* TRANSLATORS: The text on the action button in the "Export" settings
587         * dialog */
588        but = new wxButton(this, svx_EXPORT, wmsg(/*&Export…*/230));
589    }
590    but->SetDefault();
591    h3->Add(but, 0, wxALIGN_RIGHT|wxALL, 5);
592    v1->Add(h3, 0, wxALIGN_RIGHT|wxALL, 5);
593
594    SetAutoLayout(true);
595    SetSizer(v1);
596    v1->SetSizeHints(this);
597
598    LayoutToUI();
599    SomethingChanged(0);
600}
601
602void
603svxPrintDlg::OnPrint(wxCommandEvent&) {
604    SomethingChanged(0);
605    TransferDataFromWindow();
606    wxPageSetupDialogData * psdd = wxGetApp().GetPageSetupDialogData();
607    wxPrintDialogData pd(psdd->GetPrintData());
608    wxPrinter pr(&pd);
609    svxPrintout po(mainfrm, &m_layout, psdd, m_File);
610    if (pr.Print(this, &po, true)) {
611        // Close the print dialog if printing succeeded.
612        Destroy();
613    }
614}
615
616void
617svxPrintDlg::OnExport(wxCommandEvent&) {
618    UIToLayout();
619    TransferDataFromWindow();
620    wxString leaf;
621    wxFileName::SplitPath(m_File, NULL, NULL, &leaf, NULL, wxPATH_NATIVE);
622    unsigned format_idx = ((wxChoice*)FindWindow(svx_FORMAT))->GetSelection();
623    leaf += wxString::FromUTF8(extension[format_idx]);
624
625    wxString filespec = wmsg(msg_filetype[format_idx]);
626    filespec += wxT("|*");
627    filespec += wxString::FromUTF8(extension[format_idx]);
628    filespec += wxT("|");
629    filespec += wmsg(/*All files*/208);
630    filespec += wxT("|");
631    filespec += wxFileSelectorDefaultWildcardStr;
632
633    /* TRANSLATORS: Title of file dialog to choose name and type of exported
634     * file. */
635    wxFileDialog dlg(this, wmsg(/*Export as:*/401), wxString(), leaf,
636                     filespec, wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
637    if (dlg.ShowModal() == wxID_OK) {
638        wxString input_projection = ((wxTextCtrl*)FindWindow(svx_PROJ))->GetValue();
639        double grid = 100; // metres
640        double text_height = 0.6;
641        double marker_size = 0.8;
642
643        try {
644            if (!Export(dlg.GetPath(), m_layout.title,
645                        m_layout.datestamp, m_layout.datestamp_numeric, mainfrm,
646                        m_layout.rot, m_layout.tilt, m_layout.show_mask,
647                        export_format(format_idx), input_projection.mb_str(),
648                        grid, text_height, marker_size, m_layout.Scale)) {
649                wxString m = wxString::Format(wmsg(/*Couldn’t write file “%s”*/402).c_str(),
650                                              m_File.c_str());
651                wxGetApp().ReportError(m);
652            }
653        } catch (const wxString & m) {
654            wxGetApp().ReportError(m);
655        }
656    }
657    Destroy();
658}
659
660#ifdef AVEN_PRINT_PREVIEW
661void
662svxPrintDlg::OnPreview(wxCommandEvent&) {
663    SomethingChanged(0);
664    TransferDataFromWindow();
665    wxPageSetupDialogData * psdd = wxGetApp().GetPageSetupDialogData();
666    wxPrintDialogData pd(psdd->GetPrintData());
667    wxPrintPreview* pv;
668    pv = new wxPrintPreview(new svxPrintout(mainfrm, &m_layout, psdd, m_File),
669                            new svxPrintout(mainfrm, &m_layout, psdd, m_File),
670                            &pd);
671    // TRANSLATORS: Title of the print preview dialog
672    wxPreviewFrame *frame = new wxPreviewFrame(pv, mainfrm, wmsg(/*Print Preview*/398));
673    frame->Initialize();
674
675    // Size preview frame so that all of the controlbar and canvas can be seen
676    // if possible.
677    int w, h;
678    // GetBestSize gives us the width needed to show the whole controlbar.
679    frame->GetBestSize(&w, &h);
680#ifdef __WXMAC__
681    // wxMac opens the preview window at minimum size by default.
682    // 360x480 is apparently enough to show A4 portrait.
683    if (h < 480 || w < 360) {
684        if (h < 480) h = 480;
685        if (w < 360) w = 360;
686    }
687#else
688    if (h < w) {
689        // On wxGTK at least, GetBestSize() returns much too small a height.
690        h = w * 6 / 5;
691    }
692#endif
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);
711    SomethingChanged(svx_TILT);
712}
713
714void
715svxPrintDlg::OnElevation(wxCommandEvent&) {
716    m_tilt->SetValue(0);
717    SomethingChanged(svx_TILT);
718}
719
720void
721svxPrintDlg::OnPlanUpdate(wxUpdateUIEvent& e) {
722    e.Enable(m_tilt->GetValue() != -90);
723}
724
725void
726svxPrintDlg::OnElevationUpdate(wxUpdateUIEvent& e) {
727    e.Enable(m_tilt->GetValue() != 0);
728}
729
730void
731svxPrintDlg::OnChangeSpin(wxSpinEvent& e) {
732    SomethingChanged(e.GetId());
733}
734
735void
736svxPrintDlg::OnChange(wxCommandEvent& e) {
737    SomethingChanged(e.GetId());
738}
739
740void
741svxPrintDlg::OnCancel(wxCommandEvent&) {
742    if (close_after)
743        mainfrm->Close();
744    Destroy();
745}
746
747void
748svxPrintDlg::SomethingChanged(int control_id) {
749    if ((control_id == 0 || control_id == svx_FORMAT) && m_format) {
750        // Update the shown/hidden fields for the newly selected export filter.
751        int new_filter_idx = m_format->GetSelection();
752        if (new_filter_idx != wxNOT_FOUND) {
753            unsigned mask = format_info[new_filter_idx];
754            static const struct { int id; unsigned mask; } controls[] = {
755                { svx_LEGS, LEGS },
756                { svx_SURFACE, SURF },
757                { svx_STATIONS, STNS },
758                { svx_NAMES, LABELS },
759                { svx_XSECT, XSECT },
760                { svx_WALLS, WALLS },
761                { svx_PASSAGES, PASG },
762                { svx_ENTS, ENTS },
763                { svx_FIXES, FIXES },
764                { svx_EXPORTS, EXPORTS },
765                { svx_CENTRED, CENTRED },
766                { svx_FULLCOORDS, FULL_COORDS },
767                { svx_PROJ_LABEL, PROJ },
768                { svx_PROJ, PROJ },
769            };
770            static unsigned n_controls = sizeof(controls) / sizeof(controls[0]);
771            for (unsigned i = 0; i != n_controls; ++i) {
772                wxWindow * control = FindWindow(controls[i].id);
773                if (control) control->Show(mask & controls[i].mask);
774            }
775            m_scalebox->Show(bool(mask & SCALE));
776            m_viewbox->Show(!bool(mask & EXPORT_3D));
777            GetSizer()->Layout();
778            if (control_id == svx_FORMAT) {
779                wxConfigBase * cfg = wxConfigBase::Get();
780                cfg->Write(wxT("export_format"), formats[new_filter_idx]);
781            }
782        }
783    }
784
785    UIToLayout();
786
787    if (m_printSize || m_scale) {
788        // Update the bounding box.
789        RecalcBounds();
790
791        if (m_scale) {
792            (m_scale->GetValue()).ToDouble(&(m_layout.Scale));
793            if (m_layout.Scale == 0.0) {
794                m_layout.pick_scale(1, 1);
795            }
796        }
797    }
798
799    if (m_printSize && m_layout.xMax >= m_layout.xMin) {
800        m_layout.pages_required();
801        m_printSize->SetLabel(wxString::Format(wmsg(/*%d pages (%dx%d)*/257), m_layout.pages, m_layout.pagesX, m_layout.pagesY));
802    }
803}
804
805void
806svxPrintDlg::LayoutToUI(){
807//    m_blanks->SetValue(m_layout.SkipBlank);
808    if (m_layout.view != layout::EXTELEV) {
809        m_tilt->SetValue(m_layout.tilt);
810        m_bearing->SetValue(m_layout.rot);
811    }
812
813    // Do this last as it causes an OnChange message which calls UIToLayout
814    if (m_scale) {
815        if (m_layout.Scale != 0) {
816            wxString temp;
817            temp << m_layout.Scale;
818            m_scale->SetValue(temp);
819        } else {
820            if (scales[0].empty()) scales[0].assign(wmsg(/*One page*/258));
821            m_scale->SetValue(scales[0]);
822        }
823    }
824}
825
826void
827svxPrintDlg::UIToLayout(){
828//    m_layout.SkipBlank = m_blanks->IsChecked();
829
830    if (m_layout.view != layout::EXTELEV && m_tilt) {
831        m_layout.tilt = m_tilt->GetValue();
832        if (m_layout.tilt == -90) {
833            m_layout.view = layout::PLAN;
834        } else if (m_layout.tilt == 0) {
835            m_layout.view = layout::ELEV;
836        } else {
837            m_layout.view = layout::TILT;
838        }
839
840        bool enable_passage_opts = (m_layout.view != layout::TILT);
841        wxWindow * win;
842        win = FindWindow(svx_XSECT);
843        if (win) win->Enable(enable_passage_opts);
844        win = FindWindow(svx_WALLS);
845        if (win) win->Enable(enable_passage_opts);
846        win = FindWindow(svx_PASSAGES);
847        if (win) win->Enable(enable_passage_opts);
848
849        m_layout.rot = m_bearing->GetValue();
850    }
851}
852
853void
854svxPrintDlg::RecalcBounds()
855{
856    m_layout.yMax = m_layout.xMax = -DBL_MAX;
857    m_layout.yMin = m_layout.xMin = DBL_MAX;
858
859    double SIN = sin(rad(m_layout.rot));
860    double COS = cos(rad(m_layout.rot));
861    double SINT = sin(rad(m_layout.tilt));
862    double COST = cos(rad(m_layout.tilt));
863
864    if (m_layout.show_mask & LEGS) {
865        list<traverse>::const_iterator trav = mainfrm->traverses_begin();
866        list<traverse>::const_iterator tend = mainfrm->traverses_end();
867        for ( ; trav != tend; ++trav) {
868            vector<PointInfo>::const_iterator pos = trav->begin();
869            vector<PointInfo>::const_iterator end = trav->end();
870            for ( ; pos != end; ++pos) {
871                double x = pos->GetX();
872                double y = pos->GetY();
873                double z = pos->GetZ();
874                double X = x * COS - y * SIN;
875                if (X > m_layout.xMax) m_layout.xMax = X;
876                if (X < m_layout.xMin) m_layout.xMin = X;
877                double Y = z * COST - (x * SIN + y * COS) * SINT;
878                if (Y > m_layout.yMax) m_layout.yMax = Y;
879                if (Y < m_layout.yMin) m_layout.yMin = Y;
880            }
881        }
882    }
883    if (m_layout.show_mask & SURF) {
884        list<traverse>::const_iterator trav = mainfrm->surface_traverses_begin();
885        list<traverse>::const_iterator tend = mainfrm->surface_traverses_end();
886        for ( ; trav != tend; ++trav) {
887            vector<PointInfo>::const_iterator pos = trav->begin();
888            vector<PointInfo>::const_iterator end = trav->end();
889            for ( ; pos != end; ++pos) {
890                double x = pos->GetX();
891                double y = pos->GetY();
892                double z = pos->GetZ();
893                double X = x * COS - y * SIN;
894                if (X > m_layout.xMax) m_layout.xMax = X;
895                if (X < m_layout.xMin) m_layout.xMin = X;
896                double Y = z * COST - (x * SIN + y * COS) * SINT;
897                if (Y > m_layout.yMax) m_layout.yMax = Y;
898                if (Y < m_layout.yMin) m_layout.yMin = Y;
899            }
900        }
901    }
902    if (m_layout.show_mask & (LABELS|STNS)) {
903        list<LabelInfo*>::const_iterator label = mainfrm->GetLabels();
904        while (label != mainfrm->GetLabelsEnd()) {
905            double x = (*label)->GetX();
906            double y = (*label)->GetY();
907            double z = (*label)->GetZ();
908            if ((m_layout.show_mask & SURF) || (*label)->IsUnderground()) {
909                double X = x * COS - y * SIN;
910                if (X > m_layout.xMax) m_layout.xMax = X;
911                if (X < m_layout.xMin) m_layout.xMin = X;
912                double Y = z * COST - (x * SIN + y * COS) * SINT;
913                if (Y > m_layout.yMax) m_layout.yMax = Y;
914                if (Y < m_layout.yMin) m_layout.yMin = Y;
915            }
916            ++label;
917        }
918    }
919}
920
921static int xpPageWidth, ypPageDepth;
922static long MarginLeft, MarginRight, MarginTop, MarginBottom;
923static long x_offset, y_offset;
924static wxFont *font_labels, *font_default;
925static int fontsize, fontsize_labels;
926
927/* FIXME: allow the font to be set */
928
929static const char *fontname = "Arial", *fontname_labels = "Arial";
930
931// wx <-> prcore (calls to print_page etc...)
932svxPrintout::svxPrintout(MainFrm *mainfrm_, layout *l,
933                         wxPageSetupDialogData *data, const wxString & title)
934    : wxPrintout(title)
935{
936    mainfrm = mainfrm_;
937    m_layout = l;
938    m_data = data;
939}
940
941void
942svxPrintout::draw_info_box()
943{
944   layout *l = m_layout;
945   int boxwidth = 70;
946   int boxheight = 30;
947
948   SetColour(PR_COLOUR_FRAME);
949
950   int div = boxwidth;
951   if (l->view != layout::EXTELEV) {
952      boxwidth += boxheight;
953      MOVEMM(div, boxheight);
954      DRAWMM(div, 0);
955      MOVEMM(0, 30); DRAWMM(div, 30);
956   }
957
958   MOVEMM(0, boxheight);
959   DRAWMM(boxwidth, boxheight);
960   DRAWMM(boxwidth, 0);
961   if (!l->Border) {
962      DRAWMM(0, 0);
963      DRAWMM(0, boxheight);
964   }
965
966   MOVEMM(0, 20); DRAWMM(div, 20);
967   MOVEMM(0, 10); DRAWMM(div, 10);
968
969   switch (l->view) {
970    case layout::PLAN: {
971      long ax, ay, bx, by, cx, cy, dx, dy;
972
973      long xc = boxwidth - boxheight / 2;
974      long yc = boxheight / 2;
975      const double RADIUS = boxheight / 3;
976      DrawEllipse(long(xc * l->scX), long(yc * l->scY),
977                  long(RADIUS * l->scX), long(RADIUS * l->scY));
978
979      ax = (long)((xc - (RADIUS - 1) * sin(rad(000.0 + l->rot))) * l->scX);
980      ay = (long)((yc + (RADIUS - 1) * cos(rad(000.0 + l->rot))) * l->scY);
981      bx = (long)((xc - RADIUS * 0.5 * sin(rad(180.0 + l->rot))) * l->scX);
982      by = (long)((yc + RADIUS * 0.5 * cos(rad(180.0 + l->rot))) * l->scY);
983      cx = (long)((xc - (RADIUS - 1) * sin(rad(160.0 + l->rot))) * l->scX);
984      cy = (long)((yc + (RADIUS - 1) * cos(rad(160.0 + l->rot))) * l->scY);
985      dx = (long)((xc - (RADIUS - 1) * sin(rad(200.0 + l->rot))) * l->scX);
986      dy = (long)((yc + (RADIUS - 1) * cos(rad(200.0 + l->rot))) * l->scY);
987
988      MoveTo(ax, ay);
989      DrawTo(bx, by);
990      DrawTo(cx, cy);
991      DrawTo(ax, ay);
992      DrawTo(dx, dy);
993      DrawTo(bx, by);
994
995      SetColour(PR_COLOUR_TEXT);
996      MOVEMM(div + 0.5, boxheight - 5.5);
997      WriteString(wmsg(/*North*/115));
998
999      wxString angle;
1000      angle.Printf(wxT("%03d"), l->rot);
1001      angle += wmsg(/*°*/344);
1002      wxString s;
1003      /* TRANSLATORS: This is used on printouts of plans, with %s replaced by
1004       * something like "123°".  The bearing is up the page. */
1005      s.Printf(wmsg(/*Plan view, %s up page*/168), angle.c_str());
1006      MOVEMM(2, 12); WriteString(s);
1007      break;
1008    }
1009    case layout::ELEV: case layout::TILT: {
1010      const int L = div + 2;
1011      const int R = boxwidth - 2;
1012      const int H = boxheight / 2;
1013      MOVEMM(L, H); DRAWMM(L + 5, H - 3); DRAWMM(L + 3, H); DRAWMM(L + 5, H + 3);
1014
1015      DRAWMM(L, H); DRAWMM(R, H);
1016
1017      DRAWMM(R - 5, H + 3); DRAWMM(R - 3, H); DRAWMM(R - 5, H - 3); DRAWMM(R, H);
1018
1019      MOVEMM((L + R) / 2, H - 2); DRAWMM((L + R) / 2, H + 2);
1020
1021      SetColour(PR_COLOUR_TEXT);
1022      MOVEMM(div + 2, boxheight - 8);
1023      /* TRANSLATORS: "Elevation on" 020 <-> 200 degrees */
1024      WriteString(wmsg(/*Elevation on*/116));
1025     
1026      MOVEMM(L, 2);
1027      WriteString(wxString::Format(wxT("%03d%s"),
1028                                   (l->rot + 270) % 360,
1029                                   wmsg(/*°*/344).c_str()));
1030      MOVEMM(R - 10, 2);
1031      WriteString(wxString::Format(wxT("%03d%s"),
1032                                   (l->rot + 90) % 360,
1033                                   wmsg(/*°*/344).c_str()));
1034
1035      wxString angle;
1036      angle.Printf(wxT("%03d"), l->rot);
1037      angle += wmsg(/*°*/344);
1038      wxString s;
1039      if (l->view == layout::ELEV) {
1040          /* TRANSLATORS: This is used on printouts of elevations, with %s
1041           * replaced by something like "123°".  The bearing is the direction
1042           * we’re looking. */
1043          s.Printf(wmsg(/*Elevation facing %s*/169), angle.c_str());
1044      } else {
1045          wxString a2;
1046          a2.Printf(wxT("%d"), l->tilt);
1047          a2 += wmsg(/*°*/344);
1048          /* TRANSLATORS: This is used on printouts of tilted elevations, with
1049           * the first %s replaced by something like "123°", and the second by
1050           * something like "-45°".  The bearing is the direction we’re
1051           * looking. */
1052          s.Printf(wmsg(/*Elevation facing %s, tilted %s*/284), angle.c_str(), a2.c_str());
1053      }
1054      MOVEMM(2, 12); WriteString(s);
1055      break;
1056    }
1057    case layout::EXTELEV:
1058      SetColour(PR_COLOUR_TEXT);
1059      MOVEMM(2, 12);
1060      /* TRANSLATORS: This is used on printouts of extended elevations. */
1061      WriteString(wmsg(/*Extended elevation*/191));
1062      break;
1063   }
1064
1065   MOVEMM(2, boxheight - 8); WriteString(l->title);
1066
1067   MOVEMM(2, 2);
1068   // FIXME: "Original Scale" better?
1069   WriteString(wxString::Format(wmsg(/*Scale*/154) + wxT(" 1:%.0f"),
1070                                l->Scale));
1071
1072   /* This used to be a copyright line, but it was occasionally
1073    * mis-interpreted as us claiming copyright on the survey, so let's
1074    * give the website URL instead */
1075   MOVEMM(boxwidth + 2, 2);
1076   WriteString(wxT("Survex "VERSION" - http://survex.com/"));
1077
1078   draw_scale_bar(boxwidth + 10.0, 17.0, l->PaperWidth - boxwidth - 18.0);
1079}
1080
1081/* Draw fancy scale bar with bottom left at (x,y) (both in mm) and at most */
1082/* MaxLength mm long. The scaling in use is 1:scale */
1083void
1084svxPrintout::draw_scale_bar(double x, double y, double MaxLength)
1085{
1086   double StepEst, d;
1087   int E, Step, n, c;
1088   wxString buf;
1089   /* Limit scalebar to 20cm to stop people with A0 plotters complaining */
1090   if (MaxLength > 200.0) MaxLength = 200.0;
1091
1092#define dmin 10.0      /* each division >= dmin mm long */
1093#define StepMax 5      /* number in steps of at most StepMax (x 10^N) */
1094#define epsilon (1e-4) /* fudge factor to prevent rounding problems */
1095
1096   E = (int)ceil(log10((dmin * 0.001 * m_layout->Scale) / StepMax));
1097   StepEst = pow(10.0, -(double)E) * (dmin * 0.001) * m_layout->Scale - epsilon;
1098
1099   /* Force labelling to be in multiples of 1, 2, or 5 */
1100   Step = (StepEst <= 1.0 ? 1 : (StepEst <= 2.0 ? 2 : 5));
1101
1102   /* Work out actual length of each scale bar division */
1103   d = Step * pow(10.0, (double)E) / m_layout->Scale * 1000.0;
1104
1105   /* FIXME: Non-metric units here... */
1106   /* Choose appropriate units, s.t. if possible E is >=0 and minimized */
1107   int units;
1108   if (E >= 3) {
1109      E -= 3;
1110      units = /*km*/423;
1111   } else if (E >= 0) {
1112      units = /*m*/424;
1113   } else {
1114      E += 2;
1115      units = /*cm*/425;
1116   }
1117
1118   buf = wmsg(/*Scale*/154);
1119
1120   /* Add units used - eg. "Scale (10m)" */
1121   double pow10_E = pow(10.0, (double)E);
1122   if (E >= 0) {
1123      buf += wxString::Format(wxT(" (%.f%s)"), pow10_E, wmsg(units).c_str());
1124   } else {
1125      int sf = -(int)floor(E);
1126      buf += wxString::Format(wxT(" (%.*f%s)"), sf, pow10_E, wmsg(units).c_str());
1127   }
1128   SetColour(PR_COLOUR_TEXT);
1129   MOVEMM(x, y + 4); WriteString(buf);
1130
1131   /* Work out how many divisions there will be */
1132   n = (int)(MaxLength / d);
1133
1134   SetColour(PR_COLOUR_FRAME);
1135
1136   long Y = long(y * m_layout->scY);
1137   long Y2 = long((y + 3) * m_layout->scY);
1138   long X = long(x * m_layout->scX);
1139   long X2 = long((x + n * d) * m_layout->scX);
1140
1141   /* Draw top of scale bar */
1142   MoveTo(X2, Y2);
1143   DrawTo(X, Y2);
1144#if 0
1145   DrawTo(X2, Y);
1146   DrawTo(X, Y);
1147   MOVEMM(x + n * d, y); DRAWMM(x, y);
1148#endif
1149   /* Draw divisions and label them */
1150   for (c = 0; c <= n; c++) {
1151      SetColour(PR_COLOUR_FRAME);
1152      X = long((x + c * d) * m_layout->scX);
1153      MoveTo(X, Y);
1154      DrawTo(X, Y2);
1155#if 0 // Don't waste toner!
1156      /* Draw a "zebra crossing" scale bar. */
1157      if (c < n && (c & 1) == 0) {
1158          X2 = long((x + (c + 1) * d) * m_layout->scX);
1159          SolidRectangle(X, Y, X2 - X, Y2 - Y);
1160      }
1161#endif
1162      buf.Printf(wxT("%d"), c * Step);
1163      SetColour(PR_COLOUR_TEXT);
1164      MOVEMM(x + c * d - buf.length(), y - 5);
1165      WriteString(buf);
1166   }
1167}
1168
1169#if 0
1170void
1171make_calibration(layout *l) {
1172      img_point pt = { 0.0, 0.0, 0.0 };
1173      l->xMax = l->yMax = 0.1;
1174      l->xMin = l->yMin = 0;
1175
1176      stack(l,img_MOVE, NULL, &pt);
1177      pt.x = 0.1;
1178      stack(l,img_LINE, NULL, &pt);
1179      pt.y = 0.1;
1180      stack(l,img_LINE, NULL, &pt);
1181      pt.x = 0.0;
1182      stack(l,img_LINE, NULL, &pt);
1183      pt.y = 0.0;
1184      stack(l,img_LINE, NULL, &pt);
1185      pt.x = 0.05;
1186      pt.y = 0.001;
1187      stack(l,img_LABEL, "10cm", &pt);
1188      pt.x = 0.001;
1189      pt.y = 0.05;
1190      stack(l,img_LABEL, "10cm", &pt);
1191      l->Scale = 1.0;
1192}
1193#endif
1194
1195int
1196svxPrintout::next_page(int *pstate, char **q, int pageLim)
1197{
1198   char *p;
1199   int page;
1200   int c;
1201   p = *q;
1202   if (*pstate > 0) {
1203      /* doing a range */
1204      (*pstate)++;
1205      SVX_ASSERT(*p == '-');
1206      p++;
1207      while (isspace((unsigned char)*p)) p++;
1208      if (sscanf(p, "%u%n", &page, &c) > 0) {
1209         p += c;
1210      } else {
1211         page = pageLim;
1212      }
1213      if (*pstate > page) goto err;
1214      if (*pstate < page) return *pstate;
1215      *q = p;
1216      *pstate = 0;
1217      return page;
1218   }
1219
1220   while (isspace((unsigned char)*p) || *p == ',') p++;
1221
1222   if (!*p) return 0; /* done */
1223
1224   if (*p == '-') {
1225      *q = p;
1226      *pstate = 1;
1227      return 1; /* range with initial parameter omitted */
1228   }
1229   if (sscanf(p, "%u%n", &page, &c) > 0) {
1230      p += c;
1231      while (isspace((unsigned char)*p)) p++;
1232      *q = p;
1233      if (0 < page && page <= pageLim) {
1234         if (*p == '-') *pstate = page; /* range with start */
1235         return page;
1236      }
1237   }
1238   err:
1239   *pstate = -1;
1240   return 0;
1241}
1242
1243/* Draws in alignment marks on each page or borders on edge pages */
1244void
1245svxPrintout::drawticks(border clip, int tsize, int x, int y)
1246{
1247   long i;
1248   int s = tsize * 4;
1249   int o = s / 8;
1250   bool fAtCorner = fFalse;
1251   SetColour(PR_COLOUR_FRAME);
1252   if (x == 0 && m_layout->Border) {
1253      /* solid left border */
1254      MoveTo(clip.x_min, clip.y_min);
1255      DrawTo(clip.x_min, clip.y_max);
1256      fAtCorner = fTrue;
1257   } else {
1258      if (x > 0 || y > 0) {
1259         MoveTo(clip.x_min, clip.y_min);
1260         DrawTo(clip.x_min, clip.y_min + tsize);
1261      }
1262      if (s && x > 0 && m_layout->Cutlines) {
1263         /* dashed left border */
1264         i = (clip.y_max - clip.y_min) -
1265             (tsize + ((clip.y_max - clip.y_min - tsize * 2L) % s) / 2);
1266         for ( ; i > tsize; i -= s) {
1267            MoveTo(clip.x_min, clip.y_max - (i + o));
1268            DrawTo(clip.x_min, clip.y_max - (i - o));
1269         }
1270      }
1271      if (x > 0 || y < m_layout->pagesY - 1) {
1272         MoveTo(clip.x_min, clip.y_max - tsize);
1273         DrawTo(clip.x_min, clip.y_max);
1274         fAtCorner = fTrue;
1275      }
1276   }
1277
1278   if (y == m_layout->pagesY - 1 && m_layout->Border) {
1279      /* solid top border */
1280      if (!fAtCorner) MoveTo(clip.x_min, clip.y_max);
1281      DrawTo(clip.x_max, clip.y_max);
1282      fAtCorner = fTrue;
1283   } else {
1284      if (y < m_layout->pagesY - 1 || x > 0) {
1285         if (!fAtCorner) MoveTo(clip.x_min, clip.y_max);
1286         DrawTo(clip.x_min + tsize, clip.y_max);
1287      }
1288      if (s && y < m_layout->pagesY - 1 && m_layout->Cutlines) {
1289         /* dashed top border */
1290         i = (clip.x_max - clip.x_min) -
1291             (tsize + ((clip.x_max - clip.x_min - tsize * 2L) % s) / 2);
1292         for ( ; i > tsize; i -= s) {
1293            MoveTo(clip.x_max - (i + o), clip.y_max);
1294            DrawTo(clip.x_max - (i - o), clip.y_max);
1295         }
1296      }
1297      if (y < m_layout->pagesY - 1 || x < m_layout->pagesX - 1) {
1298         MoveTo(clip.x_max - tsize, clip.y_max);
1299         DrawTo(clip.x_max, clip.y_max);
1300         fAtCorner = fTrue;
1301      } else {
1302         fAtCorner = fFalse;
1303      }
1304   }
1305
1306   if (x == m_layout->pagesX - 1 && m_layout->Border) {
1307      /* solid right border */
1308      if (!fAtCorner) MoveTo(clip.x_max, clip.y_max);
1309      DrawTo(clip.x_max, clip.y_min);
1310      fAtCorner = fTrue;
1311   } else {
1312      if (x < m_layout->pagesX - 1 || y < m_layout->pagesY - 1) {
1313         if (!fAtCorner) MoveTo(clip.x_max, clip.y_max);
1314         DrawTo(clip.x_max, clip.y_max - tsize);
1315      }
1316      if (s && x < m_layout->pagesX - 1 && m_layout->Cutlines) {
1317         /* dashed right border */
1318         i = (clip.y_max - clip.y_min) -
1319             (tsize + ((clip.y_max - clip.y_min - tsize * 2L) % s) / 2);
1320         for ( ; i > tsize; i -= s) {
1321            MoveTo(clip.x_max, clip.y_min + (i + o));
1322            DrawTo(clip.x_max, clip.y_min + (i - o));
1323         }
1324      }
1325      if (x < m_layout->pagesX - 1 || y > 0) {
1326         MoveTo(clip.x_max, clip.y_min + tsize);
1327         DrawTo(clip.x_max, clip.y_min);
1328         fAtCorner = fTrue;
1329      } else {
1330         fAtCorner = fFalse;
1331      }
1332   }
1333
1334   if (y == 0 && m_layout->Border) {
1335      /* solid bottom border */
1336      if (!fAtCorner) MoveTo(clip.x_max, clip.y_min);
1337      DrawTo(clip.x_min, clip.y_min);
1338   } else {
1339      if (y > 0 || x < m_layout->pagesX - 1) {
1340         if (!fAtCorner) MoveTo(clip.x_max, clip.y_min);
1341         DrawTo(clip.x_max - tsize, clip.y_min);
1342      }
1343      if (s && y > 0 && m_layout->Cutlines) {
1344         /* dashed bottom border */
1345         i = (clip.x_max - clip.x_min) -
1346             (tsize + ((clip.x_max - clip.x_min - tsize * 2L) % s) / 2);
1347         for ( ; i > tsize; i -= s) {
1348            MoveTo(clip.x_min + (i + o), clip.y_min);
1349            DrawTo(clip.x_min + (i - o), clip.y_min);
1350         }
1351      }
1352      if (y > 0 || x > 0) {
1353         MoveTo(clip.x_min + tsize, clip.y_min);
1354         DrawTo(clip.x_min, clip.y_min);
1355      }
1356   }
1357}
1358
1359bool
1360svxPrintout::OnPrintPage(int pageNum) {
1361    GetPageSizePixels(&xpPageWidth, &ypPageDepth);
1362    pdc = GetDC();
1363#ifdef AVEN_PRINT_PREVIEW
1364    if (IsPreview()) {
1365        int dcx, dcy;
1366        pdc->GetSize(&dcx, &dcy);
1367        pdc->SetUserScale((double)dcx / xpPageWidth, (double)dcy / ypPageDepth);
1368    }
1369#endif
1370
1371    layout * l = m_layout;
1372    {
1373        int pwidth, pdepth;
1374        GetPageSizeMM(&pwidth, &pdepth);
1375        l->scX = (double)xpPageWidth / pwidth;
1376        l->scY = (double)ypPageDepth / pdepth;
1377        font_scaling_x = l->scX * (25.4 / 72.0);
1378        font_scaling_y = l->scY * (25.4 / 72.0);
1379        MarginLeft = m_data->GetMarginTopLeft().x;
1380        MarginTop = m_data->GetMarginTopLeft().y;
1381        MarginBottom = m_data->GetMarginBottomRight().y;
1382        MarginRight = m_data->GetMarginBottomRight().x;
1383        xpPageWidth -= (int)(l->scX * (MarginLeft + MarginRight));
1384        ypPageDepth -= (int)(l->scY * (10 + MarginBottom + MarginRight));
1385        // xpPageWidth -= 1;
1386        pdepth -= 10;
1387        x_offset = (long)(l->scX * MarginLeft);
1388        y_offset = (long)(l->scY * MarginTop);
1389        l->PaperWidth = pwidth -= MarginLeft + MarginRight;
1390        l->PaperDepth = pdepth -= MarginTop + MarginBottom;
1391    }
1392
1393    double SIN = sin(rad(l->rot));
1394    double COS = cos(rad(l->rot));
1395    double SINT = sin(rad(l->tilt));
1396    double COST = cos(rad(l->tilt));
1397
1398    NewPage(pageNum, l->pagesX, l->pagesY);
1399
1400    if (l->Legend && pageNum == (l->pagesY - 1) * l->pagesX + 1) {
1401        SetFont(PR_FONT_DEFAULT);
1402        draw_info_box();
1403    }
1404
1405    pdc->SetClippingRegion(x_offset, y_offset,xpPageWidth+1, ypPageDepth+1);
1406
1407    const double Sc = 1000 / l->Scale;
1408
1409    if (l->show_mask & LEGS) {
1410        SetColour(PR_COLOUR_LEG);
1411        list<traverse>::const_iterator trav = mainfrm->traverses_begin();
1412        list<traverse>::const_iterator tend = mainfrm->traverses_end();
1413        for ( ; trav != tend; ++trav) {
1414            vector<PointInfo>::const_iterator pos = trav->begin();
1415            vector<PointInfo>::const_iterator end = trav->end();
1416            for ( ; pos != end; ++pos) {
1417                double x = pos->GetX();
1418                double y = pos->GetY();
1419                double z = pos->GetZ();
1420                double X = x * COS - y * SIN;
1421                double Y = z * COST - (x * SIN + y * COS) * SINT;
1422                long px = (long)((X * Sc + l->xOrg) * l->scX);
1423                long py = (long)((Y * Sc + l->yOrg) * l->scY);
1424                if (pos == trav->begin()) {
1425                    MoveTo(px, py);
1426                } else {
1427                    DrawTo(px, py);
1428                }
1429            }
1430        }
1431    }
1432
1433    if ((l->show_mask & XSECT) &&
1434        (l->tilt == 0.0 || l->tilt == 90.0 || l->tilt == -90.0)) {
1435        list<vector<XSect> >::const_iterator trav = mainfrm->tubes_begin();
1436        list<vector<XSect> >::const_iterator tend = mainfrm->tubes_end();
1437        for ( ; trav != tend; ++trav) {
1438            if (l->tilt == 90.0 || l->tilt == -90.0) PlotLR(*trav);
1439            if (l->tilt == 0.0) PlotUD(*trav);
1440        }
1441    }
1442
1443    if (l->show_mask & SURF) {
1444        SetColour(PR_COLOUR_SURFACE_LEG);
1445        list<traverse>::const_iterator trav = mainfrm->surface_traverses_begin();
1446        list<traverse>::const_iterator tend = mainfrm->surface_traverses_end();
1447        for ( ; trav != tend; ++trav) {
1448            vector<PointInfo>::const_iterator pos = trav->begin();
1449            vector<PointInfo>::const_iterator end = trav->end();
1450            for ( ; pos != end; ++pos) {
1451                double x = pos->GetX();
1452                double y = pos->GetY();
1453                double z = pos->GetZ();
1454                double X = x * COS - y * SIN;
1455                double Y = z * COST - (x * SIN + y * COS) * SINT;
1456                long px = (long)((X * Sc + l->xOrg) * l->scX);
1457                long py = (long)((Y * Sc + l->yOrg) * l->scY);
1458                if (pos == trav->begin()) {
1459                    MoveTo(px, py);
1460                } else {
1461                    DrawTo(px, py);
1462                }
1463            }
1464        }
1465    }
1466
1467    if (l->show_mask & (LABELS|STNS)) {
1468        if (l->show_mask & LABELS) SetFont(PR_FONT_LABELS);
1469        list<LabelInfo*>::const_iterator label = mainfrm->GetLabels();
1470        while (label != mainfrm->GetLabelsEnd()) {
1471            double px = (*label)->GetX();
1472            double py = (*label)->GetY();
1473            double pz = (*label)->GetZ();
1474            if ((l->show_mask & SURF) || (*label)->IsUnderground()) {
1475                double X = px * COS - py * SIN;
1476                double Y = pz * COST - (px * SIN + py * COS) * SINT;
1477                long xnew, ynew;
1478                xnew = (long)((X * Sc + l->xOrg) * l->scX);
1479                ynew = (long)((Y * Sc + l->yOrg) * l->scY);
1480                if (l->show_mask & STNS) {
1481                    SetColour(PR_COLOUR_CROSS);
1482                    DrawCross(xnew, ynew);
1483                }
1484                if (l->show_mask & LABELS) {
1485                    SetColour(PR_COLOUR_LABELS);
1486                    MoveTo(xnew, ynew);
1487                    WriteString((*label)->GetText());
1488                }
1489            }
1490            ++label;
1491        }
1492    }
1493
1494    return true;
1495}
1496
1497void
1498svxPrintout::GetPageInfo(int *minPage, int *maxPage,
1499                         int *pageFrom, int *pageTo)
1500{
1501    *minPage = *pageFrom = 1;
1502    *maxPage = *pageTo = m_layout->pages;
1503}
1504
1505bool
1506svxPrintout::HasPage(int pageNum) {
1507    return (pageNum <= m_layout->pages);
1508}
1509
1510void
1511svxPrintout::OnBeginPrinting() {
1512    FILE *fh_list[4];
1513
1514    FILE **pfh = fh_list;
1515    FILE *fh;
1516    const char *pth_cfg;
1517    char *print_ini;
1518
1519    /* ini files searched in this order:
1520     * ~/.survex/print.ini [unix only]
1521     * /etc/survex/print.ini [unix only]
1522     * <support file directory>/myprint.ini [not unix]
1523     * <support file directory>/print.ini [must exist]
1524     */
1525
1526#ifdef __UNIX__
1527    pth_cfg = getenv("HOME");
1528    if (pth_cfg) {
1529        fh = fopenWithPthAndExt(pth_cfg, ".survex/print."EXT_INI, NULL,
1530                "rb", NULL);
1531        if (fh) *pfh++ = fh;
1532    }
1533    pth_cfg = msg_cfgpth();
1534    fh = fopenWithPthAndExt(NULL, "/etc/survex/print."EXT_INI, NULL, "rb",
1535            NULL);
1536    if (fh) *pfh++ = fh;
1537#else
1538    pth_cfg = msg_cfgpth();
1539    print_ini = add_ext("myprint", EXT_INI);
1540    fh = fopenWithPthAndExt(pth_cfg, print_ini, NULL, "rb", NULL);
1541    if (fh) *pfh++ = fh;
1542#endif
1543    print_ini = add_ext("print", EXT_INI);
1544    fh = fopenWithPthAndExt(pth_cfg, print_ini, NULL, "rb", NULL);
1545    if (!fh) fatalerror(/*Couldn’t open file “%s”*/24, print_ini);
1546    *pfh++ = fh;
1547    *pfh = NULL;
1548    Init(pfh, false);
1549    for (pfh = fh_list; *pfh; pfh++) (void)fclose(*pfh);
1550    Pre();
1551    m_layout->footer = wmsg(/*Survey “%s”   Page %d (of %d)   Processed on %s*/167);
1552}
1553
1554void
1555svxPrintout::OnEndPrinting() {
1556    delete font_labels;
1557    delete font_default;
1558    delete pen_frame;
1559    delete pen_leg;
1560    delete pen_surface_leg;
1561    delete pen_cross;
1562}
1563
1564
1565// prcore -> wx.grafx (calls to move pens around and stuff - low level)
1566// this seems to have been done...
1567
1568
1569
1570static border clip;
1571
1572
1573int
1574svxPrintout::check_intersection(long x_p, long y_p)
1575{
1576#define U 1
1577#define D 2
1578#define L 4
1579#define R 8
1580   int mask_p = 0, mask_t = 0;
1581   if (x_p < 0)
1582      mask_p = L;
1583   else if (x_p > xpPageWidth)
1584      mask_p = R;
1585
1586   if (y_p < 0)
1587      mask_p |= D;
1588   else if (y_p > ypPageDepth)
1589      mask_p |= U;
1590
1591   if (x_t < 0)
1592      mask_t = L;
1593   else if (x_t > xpPageWidth)
1594      mask_t = R;
1595
1596   if (y_t < 0)
1597      mask_t |= D;
1598   else if (y_t > ypPageDepth)
1599      mask_t |= U;
1600
1601#if 0
1602   /* approximation to correct answer */
1603   return !(mask_t & mask_p);
1604#else
1605   /* One end of the line is on the page */
1606   if (!mask_t || !mask_p) return 1;
1607
1608   /* whole line is above, left, right, or below page */
1609   if (mask_t & mask_p) return 0;
1610
1611   if (mask_t == 0) mask_t = mask_p;
1612   if (mask_t & U) {
1613      double v = (double)(y_p - ypPageDepth) / (y_p - y_t);
1614      return v >= 0 && v <= 1;
1615   }
1616   if (mask_t & D) {
1617      double v = (double)y_p / (y_p - y_t);
1618      return v >= 0 && v <= 1;
1619   }
1620   if (mask_t & R) {
1621      double v = (double)(x_p - xpPageWidth) / (x_p - x_t);
1622      return v >= 0 && v <= 1;
1623   }
1624   SVX_ASSERT(mask_t & L);
1625   {
1626      double v = (double)x_p / (x_p - x_t);
1627      return v >= 0 && v <= 1;
1628   }
1629#endif
1630#undef U
1631#undef D
1632#undef L
1633#undef R
1634}
1635
1636void
1637svxPrintout::MoveTo(long x, long y)
1638{
1639    x_t = x_offset + x - clip.x_min;
1640    y_t = y_offset + clip.y_max - y;
1641}
1642
1643void
1644svxPrintout::DrawTo(long x, long y)
1645{
1646    long x_p = x_t, y_p = y_t;
1647    x_t = x_offset + x - clip.x_min;
1648    y_t = y_offset + clip.y_max - y;
1649    if (cur_pass != -1) {
1650        pdc->DrawLine(x_p, y_p, x_t, y_t);
1651    } else {
1652        if (check_intersection(x_p, y_p)) fBlankPage = fFalse;
1653    }
1654}
1655
1656#define POINTS_PER_INCH 72.0
1657#define POINTS_PER_MM (POINTS_PER_INCH / MM_PER_INCH)
1658#define PWX_CROSS_SIZE (int)(2 * m_layout->scX / POINTS_PER_MM)
1659
1660void
1661svxPrintout::DrawCross(long x, long y)
1662{
1663   if (cur_pass != -1) {
1664      MoveTo(x - PWX_CROSS_SIZE, y - PWX_CROSS_SIZE);
1665      DrawTo(x + PWX_CROSS_SIZE, y + PWX_CROSS_SIZE);
1666      MoveTo(x + PWX_CROSS_SIZE, y - PWX_CROSS_SIZE);
1667      DrawTo(x - PWX_CROSS_SIZE, y + PWX_CROSS_SIZE);
1668      MoveTo(x, y);
1669   } else {
1670      if ((x + PWX_CROSS_SIZE > clip.x_min &&
1671           x - PWX_CROSS_SIZE < clip.x_max) ||
1672          (y + PWX_CROSS_SIZE > clip.y_min &&
1673           y - PWX_CROSS_SIZE < clip.y_max)) {
1674         fBlankPage = fFalse;
1675      }
1676   }
1677}
1678
1679void
1680svxPrintout::SetFont(int fontcode)
1681{
1682    switch (fontcode) {
1683        case PR_FONT_DEFAULT:
1684            current_font = font_default;
1685            break;
1686        case PR_FONT_LABELS:
1687            current_font = font_labels;
1688            break;
1689        default:
1690            BUG("unknown font code");
1691    }
1692}
1693
1694void
1695svxPrintout::SetColour(int colourcode)
1696{
1697    switch (colourcode) {
1698        case PR_COLOUR_TEXT:
1699            pdc->SetTextForeground(colour_text);
1700            break;
1701        case PR_COLOUR_LABELS:
1702            pdc->SetTextForeground(colour_labels);
1703            pdc->SetBackgroundMode(wxTRANSPARENT);
1704            break;
1705        case PR_COLOUR_FRAME:
1706            pdc->SetPen(*pen_frame);
1707            break;
1708        case PR_COLOUR_LEG:
1709            pdc->SetPen(*pen_leg);
1710            break;
1711        case PR_COLOUR_CROSS:
1712            pdc->SetPen(*pen_cross);
1713            break;
1714        case PR_COLOUR_SURFACE_LEG:
1715            pdc->SetPen(*pen_surface_leg);
1716            break;
1717        default:
1718            BUG("unknown colour code");
1719    }
1720}
1721
1722void
1723svxPrintout::WriteString(const wxString & s)
1724{
1725    double xsc, ysc;
1726    pdc->GetUserScale(&xsc, &ysc);
1727    pdc->SetUserScale(xsc * font_scaling_x, ysc * font_scaling_y);
1728    pdc->SetFont(*current_font);
1729    int w, h;
1730    if (cur_pass != -1) {
1731        pdc->GetTextExtent(wxT("My"), &w, &h);
1732        pdc->DrawText(s,
1733                      long(x_t / font_scaling_x),
1734                      long(y_t / font_scaling_y) - h);
1735    } else {
1736        pdc->GetTextExtent(s, &w, &h);
1737        if ((y_t + h > 0 && y_t - h < clip.y_max - clip.y_min) ||
1738            (x_t < clip.x_max - clip.x_min && x_t + w > 0)) {
1739            fBlankPage = fFalse;
1740        }
1741    }
1742    pdc->SetUserScale(xsc, ysc);
1743}
1744
1745void
1746svxPrintout::DrawEllipse(long x, long y, long r, long R)
1747{
1748    /* Don't need to check in first-pass - circle is only used in title box */
1749    if (cur_pass != -1) {
1750        x_t = x_offset + x - clip.x_min;
1751        y_t = y_offset + clip.y_max - y;
1752        const wxBrush & save_brush = pdc->GetBrush();
1753        pdc->SetBrush(*wxTRANSPARENT_BRUSH);
1754        pdc->DrawEllipse(x_t - r, y_t - R, 2 * r, 2 * R);
1755        pdc->SetBrush(save_brush);
1756    }
1757}
1758
1759void
1760svxPrintout::SolidRectangle(long x, long y, long w, long h)
1761{
1762    long X = x_offset + x - clip.x_min;
1763    long Y = y_offset + clip.y_max - y;
1764    pdc->SetBrush(*wxBLACK_BRUSH);
1765    pdc->DrawRectangle(X, Y - h, w, h);
1766}
1767
1768int
1769svxPrintout::Pre()
1770{
1771    font_labels = new wxFont(fontsize_labels, wxDEFAULT, wxNORMAL, wxNORMAL,
1772                             false, wxString(fontname_labels, wxConvUTF8),
1773                             wxFONTENCODING_ISO8859_1);
1774    font_default = new wxFont(fontsize, wxDEFAULT, wxNORMAL, wxNORMAL,
1775                              false, wxString(fontname, wxConvUTF8),
1776                              wxFONTENCODING_ISO8859_1);
1777    current_font = font_default;
1778    pen_leg = new wxPen(colour_leg);
1779    pen_surface_leg = new wxPen(colour_surface_leg);
1780    pen_cross = new wxPen(colour_cross);
1781    pen_frame = new wxPen(colour_frame);
1782    return 1; /* only need 1 pass */
1783}
1784
1785void
1786svxPrintout::NewPage(int pg, int pagesX, int pagesY)
1787{
1788    int x, y;
1789    x = (pg - 1) % pagesX;
1790    y = pagesY - 1 - ((pg - 1) / pagesX);
1791
1792    clip.x_min = (long)x * xpPageWidth;
1793    clip.y_min = (long)y * ypPageDepth;
1794    clip.x_max = clip.x_min + xpPageWidth; /* dm/pcl/ps had -1; */
1795    clip.y_max = clip.y_min + ypPageDepth; /* dm/pcl/ps had -1; */
1796
1797    //we have to write the footer here. PostScript is being weird. Really weird.
1798    pdc->SetFont(*font_labels);
1799    MoveTo(clip.x_min, clip.y_min - (long)(7 * m_layout->scY));
1800    wxString footer;
1801    footer.Printf(m_layout->footer,
1802                  m_layout->title.c_str(),
1803                  pg,
1804                  m_layout->pagesX * m_layout->pagesY,
1805                  m_layout->datestamp.c_str());
1806    WriteString(footer);
1807    pdc->DestroyClippingRegion();
1808    drawticks(clip, (int)(9 * m_layout->scX / POINTS_PER_MM), x, y);
1809}
1810
1811void
1812svxPrintout::PlotLR(const vector<XSect> & centreline)
1813{
1814    assert(centreline.size() > 1);
1815    XSect prev_pt_v;
1816    Vector3 last_right(1.0, 0.0, 0.0);
1817
1818    const double Sc = 1000 / m_layout->Scale;
1819    const double SIN = sin(rad(m_layout->rot));
1820    const double COS = cos(rad(m_layout->rot));
1821
1822    vector<XSect>::const_iterator i = centreline.begin();
1823    vector<XSect>::size_type segment = 0;
1824    while (i != centreline.end()) {
1825        // get the coordinates of this vertex
1826        const XSect & pt_v = *i++;
1827
1828        Vector3 right;
1829
1830        const Vector3 up_v(0.0, 0.0, 1.0);
1831
1832        if (segment == 0) {
1833            assert(i != centreline.end());
1834            // first segment
1835
1836            // get the coordinates of the next vertex
1837            const XSect & next_pt_v = *i;
1838
1839            // calculate vector from this pt to the next one
1840            Vector3 leg_v = next_pt_v - pt_v;
1841
1842            // obtain a vector in the LRUD plane
1843            right = leg_v * up_v;
1844            if (right.magnitude() == 0) {
1845                right = last_right;
1846            } else {
1847                last_right = right;
1848            }
1849        } else if (segment + 1 == centreline.size()) {
1850            // last segment
1851
1852            // Calculate vector from the previous pt to this one.
1853            Vector3 leg_v = pt_v - prev_pt_v;
1854
1855            // Obtain a horizontal vector in the LRUD plane.
1856            right = leg_v * up_v;
1857            if (right.magnitude() == 0) {
1858                right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
1859            } else {
1860                last_right = right;
1861            }
1862        } else {
1863            assert(i != centreline.end());
1864            // Intermediate segment.
1865
1866            // Get the coordinates of the next vertex.
1867            const XSect & next_pt_v = *i;
1868
1869            // Calculate vectors from this vertex to the
1870            // next vertex, and from the previous vertex to
1871            // this one.
1872            Vector3 leg1_v = pt_v - prev_pt_v;
1873            Vector3 leg2_v = next_pt_v - pt_v;
1874
1875            // Obtain horizontal vectors perpendicular to
1876            // both legs, then normalise and average to get
1877            // a horizontal bisector.
1878            Vector3 r1 = leg1_v * up_v;
1879            Vector3 r2 = leg2_v * up_v;
1880            r1.normalise();
1881            r2.normalise();
1882            right = r1 + r2;
1883            if (right.magnitude() == 0) {
1884                // This is the "mid-pitch" case...
1885                right = last_right;
1886            }
1887            last_right = right;
1888        }
1889
1890        // Scale to unit vectors in the LRUD plane.
1891        right.normalise();
1892
1893        Double l = pt_v.GetL();
1894        Double r = pt_v.GetR();
1895
1896        if (l >= 0) {
1897            Vector3 p = pt_v - right * l;
1898            double X = p.GetX() * COS - p.GetY() * SIN;
1899            double Y = (p.GetX() * SIN + p.GetY() * COS);
1900            long x = (long)((X * Sc + m_layout->xOrg) * m_layout->scX);
1901            long y = (long)((Y * Sc + m_layout->yOrg) * m_layout->scY);
1902            MoveTo(x - PWX_CROSS_SIZE, y - PWX_CROSS_SIZE);
1903            DrawTo(x, y);
1904            DrawTo(x - PWX_CROSS_SIZE, y + PWX_CROSS_SIZE);
1905        }
1906        if (r >= 0) {
1907            Vector3 p = pt_v + right * r;
1908            double X = p.GetX() * COS - p.GetY() * SIN;
1909            double Y = (p.GetX() * SIN + p.GetY() * COS);
1910            long x = (long)((X * Sc + m_layout->xOrg) * m_layout->scX);
1911            long y = (long)((Y * Sc + m_layout->yOrg) * m_layout->scY);
1912            MoveTo(x + PWX_CROSS_SIZE, y - PWX_CROSS_SIZE);
1913            DrawTo(x, y);
1914            DrawTo(x + PWX_CROSS_SIZE, y + PWX_CROSS_SIZE);
1915        }
1916
1917        prev_pt_v = pt_v;
1918
1919        ++segment;
1920    }
1921}
1922
1923void
1924svxPrintout::PlotUD(const vector<XSect> & centreline)
1925{
1926    assert(centreline.size() > 1);
1927    const double Sc = 1000 / m_layout->Scale;
1928
1929    vector<XSect>::const_iterator i = centreline.begin();
1930    while (i != centreline.end()) {
1931        // get the coordinates of this vertex
1932        const XSect & pt_v = *i++;
1933
1934        Double u = pt_v.GetU();
1935        Double d = pt_v.GetD();
1936
1937        if (u >= 0 || d >= 0) {
1938            Vector3 p = pt_v;
1939            double SIN = sin(rad(m_layout->rot));
1940            double COS = cos(rad(m_layout->rot));
1941            double X = p.GetX() * COS - p.GetY() * SIN;
1942            double Y = p.GetZ();
1943            long x = (long)((X * Sc + m_layout->xOrg) * m_layout->scX);
1944            if (u >= 0) {
1945                long y = (long)(((Y + u) * Sc + m_layout->yOrg) * m_layout->scY);
1946                MoveTo(x - PWX_CROSS_SIZE, y + PWX_CROSS_SIZE);
1947                DrawTo(x, y);
1948                DrawTo(x + PWX_CROSS_SIZE, y + PWX_CROSS_SIZE);
1949            }
1950            if (d >= 0) {
1951                long y = (long)(((Y - d) * Sc + m_layout->yOrg) * m_layout->scY);
1952                MoveTo(x - PWX_CROSS_SIZE, y - PWX_CROSS_SIZE);
1953                DrawTo(x, y);
1954                DrawTo(x + PWX_CROSS_SIZE, y - PWX_CROSS_SIZE);
1955            }
1956        }
1957    }
1958}
1959
1960static wxColour
1961to_rgb(const char *var, char *val)
1962{
1963   unsigned long rgb;
1964   if (!val) return *wxBLACK;
1965   rgb = as_colour(var, val);
1966   return wxColour((rgb & 0xff0000) >> 16, (rgb & 0xff00) >> 8, rgb & 0xff);
1967}
1968
1969/* Initialise printer routines */
1970char *
1971svxPrintout::Init(FILE **fh_list, bool fCalibrate)
1972{
1973   static const char *vars[] = {
1974      "font_size_labels",
1975      "colour_text",
1976      "colour_labels",
1977      "colour_frame",
1978      "colour_legs",
1979      "colour_crosses",
1980      "colour_surface_legs",
1981      NULL
1982   };
1983   char **vals;
1984
1985   (void)fCalibrate; /* suppress unused argument warning */
1986
1987   vals = ini_read(fh_list, "aven", vars);
1988   fontsize_labels = 10;
1989   if (vals[0]) fontsize_labels = as_int(vars[0], vals[0], 1, INT_MAX);
1990   fontsize = 10;
1991
1992   colour_text = colour_labels = colour_frame = colour_leg = colour_cross = colour_surface_leg = *wxBLACK;
1993   if (vals[1]) colour_text = to_rgb(vars[1], vals[1]);
1994   if (vals[2]) colour_labels = to_rgb(vars[2], vals[2]);
1995   if (vals[3]) colour_frame = to_rgb(vars[3], vals[3]);
1996   if (vals[4]) colour_leg = to_rgb(vars[4], vals[4]);
1997   if (vals[5]) colour_cross = to_rgb(vars[5], vals[5]);
1998   if (vals[6]) colour_surface_leg = to_rgb(vars[6], vals[6]);
1999   m_layout->scX = 1;
2000   m_layout->scY = 1;
2001   return NULL;
2002}
Note: See TracBrowser for help on using the repository browser.