summaryrefslogtreecommitdiffstats
path: root/ui/qt/print_dialog.cpp
blob: 84c2d9065659e77a5959deaa0256198d33b34d5a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/* print_dialog.cpp
 *
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 1998 Gerald Combs
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

#include "print_dialog.h"
#include <ui_print_dialog.h>

#include <wsutil/utf8_entities.h>

#ifdef Q_OS_WIN
#include <windows.h>
#include "ui/packet_range.h"
#include "ui/win32/file_dlg_win32.h"
#endif

#include <QPrintDialog>
#include <QPageSetupDialog>
#include <QPainter>
#include <QPaintEngine>
#include <QKeyEvent>
#include <QMessageBox>

#include "main_application.h"

extern "C" {

// Page element callbacks


static gboolean
print_preamble_pd(print_stream_t *self, gchar *, const char *)
{
    if (!self) return FALSE;
    PrintDialog *print_dlg = static_cast<PrintDialog *>(self->data);
    if (!print_dlg) return FALSE;

    return print_dlg->printHeader();
}

static gboolean
print_line_pd(print_stream_t *self, int indent, const char *line)
{
    if (!self) return FALSE;
    PrintDialog *print_dlg = static_cast<PrintDialog *>(self->data);
    if (!print_dlg) return FALSE;

    return print_dlg->printLine(indent, line);
}

static gboolean
new_page_pd(print_stream_t *self)
{
    if (!self) return FALSE;
    PrintDialog *print_dlg = static_cast<PrintDialog *>(self->data);
    if (!print_dlg) return FALSE;

    return print_dlg->printHeader();
}

} // extern "C"

PrintDialog::PrintDialog(QWidget *parent, capture_file *cf, QString selRange) :
    QDialog(parent),
    pd_ui_(new Ui::PrintDialog),
    cur_printer_(NULL),
    cur_painter_(NULL),
    preview_(new QPrintPreviewWidget(&printer_)),
    print_bt_(new QPushButton(tr("&Print…"))),
    cap_file_(cf),
    page_pos_(0),
    in_preview_(FALSE)
{
    Q_ASSERT(cf);

    pd_ui_->setupUi(this);
    setWindowTitle(mainApp->windowTitleString(tr("Print")));

    pd_ui_->previewLayout->insertWidget(0, preview_, Qt::AlignTop);

    preview_->setMinimumWidth(preview_->height() / 2);
    preview_->setToolTip(pd_ui_->zoomLabel->toolTip());

    // XXX Make these configurable
    header_font_.setFamily("Times");
    header_font_.setPointSizeF(header_font_.pointSizeF() * 0.8);
    packet_font_ = mainApp->monospaceFont();
    packet_font_.setPointSizeF(packet_font_.pointSizeF() * 0.8);

    memset(&print_args_, 0, sizeof(print_args_));
    memset(&stream_ops_, 0, sizeof(stream_ops_));

    /* Init the export range */
    packet_range_init(&print_args_.range, cap_file_);
    /* Default to displayed packets */
    print_args_.range.process_filtered = TRUE;

    stream_ops_.print_preamble = print_preamble_pd;
    stream_ops_.print_line     = print_line_pd;
    stream_ops_.new_page       = new_page_pd;

    stream_.data = this;
    stream_.ops = &stream_ops_;
    print_args_.stream = &stream_;

    gchar *display_basename = g_filename_display_basename(cap_file_->filename);
    printer_.setDocName(display_basename);
    g_free(display_basename);

    pd_ui_->rangeGroupBox->initRange(&print_args_.range, selRange);

    pd_ui_->buttonBox->addButton(print_bt_, QDialogButtonBox::ActionRole);
    pd_ui_->buttonBox->addButton(tr("Page &Setup…"), QDialogButtonBox::ResetRole);
    print_bt_->setDefault(true);

    connect(preview_, SIGNAL(paintRequested(QPrinter*)), this, SLOT(paintPreview(QPrinter*)));
    connect(pd_ui_->rangeGroupBox, SIGNAL(rangeChanged()),
            this, SLOT(checkValidity()));
    connect(pd_ui_->formatGroupBox, SIGNAL(formatChanged()),
            this, SLOT(checkValidity()));
    connect(pd_ui_->formFeedCheckBox, SIGNAL(toggled(bool)),
            preview_, SLOT(updatePreview()));
    connect(pd_ui_->bannerCheckBox, SIGNAL(toggled(bool)),
            preview_, SLOT(updatePreview()));

    checkValidity();
}

PrintDialog::~PrintDialog()
{
    packet_range_cleanup(&print_args_.range);
    delete pd_ui_;
}

gboolean PrintDialog::printHeader()
{
    if (!cap_file_ || !cap_file_->filename || !cur_printer_ || !cur_painter_) return FALSE;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
    int page_top = cur_printer_->pageLayout().paintRectPixels(cur_printer_->resolution()).top();
#else
    int page_top = cur_printer_->pageRect().top();
#endif

    if (page_pos_ > page_top) {
        if (in_preview_) {
            // When generating a preview, only generate the first page;
            // if we're past the first page, stop the printing process.
            return FALSE;
        }
        // Second and subsequent pages only
        cur_printer_->newPage();
        page_pos_ = page_top;
    }

    if (pd_ui_->bannerCheckBox->isChecked()) {
        QString banner = QString(tr("%1 %2 total packets, %3 shown"))
                .arg(cap_file_->filename)
                .arg(cap_file_->count)
                .arg(cap_file_->displayed_count);
        cur_painter_->setFont(header_font_);
        cur_painter_->drawText(0, page_top, banner);
    }
    page_pos_ += cur_painter_->fontMetrics().height();
    cur_painter_->setFont(packet_font_);
    return TRUE;
}

gboolean PrintDialog::printLine(int indent, const char *line)
{
    QRect out_rect, page_rect;
    QString out_line;

    if (!line || !cur_printer_ || !cur_painter_) return FALSE;

    /* Prepare the tabs for printing, depending on tree level */
    out_line.fill(' ', indent * 4);
    out_line += line;

#if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
    page_rect = cur_printer_->pageLayout().paintRectPixels(cur_printer_->resolution());
#else
    page_rect = cur_printer_->pageRect();
#endif

    out_rect = cur_painter_->boundingRect(page_rect, Qt::TextWordWrap, out_line);

    if (page_rect.height() < page_pos_ + out_rect.height()) {
        //
        // We're past the end of the page, so this line will be on
        // the next page.
        //
        if (in_preview_) {
            // When generating a preview, only generate the first page;
            // if we're past the first page, stop the printing process.
            return FALSE;
        }
        if (*line == '\0') {
            // This is an empty line, so it's a separator; no need to
            // waste space printing it at the top of a page, as the
            // page break suffices as a separator.
            return TRUE;
        }
        printHeader();
    }

    out_rect.translate(0, page_pos_);
    cur_painter_->drawText(out_rect, Qt::TextWordWrap, out_line);
    page_pos_ += out_rect.height();
    return TRUE;
}

// Protected

void PrintDialog::keyPressEvent(QKeyEvent *event)
{
    // XXX - This differs from the main window but matches other applications (e.g. Mozilla and Safari)
    switch(event->key()) {
    case Qt::Key_Minus:
    case Qt::Key_Underscore:    // Shifted minus on U.S. keyboards
        preview_->zoomOut();
        break;
    case Qt::Key_Plus:
    case Qt::Key_Equal:         // Unshifted plus on U.S. keyboards
        preview_->zoomIn();
        break;
    case Qt::Key_0:
    case Qt::Key_ParenRight:    // Shifted 0 on U.S. keyboards
        // fitInView doesn't grow (at least in Qt 4.8.2) so make sure it shrinks.
        preview_->setUpdatesEnabled(false);
        preview_->setZoomFactor(1.0);
        preview_->fitInView();
        preview_->setUpdatesEnabled(true);
        break;
    }

    QDialog::keyPressEvent(event);
}

// Private

void PrintDialog::printPackets(QPrinter *printer, bool in_preview)
{
    QPainter painter;

    if (!printer) return;

#if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
    page_pos_ = printer->pageLayout().paintRectPixels(printer->resolution()).top();
#else
    page_pos_ = printer->pageRect().top();
#endif
    in_preview_ = in_preview;

    /* Fill in our print args */

    print_args_.format              = PR_FMT_TEXT;
    print_args_.print_summary       = pd_ui_->formatGroupBox->summaryEnabled();
    print_args_.print_col_headings  = pd_ui_->formatGroupBox->includeColumnHeadingsEnabled();
    print_args_.print_hex           = pd_ui_->formatGroupBox->bytesEnabled();
    print_args_.hexdump_options     = pd_ui_->formatGroupBox->getHexdumpOptions();
    print_args_.print_formfeed      = pd_ui_->formFeedCheckBox->isChecked();

    print_args_.print_dissections = print_dissections_none;
    if (pd_ui_->formatGroupBox->detailsEnabled()) {
        if (pd_ui_->formatGroupBox->allCollapsedEnabled())
            print_args_.print_dissections = print_dissections_collapsed;
        else if (pd_ui_->formatGroupBox->asDisplayedEnabled())
            print_args_.print_dissections = print_dissections_as_displayed;
        else if (pd_ui_->formatGroupBox->allExpandedEnabled())
            print_args_.print_dissections = print_dissections_expanded;
    }

    // This should be identical to printer_. However, the QPrintPreviewWidget docs
    // tell us to draw on the printer handed to us by the paintRequested() signal.
    cur_printer_ = printer;
    cur_painter_ = &painter;
    if (!painter.begin(printer)) {
        QMessageBox::warning(this, tr("Print Error"),
                             QString(tr("Unable to print to %1.")).arg(printer_.printerName()),
                             QMessageBox::Ok);
        close();
    }
    // Don't show a progress bar if we're previewing; if it takes a
    // significant amount of time to generate a preview of the first
    // page, We Have A Real Problem
    cf_print_packets(cap_file_, &print_args_, in_preview ? FALSE : TRUE);
    cur_printer_ = NULL;
    cur_painter_ = NULL;
    painter.end();
}

void PrintDialog::paintPreview(QPrinter *printer)
{
    printPackets(printer, true);
}

void PrintDialog::checkValidity()
{
    bool enable = true;

    if (!pd_ui_->rangeGroupBox->isValid()) enable = false;

    if (!pd_ui_->formatGroupBox->summaryEnabled() &&
        !pd_ui_->formatGroupBox->detailsEnabled() &&
        !pd_ui_->formatGroupBox->bytesEnabled())
    {
        enable = false;
    }

    print_bt_->setEnabled(enable);
    preview_->updatePreview();
}

void PrintDialog::on_buttonBox_helpRequested()
{
    mainApp->helpTopicAction(HELP_PRINT_DIALOG);
}

void PrintDialog::on_buttonBox_clicked(QAbstractButton *button)
{
    QPrintDialog *print_dlg;
    QPageSetupDialog *ps_dlg;
#ifdef Q_OS_WIN
        HANDLE da_ctx;
#endif

    switch (pd_ui_->buttonBox->buttonRole(button)) {
    case QDialogButtonBox::ActionRole:
        int result;
#ifdef Q_OS_WIN
        da_ctx = set_thread_per_monitor_v2_awareness();
#endif
        print_dlg = new QPrintDialog(&printer_, this);
        result = print_dlg->exec();
#ifdef Q_OS_WIN
        revert_thread_per_monitor_v2_awareness(da_ctx);
#endif
        if (result == QDialog::Accepted) {
            printPackets(&printer_, false);
            done(result);
        }
        break;
    case QDialogButtonBox::ResetRole:
#ifdef Q_OS_WIN
        da_ctx = set_thread_per_monitor_v2_awareness();
#endif
        ps_dlg = new QPageSetupDialog(&printer_, this);
        ps_dlg->exec();
#ifdef Q_OS_WIN
        revert_thread_per_monitor_v2_awareness(da_ctx);
#endif
        preview_->updatePreview();
        break;
    default: // Help, Cancel
        break;
    }
}