Debian Codegraph @

src/album/utils/baseutils.cpp

raw
1 /*
2 * Copyright (C) 2020 ~ 2021 Uniontech Software Technology Co., Ltd.
3 *
4 * Author: ZhangYong <[email protected]>
5 *
6 * Maintainer: ZhangYong <[email protected]>
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21 #include "baseutils.h"
22 #include "imageutils.h"
23 #include "application.h"
24 #include <stdio.h>
25 #include <fcntl.h>
26 #include <fstream>
27 #include <linux/fs.h>
28 #include <QApplication>
29 #include <QClipboard>
30 #include <QCryptographicHash>
31 #include <QDateTime>
32 #include <QDesktopServices>
33 #include <QDir>
34 #include <QFontMetrics>
35 #include <QFileInfo>
36 #include <QImage>
37 #include <QMimeData>
38 #include <QProcess>
39 #include <QUrl>
40 #include <QUrlQuery>
41 #include <QDebug>
42 #include <QTextStream>
43 #include <QtMath>
44 #include <QRegularExpression>
45
46 #include <DApplication>
47 #include <DDesktopServices>
48 #include <QImageReader>
49 #include <QMimeDatabase>
50
51 DWIDGET_USE_NAMESPACE
52
53 namespace utils {
54
55 namespace base {
56
57 const QString DATETIME_FORMAT_NORMAL = "yyyy.MM.dd";
58 const QString DATETIME_FORMAT_EXIF = "yyyy:MM:dd HH:mm:ss";
59
60 int stringHeight(const QFont &f, const QString &str)
61 {
62 QFontMetrics fm(f);
63 return fm.boundingRect(str).height();
64 }
65
66 QDateTime stringToDateTime(const QString &time)
67 {
68 QDateTime dt = QDateTime::fromString(time, DATETIME_FORMAT_EXIF);
69 if (! dt.isValid()) {
70 dt = QDateTime::fromString(time, DATETIME_FORMAT_NORMAL);
71 }
72 return dt;
73 }
74
75 void showInFileManager(const QString &path)
76 {
77 if (path.isEmpty() || !QFile::exists(path)) {
78 return;
79 }
80 QString m_Path = static_cast<QString>(path);
81
82 QStringList spc {"#", "&", "@", "!", "?"};
83 for (QString c : spc) {
84 m_Path.replace(c, QUrl::toPercentEncoding(c));
85 }
86 QUrl url = QUrl::fromUserInput(/*"\"" + */m_Path/* + "\""*/);
87 url.setPath(m_Path, QUrl::TolerantMode);
88 Dtk::Widget::DDesktopServices::showFileItem(url);
89 }
90
91 void copyImageToClipboard(const QStringList &paths)
92 {
93 // Get clipboard
94 QClipboard *cb = qApp->clipboard();
95
96 // Ownership of the new data is transferred to the clipboard.
97 QMimeData *newMimeData = new QMimeData();
98 QByteArray gnomeFormat = QByteArray("copy\n");
99 QString text;
100 QList<QUrl> dataUrls;
101 for (QString path : paths) {
102 if (!path.isEmpty())
103 text += path + '\n';
104 dataUrls << QUrl::fromLocalFile(path);
105 gnomeFormat.append(QUrl::fromLocalFile(path).toEncoded()).append("\n");
106 }
107
108 newMimeData->setText(text.endsWith('\n') ? text.left(text.length() - 1) : text);
109 newMimeData->setUrls(dataUrls);
110 gnomeFormat.remove(gnomeFormat.length() - 1, 1);
111 newMimeData->setData("x-special/gnome-copied-files", gnomeFormat);
112
113 // Set the mimedata
114 cb->setMimeData(newMimeData, QClipboard::Clipboard);
115 }
116
117 QString getFileContent(const QString &file)
118 {
119 QFile f(file);
120 QString fileContent = "";
121 if (f.open(QFile::ReadOnly)) {
122 fileContent = QLatin1String(f.readAll());
123 f.close();
124 }
125 return fileContent;
126 }
127
128 QString SpliteText(const QString &text, const QFont &font, int nLabelSize)
129 {
130 //LMH0424,之前是递归,现在改了算法,判断换行
131 QFontMetrics fm(font);
132 double dobuleTextSize = fm.horizontalAdvance(text);
133 double dobuleLabelSize = nLabelSize;
134 if (dobuleTextSize > dobuleLabelSize && dobuleLabelSize > 0 && dobuleTextSize < 10000) {
135 double splitCount = dobuleTextSize / dobuleLabelSize;
136 int nCount = int(splitCount + 1);
137 QString textSplite;
138 QString textTotal = text;
139 for (int index = 0; index < nCount; ++index) {
140 int nPos = 0;
141 long nOffset = 0;
142 for (int i = 0; i < text.size(); i++) {
143 nOffset += fm.width(text.at(i));
144 if (nOffset >= nLabelSize) {
145 nPos = i;
146 break;
147 }
148 }
149 nPos = (nPos - 1 < 0) ? 0 : nPos - 1;
150 QString qstrLeftData;
151 if (nCount - 1 == index) {
152 qstrLeftData = textTotal;
153 textSplite += qstrLeftData;
154 } else {
155 qstrLeftData = textTotal.left(nPos);
156 textSplite += qstrLeftData + "\n";
157 }
158 textTotal = textTotal.mid(nPos);
159 }
160 return textSplite;
161 } else {
162 return text;
163 }
164 }
165
166 QString hashByString(const QString &str)
167 {
168 return QString(QCryptographicHash::hash(str.toUtf8(), QCryptographicHash::Md5).toHex());
169 }
170
171 QString hashByData(const QString &str)
172 {
173 QFile file(str);
174 QString stHashValue;
175 if (file.open(QIODevice::ReadOnly)) { //只读方式打开
176 QCryptographicHash hash(QCryptographicHash::Md5);
177
178 QByteArray buf = file.read(1 * 1024 * 1024); // 每次读取10M
179 buf = buf.append(str.toUtf8());
180 hash.addData(buf); // 将数据添加到Hash中
181 stHashValue.append(hash.result().toHex());
182 }
183 return stHashValue;
184 }
185
186 //bool checkMimeData(const QMimeData *mimeData)
187 //{
188 // if (1 > mimeData->urls().size()) {
189 // return false;
190 // }
191 // QList<QUrl> urlList = mimeData->urls();
192 // using namespace utils::image;
193 // for (QUrl url : urlList) {
194 // const QString path = url.toLocalFile();
195 // QFileInfo fileinfo(path);
196 // if (fileinfo.isDir()) {
197 // auto finfos = getImagesAndVideoInfo(path, false);
198 // for (auto finfo : finfos) {
199 // if (imageSupportRead(finfo.absoluteFilePath()) || isVideo(finfo.absoluteFilePath())) {
200 // QFileInfo info(finfo.absoluteFilePath());
201 // QMimeDatabase db;
202 // QMimeType mt = db.mimeTypeForFile(info.filePath(), QMimeDatabase::MatchContent);
203 // QMimeType mt1 = db.mimeTypeForFile(info.filePath(), QMimeDatabase::MatchExtension);
204 // QString str = info.suffix().toLower();
205
206 // if (str.isEmpty()) {
207 // if (mt.name().startsWith("image/") || mt.name().startsWith("video/x-mng")) {
208 // if (utils::image::supportedImageFormats().contains(str, Qt::CaseInsensitive)) {
209 // return true;
210 // } else if (str.isEmpty()) {
211 // return true;
212 // }
213 // }
214 // if (mt.name().startsWith("video/") || mt.name().startsWith("application/x-matroska")) {
215 // return true;
216 // }
217 // } else {
218 // if (mt1.name().startsWith("image/") || mt1.name().startsWith("video/x-mng")) {
219 // if (utils::image::supportedImageFormats().contains(str, Qt::CaseInsensitive)) {
220 // return true;
221 // }
222 // }
223 // if (mt1.name().startsWith("video/") || mt1.name().startsWith("application/x-matroska")) {
224 // return true;
225 // }
226 // }
227 // }
228 // }
229 // } else if (imageSupportRead(path) || isVideo(path)) {
230 //// paths << path;
231 // QFileInfo info(path);
232 // QMimeDatabase db;
233 // QMimeType mt = db.mimeTypeForFile(info.filePath(), QMimeDatabase::MatchContent);
234 // QMimeType mt1 = db.mimeTypeForFile(info.filePath(), QMimeDatabase::MatchExtension);
235 // QString str = info.suffix().toLower();
236 // if (str.isEmpty()) {
237 // if (mt.name().startsWith("image/") || mt.name().startsWith("video/x-mng")) {
238 // if (utils::image::supportedImageFormats().contains(str, Qt::CaseInsensitive)) {
239 // return true;
240 // } else if (str.isEmpty()) {
241 // return true;
242 // }
243 // }
244 // if (mt.name().startsWith("video/") || mt.name().startsWith("application/x-matroska")) {
245 // return true;
246 // }
247 // } else {
248 // if (mt1.name().startsWith("image/") || mt1.name().startsWith("video/x-mng")) {
249 // if (utils::image::supportedImageFormats().contains(str, Qt::CaseInsensitive)) {
250 // return true;
251 // }
252 // }
253 // if (mt1.name().startsWith("video/") || mt1.name().startsWith("application/x-matroska")) {
254 // return true;
255 // }
256 // }
257 // return false;
258 // }
259 // }
260 // return false;
261 //}
262
263 QPixmap renderSVG(const QString &filePath, const QSize &size)
264 {
265 QImageReader reader;
266 QPixmap pixmap;
267
268 reader.setFileName(filePath);
269
270 if (reader.canRead() && reader.imageCount() > 0) {
271 const qreal ratio = dApp->getDAppNew()->devicePixelRatio();
272 reader.setScaledSize(size * ratio);
273 pixmap = QPixmap::fromImage(reader.read());
274 pixmap.setDevicePixelRatio(ratio);
275 } else {
276 pixmap.load(filePath);
277 }
278
279 return pixmap;
280 }
281
282 QString mkMutiDir(const QString &path) //创建多级目录
283 {
284 QDir dir(path);
285 if (dir.exists(path)) {
286 return path;
287 }
288 QString parentDir = mkMutiDir(path.mid(0, path.lastIndexOf('/')));
289 QString dirname = path.mid(path.lastIndexOf('/') + 1);
290 QDir parentPath(parentDir);
291 if (!dirname.isEmpty())
292 parentPath.mkpath(dirname);
293 return parentDir + "/" + dirname;
294 }
295 //根据源文件路径生产缩略图路径
296 QString filePathToThumbnailPath(const QString &filePath, QString dataHash)
297 {
298 QString thumbnailPath = albumGlobal::CACHE_PATH + filePath;
299
300 QFileInfo temDir(filePath);
301 //如果hash为空,制作新的hash
302 if (dataHash.isEmpty()) {
303 dataHash = hashByData(filePath);
304 }
305
306 thumbnailPath = albumGlobal::CACHE_PATH + temDir.path() + "/" + dataHash + ".png";
307 return thumbnailPath;
308 }
309
310 bool checkMimeUrls(const QList<QUrl> urls)
311 {
312 if (1 > urls.size()) {
313 return false;
314 }
315 QList<QUrl> urlList = urls;
316 using namespace utils::image;
317 for (QUrl url : urlList) {
318 const QString path = url.toLocalFile();
319 QFileInfo fileinfo(path);
320 if (fileinfo.isDir()) {
321 auto finfos = getImagesAndVideoInfo(path, false);
322 for (auto finfo : finfos) {
323 if (imageSupportRead(finfo.absoluteFilePath()) || isVideo(finfo.absoluteFilePath())) {
324 return true;
325 }
326 }
327 } else if (imageSupportRead(path) || isVideo(path)) {
328 return true;
329 }
330 }
331 return false;
332 }
333
334 QUrl UrlInfo(QString path)
335 {
336 QUrl url;
337 // Just check if the path is an existing file.
338 if (QFile::exists(path)) {
339 url = QUrl::fromLocalFile(QDir::current().absoluteFilePath(path));
340 return url;
341 }
342
343 const auto match = QRegularExpression(QStringLiteral(":(\\d+)(?::(\\d+))?:?$")).match(path);
344
345 if (match.isValid()) {
346 // cut away line/column specification from the path.
347 path.chop(match.capturedLength());
348 }
349
350 // make relative paths absolute using the current working directory
351 // prefer local file, if in doubt!
352 url = QUrl::fromUserInput(path, QDir::currentPath(), QUrl::AssumeLocalFile);
353
354 // in some cases, this will fail, e.g.
355 // assume a local file and just convert it to an url.
356 if (!url.isValid()) {
357 // create absolute file path, we will e.g. pass this over dbus to other processes
358 url = QUrl::fromLocalFile(QDir::current().absoluteFilePath(path));
359 }
360 return url;
361 }
362
363 int daysDifferenceBetweenTime(const QDateTime &start, const QDateTime &end)
364 {
365 int daysSec = 24 * 60 * 60;
366 int stime = static_cast<int>(start.toTime_t());
367 int etime = static_cast<int>(end.toTime_t());
368 return ((etime - stime) / daysSec);
369 }
370
371 QString audioIndex2str(const int &index)
372 {
373 QStringList audioList = {"mp2", "mp3", "aac", "ac3", "dts", "vorbis", "dvaudio", "wmav1", "wmav2", "mace3", "mace6",
374 "vmdaudio", "flac", "mp3adu", "mp3on4", "shorten", "alac", "westwood_snd1", "gsm", "qdm2",
375 "cook", "truespeech", "tta", "smackaudio", "qcelp", "wavpack", "dsicinaudio", "imc",
376 "musepack7", "mlp", "gsm_ms", "atrac3", "ape", "nellymoser", "musepack8", "speex", "wmavoice",
377 "wmapro", "wmalossless", "atrac3p", "eac3", "sipr", "mp1", "twinvq", "truehd", "mp4als",
378 "atrac1", "binkaudio_rdft", "binkaudio_dct", "aac_latm", "qdmc", "celt", "g723_1", "g729",
379 "8svx_exp", "8svx_fib", "bmv_audio", "ralf", "iac", "ilbc", "opus", "comfort_noise", "tak",
380 "metasound", "paf_audio", "on2avc", "dss_sp", "codec2", "ffwavesynth", "sonic", "sonic_ls",
381 "evrc", "smv", "dsd_lsbf", "dsd_msbf", "dsd_lsbf_planar", "dsd_msbf_planar", "4gv",
382 "interplay_acm", "xma1", "xma2", "dst", "atrac3al", "atrac3pal", "dolby_e", "aptx", "aptx_hd",
383 "sbc", "atrac9"
384 };
385 QMap<int, QString> codecMap;
386 for (int i = 0; i < audioList.size(); i++) {
387 codecMap.insert(i + 86016, audioList[i]);
388 }
389 QString aa = codecMap[index];
390 return aa;
391 }
392
393 QString videoIndex2str(const int &index)
394 {
395 QStringList videoList = {"none", "mpeg1video", "mpeg2video", "h261", "h263", "rv10", "rv20",
396 "mjpeg", "mjpegb", "ljpeg", "sp5x", "jpegls", "mpeg4", "rawvideo", "msmpeg4v1",
397 "msmpeg4v2", "msmpeg4v3", "wmv1", "wmv2", "h263p", "h263i", "flv1", "svq1",
398 "svq3", "dvvideo", "huffyuv", "cyuv", "h264", "indeo3", "vp3", "theora",
399 "asv1", "asv2", "ffv1", "4xm", "vcr1", "cljr", "mdec", "roq", "interplay_video",
400 "xan_wc3", "xan_wc4", "rpza", "cinepak", "ws_vqa", "msrle", "msvideo1", "idcin",
401 "8bps", "smc", "flic", "truemotion1", "vmdvideo", "mszh", "zlib", "qtrle", "tscc",
402 "ulti", "qdraw", "vixl", "qpeg", "png", "ppm", "pbm", "pgm", "pgmyuv", "pam", "ffvhuff",
403 "rv30", "rv40", "vc1", "wmv3", "loco", "wnv1", "aasc", "indeo2", "fraps", "truemotion2",
404 "bmp", "cscd", "mmvideo", "zmbv", "avs", "smackvideo", "nuv", "kmvc", "flashsv",
405 "cavs", "jpeg2000", "vmnc", "vp5", "vp6", "vp6f", "targa", "dsicinvideo", "tiertexseqvideo",
406 "tiff", "gif", "dxa", "dnxhd", "thp", "sgi", "c93", "bethsoftvid", "ptx", "txd", "vp6a",
407 "amv", "vb", "pcx", "sunrast", "indeo4", "indeo5", "mimic", "rl2", "escape124", "dirac", "bfi",
408 "cmv", "motionpixels", "tgv", "tgq", "tqi", "aura", "aura2", "v210x", "tmv", "v210", "dpx",
409 "mad", "frwu", "flashsv2", "cdgraphics", "r210", "anm", "binkvideo", "iff_ilbm", "kgv1",
410 "yop", "vp8", "pictor", "ansi", "a64_multi", "a64_multi5", "r10k", "mxpeg", "lagarith",
411 "prores", "jv", "dfa", "wmv3image", "vc1image", "utvideo", "bmv_video", "vble", "dxtory",
412 "v410", "xwd", "cdxl", "xbm", "zerocodec", "mss1", "msa1", "tscc2", "mts2", "cllc", "mss2",
413 "vp9", "aic", "escape130", "g2m", "webp", "hnm4_video", "hevc", "fic", "alias_pix",
414 "brender_pix", "paf_video", "exr", "vp7", "sanm", "sgirle", "mvc1", "mvc2", "hqx", "tdsc",
415 "hq_hqa", "hap", "dds", "dxv", "screenpresso", "rscc", "avs2"
416 };
417 QStringList PCMList = {"pcm_s16le", "pcm_s16be", "pcm_u16le", "pcm_u16be", "pcm_s8", "pcm_u8", "pcm_mulaw"
418 "pcm_alaw", "pcm_s32le", "pcm_s32be", "pcm_u32le", "pcm_u32be", "pcm_s24le", "pcm_s24be"
419 "pcm_u24le", "pcm_u24be", "pcm_s24daud", "pcm_zork", "pcm_s16le_planar", "pcm_dvd"
420 "pcm_f32be", "pcm_f32le", "pcm_f64be", "pcm_f64le", "pcm_bluray", "pcm_lxf", "s302m"
421 "pcm_s8_planar", "pcm_s24le_planar", "pcm_s32le_planar", "pcm_s16be_planar"
422 };
423 QStringList ADPCMList = {"adpcm_ima_qt", "adpcm_ima_wav", "adpcm_ima_dk3", "adpcm_ima_dk4"
424 "adpcm_ima_ws", "adpcm_ima_smjpeg", "adpcm_ms", "adpcm_4xm", "adpcm_xa", "adpcm_adx"
425 "adpcm_ea", "adpcm_g726", "adpcm_ct", "adpcm_swf", "adpcm_yamaha", "adpcm_sbpro_4"
426 "adpcm_sbpro_3", "adpcm_sbpro_2", "adpcm_thp", "adpcm_ima_amv", "adpcm_ea_r1"
427 "adpcm_ea_r3", "adpcm_ea_r2", "adpcm_ima_ea_sead", "adpcm_ima_ea_eacs", "adpcm_ea_xas"
428 "adpcm_ea_maxis_xa", "adpcm_ima_iss", "adpcm_g722", "adpcm_ima_apc", "adpcm_vima"
429 };
430 QStringList AMRList = {"amr_nb", "amr_wb"};
431 QStringList realAudioList = {"ra_144", "ra_288" };
432 QMap<int, QString> codecMap;
433 for (int i = 0; i < videoList.size(); i++) {
434 codecMap.insert(i, videoList[i]);
435 }
436 for (int i = 0; i < PCMList.size(); i++) {
437 codecMap.insert(i + 65536, PCMList[i]);
438 }
439 for (int i = 0; i < ADPCMList.size(); i++) {
440 codecMap.insert(i + 69632, ADPCMList[i]);
441 }
442 codecMap.insert(73728, "amr_nb");
443 codecMap.insert(73729, "amr_wb");
444 codecMap.insert(77824, "ra_144");
445 codecMap.insert(77825, "ra_288");
446 QString aa = codecMap[index];
447 return aa;
448 }
449
450 QString Time2str(const qint64 &seconds)
451 {
452 QTime d(0, 0, 0);
453 if (seconds < DAYSECONDS) {
454 d = d.addSecs(static_cast<int>(seconds));
455 return d.toString("hh:mm:ss");
456 } else {
457 d = d.addSecs(static_cast<int>(seconds));
458 int add = static_cast<int>(seconds / DAYSECONDS) * 24;
459 QString dayOut = d.toString("hh:mm:ss");
460 dayOut.replace(0, 2, QString::number(add + dayOut.left(2).toInt()));
461 return dayOut;
462 }
463 }
464
465 bool isVideo(QString path)
466 {
467 QFileInfo temDir(path);
468 QString fileName = "*." + temDir.suffix().toLower(); //扩展名
469 return m_videoFiletypes.contains(fileName);
470 }
471
472 } // namespace base
473
474 } // namespace utils