1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the examples of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** BSD License Usage
18 ** Alternatively, you may use this file under the terms of the BSD license
19 ** as follows:
20 **
21 ** "Redistribution and use in source and binary forms, with or without
22 ** modification, are permitted provided that the following conditions are
23 ** met:
24 ** * Redistributions of source code must retain the above copyright
25 ** notice, this list of conditions and the following disclaimer.
26 ** * Redistributions in binary form must reproduce the above copyright
27 ** notice, this list of conditions and the following disclaimer in
28 ** the documentation and/or other materials provided with the
29 ** distribution.
30 ** * Neither the name of The Qt Company Ltd nor the names of its
31 ** contributors may be used to endorse or promote products derived
32 ** from this software without specific prior written permission.
33 **
34 **
35 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46 **
47 ** $QT_END_LICENSE$
48 **
49 ****************************************************************************/
50
51 #include "previewform.h"
52
53 #include <QApplication>
54 #include <QComboBox>
55 #include <QDialogButtonBox>
56 #include <QGridLayout>
57 #include <QLabel>
58 #include <QPlainTextEdit>
59 #include <QPushButton>
60 #include <QScreen>
61 #include <QTextCodec>
62 #include <QTextStream>
63
64 // Helpers for creating hex dumps
indent(QTextStream & str,int indent)65 static void indent(QTextStream &str, int indent)
66 {
67 for (int i = 0; i < indent; ++i)
68 str << ' ';
69 }
70
formatHex(QTextStream & str,const QByteArray & data)71 static void formatHex(QTextStream &str, const QByteArray &data)
72 {
73 const int fieldWidth = str.fieldWidth();
74 const QTextStream::FieldAlignment alignment = str.fieldAlignment();
75 const int base = str.integerBase();
76 const QChar padChar = str.padChar();
77 str.setIntegerBase(16);
78 str.setPadChar(QLatin1Char('0'));
79 str.setFieldAlignment(QTextStream::AlignRight);
80
81 const unsigned char *p = reinterpret_cast<const unsigned char *>(data.constBegin());
82 for (const unsigned char *end = p + data.size(); p < end; ++p) {
83 str << ' ';
84 str.setFieldWidth(2);
85 str << unsigned(*p);
86 str.setFieldWidth(fieldWidth);
87 }
88 str.setFieldAlignment(alignment);
89 str.setPadChar(padChar);
90 str.setIntegerBase(base);
91 }
92
formatPrintableCharacters(QTextStream & str,const QByteArray & data)93 static void formatPrintableCharacters(QTextStream &str, const QByteArray &data)
94 {
95 for (const char c : data) {
96 switch (c) {
97 case '\0':
98 str << "\\0";
99 break;
100 case '\t':
101 str << "\\t";
102 break;
103 case '\r':
104 str << "\\r";
105 break;
106 case '\n':
107 str << "\\n";
108 break;
109 default:
110 if (c >= 32 && uchar(c) < 127)
111 str << ' ' << c;
112 else
113 str << "..";
114 break;
115 }
116 }
117 }
118
formatHexDump(const QByteArray & data)119 static QString formatHexDump(const QByteArray &data)
120 {
121 enum { lineWidth = 16 };
122 QString result;
123 QTextStream str(&result);
124 str.setIntegerBase(16);
125 str.setPadChar(QLatin1Char('0'));
126 const int fieldWidth = str.fieldWidth();
127 const QTextStream::FieldAlignment alignment = str.fieldAlignment();
128 for (int a = 0, size = data.size(); a < size; a += lineWidth) {
129 str.setFieldAlignment(QTextStream::AlignRight);
130 str.setFieldWidth(8);
131 str << a;
132 str.setFieldWidth(fieldWidth);
133 str.setFieldAlignment(alignment);
134
135 const int end = qMin(a + lineWidth, size);
136 const QByteArray line = data.mid(a, end - a);
137
138 formatHex(str, line);
139 indent(str, 3 * (lineWidth - line.size()));
140
141 str << ' ';
142 formatPrintableCharacters(str, line);
143 indent(str, 2 * (lineWidth - line.size()));
144 str << '\n';
145 }
146 return result;
147 }
148
PreviewForm(QWidget * parent)149 PreviewForm::PreviewForm(QWidget *parent)
150 : QDialog(parent)
151 {
152 setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
153 encodingComboBox = new QComboBox;
154
155 QLabel *encodingLabel = new QLabel(tr("&Encoding:"));
156 encodingLabel->setBuddy(encodingComboBox);
157
158 textEdit = new QPlainTextEdit;
159 textEdit->setLineWrapMode(QPlainTextEdit::NoWrap);
160 textEdit->setReadOnly(true);
161 hexDumpEdit = new QPlainTextEdit;
162 hexDumpEdit->setLineWrapMode(QPlainTextEdit::NoWrap);
163 hexDumpEdit->setReadOnly(true);
164 hexDumpEdit->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
165
166 QDialogButtonBox *buttonBox =
167 new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
168 okButton = buttonBox->button(QDialogButtonBox::Ok);
169
170 connect(encodingComboBox, QOverload<int>::of(&QComboBox::activated),
171 this, &PreviewForm::updateTextEdit);
172 connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
173 connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
174
175 QGridLayout *mainLayout = new QGridLayout(this);
176 mainLayout->addWidget(encodingLabel, 0, 0);
177 mainLayout->addWidget(encodingComboBox, 0, 1);
178 tabWidget = new QTabWidget;
179 tabWidget->addTab(textEdit, tr("Preview"));
180 tabWidget->addTab(hexDumpEdit, tr("Hex Dump"));
181 mainLayout->addWidget(tabWidget, 1, 0, 1, 2);
182 statusLabel = new QLabel;
183 mainLayout->addWidget(statusLabel, 2, 0, 1, 2);
184 mainLayout->addWidget(buttonBox, 3, 0, 1, 2);
185
186 const QRect screenGeometry = screen()->geometry();
187 resize(screenGeometry.width() * 2 / 5, screenGeometry.height() / 2);
188 }
189
setCodecList(const QVector<QTextCodec * > & list)190 void PreviewForm::setCodecList(const QVector<QTextCodec *> &list)
191 {
192 encodingComboBox->clear();
193 for (const QTextCodec *codec : list) {
194 encodingComboBox->addItem(QLatin1String(codec->name()),
195 QVariant(codec->mibEnum()));
196 }
197 }
198
reset()199 void PreviewForm::reset()
200 {
201 decodedStr.clear();
202 textEdit->clear();
203 hexDumpEdit->clear();
204 statusLabel->clear();
205 statusLabel->setStyleSheet(QString());
206 okButton->setEnabled(false);
207 tabWidget->setCurrentIndex(0);
208 }
209
setEncodedData(const QByteArray & data)210 void PreviewForm::setEncodedData(const QByteArray &data)
211 {
212 reset();
213 encodedData = data;
214 hexDumpEdit->setPlainText(formatHexDump(data));
215 updateTextEdit();
216 }
217
updateTextEdit()218 void PreviewForm::updateTextEdit()
219 {
220 int mib = encodingComboBox->itemData(
221 encodingComboBox->currentIndex()).toInt();
222 const QTextCodec *codec = QTextCodec::codecForMib(mib);
223 const QString name = QLatin1String(codec->name());
224
225 QTextCodec::ConverterState state;
226 decodedStr = codec->toUnicode(encodedData.constData(), encodedData.size(), &state);
227
228 bool success = true;
229 if (state.remainingChars) {
230 success = false;
231 const QString message =
232 tr("%1: conversion error at character %2")
233 .arg(name).arg(encodedData.size() - state.remainingChars + 1);
234 statusLabel->setText(message);
235 statusLabel->setStyleSheet(QStringLiteral("background-color: \"red\";"));
236 } else if (state.invalidChars) {
237 statusLabel->setText(tr("%1: %n invalid characters", nullptr, state.invalidChars).arg(name));
238 statusLabel->setStyleSheet(QStringLiteral("background-color: \"yellow\";"));
239 } else {
240 statusLabel->setText(tr("%1: %n bytes converted", nullptr, encodedData.size()).arg(name));
241 statusLabel->setStyleSheet(QString());
242 }
243 if (success)
244 textEdit->setPlainText(decodedStr);
245 else
246 textEdit->clear();
247 okButton->setEnabled(success);
248 }
249