/
galleryutil.cpp
761 lines (644 loc) · 20.6 KB
/
galleryutil.cpp
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
/* ============================================================
* File : exifutil.cpp
* Description :
*
* This program is free software; you can redistribute it
* and/or modify it under the terms of the GNU General
* Public License as published bythe Free Software Foundation;
* either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* ============================================================ */
// qt
#include <QDir>
// myth
#include <mythcontext.h>
#include <mythdbcon.h>
#include <util.h>
#include <mythdirs.h>
#include <mythdb.h>
#include <mythuihelper.h>
// mythgallery
#include "config.h"
#include "galleryutil.h"
#include "thumbgenerator.h"
#ifdef DCRAW_SUPPORT
#include "../dcrawplugin/dcrawformats.h"
#endif // DCRAW_SUPPORT
#ifdef EXIF_SUPPORT
#include <libexif/exif-data.h>
#include <libexif/exif-entry.h>
// include "exif.hpp"
#endif // EXIF_SUPPORT
#define LOC QString("GalleryUtil:")
#define LOC_ERR QString("GalleryUtil, Error:")
static QFileInfo MakeUnique(const QFileInfo &dest);
static QFileInfo MakeUniqueDirectory(const QFileInfo &dest);
static bool FileCopy(const QFileInfo &src, const QFileInfo &dst);
static bool FileMove(const QFileInfo &src, const QFileInfo &dst);
static bool FileDelete(const QFileInfo &file);
QStringList GalleryUtil::GetImageFilter(void)
{
QStringList filt;
filt.push_back("*.jpg");
filt.push_back("*.jpeg");
filt.push_back("*.png");
filt.push_back("*.tif");
filt.push_back("*.tiff");
filt.push_back("*.bmp");
filt.push_back("*.gif");
#ifdef DCRAW_SUPPORT
filt << DcrawFormats::getFilters();
#endif // DCRAW_SUPPORT
return filt;
}
QStringList GalleryUtil::GetMovieFilter(void)
{
QStringList filt;
filt.push_back("*.avi");
filt.push_back("*.mpg");
filt.push_back("*.mp4");
filt.push_back("*.mpeg");
filt.push_back("*.mov");
filt.push_back("*.wmv");
return filt;
}
QStringList GalleryUtil::GetMediaFilter(void)
{
QStringList filt = GetImageFilter();
filt << GetMovieFilter();
return filt;
}
bool GalleryUtil::IsImage(const QString &filePath)
{
QFileInfo fi(filePath);
if (fi.isDir())
return false;
QStringList filt = GetImageFilter();
QStringList::const_iterator it = filt.begin();
for (; it != filt.end(); ++it)
{
if ((*it).contains(fi.suffix().toLower()))
return true;
}
return false;
}
bool GalleryUtil::IsMovie(const QString &filePath)
{
QFileInfo fi(filePath);
if (fi.isDir())
return false;
QStringList filt = GetMovieFilter();
QStringList::const_iterator it = filt.begin();
for (; it != filt.end(); ++it)
{
if ((*it).contains(fi.suffix().toLower()))
return true;
}
return false;
}
long GalleryUtil::GetNaturalRotation(const QString &filePathString)
{
long rotateAngle = 0;
QByteArray filePathBA = filePathString.toLocal8Bit();
const char *filePath = filePathBA.constData();
try
{
#ifdef EXIF_SUPPORT
char *exifvalue = new char[1024];
ExifData *data = exif_data_new_from_file (filePath);
if (data)
{
for (int i = 0; i < EXIF_IFD_COUNT; i++)
{
ExifEntry *entry = exif_content_get_entry (data->ifd[i],
EXIF_TAG_ORIENTATION);
ExifByteOrder byteorder = exif_data_get_byte_order (data);
if (entry)
{
ExifShort v_short = exif_get_short (entry->data, byteorder);
VERBOSE(VB_GENERAL|VB_EXTRA, QString("Exif entry=%1").arg(v_short));
/* See http://sylvana.net/jpegcrop/exif_orientation.html*/
if (v_short == 8)
{
rotateAngle = -90;
}
else if (v_short == 6)
{
rotateAngle = 90;
}
break;
}
}
exif_data_free(data);
}
else
{
VERBOSE(VB_FILE, LOC_ERR +
QString("Could not load exif data from '%1'")
.arg(filePath));
}
delete [] exifvalue;
/*
Exiv2::ExifData exifData;
int rc = exifData.read(filePath);
if (!rc)
{
Exiv2::ExifKey key = Exiv2::ExifKey("Exif.Image.Orientation");
Exiv2::ExifData::iterator pos = exifData.findKey(key);
if (pos != exifData.end())
{
long orientation = pos->toLong();
switch (orientation)
{
case 6:
rotateAngle = 90;
break;
case 8:
rotateAngle = -90;
break;
default:
rotateAngle = 0;
break;
}
}
}
*/
#endif // EXIF_SUPPORT
}
catch (...)
{
VERBOSE(VB_IMPORTANT, LOC_ERR +
QString("Failed to extract EXIF headers from '%1'")
.arg(filePathString));
}
return rotateAngle;
}
bool GalleryUtil::LoadDirectory(ThumbList& itemList, const QString& dir,
int sortorder, bool recurse,
ThumbHash *itemHash, ThumbGenerator* thumbGen)
{
QString blah = dir;
QDir d(blah);
QString currDir = d.absolutePath();
bool isGallery;
QFileInfoList gList = d.entryInfoList(QStringList("serial*.dat"),
QDir::Files);
isGallery = (gList.count() != 0);
// Create .thumbcache dir if neccesary
if (thumbGen)
thumbGen->getThumbcacheDir(currDir);
QFileInfoList list = d.entryInfoList(GetMediaFilter(),
QDir::Files | QDir::AllDirs,
(QDir::SortFlag)sortorder);
if (list.isEmpty())
return false;
QFileInfoList::const_iterator it = list.begin();
const QFileInfo *fi;
if (thumbGen)
{
thumbGen->cancel();
thumbGen->setDirectory(currDir, isGallery);
}
while (it != list.end())
{
fi = &(*it);
++it;
if (fi->fileName() == "." || fi->fileName() == "..")
continue;
// remove these already-resized pictures.
if (isGallery && (
(fi->fileName().indexOf(".thumb.") > 0) ||
(fi->fileName().indexOf(".sized.") > 0) ||
(fi->fileName().indexOf(".highlight.") > 0)))
continue;
if (fi->isDir() && recurse)
{
GalleryUtil::LoadDirectory(
itemList, QDir::cleanPath(fi->absoluteFilePath()),
sortorder, true, itemHash, thumbGen);
}
else
{
ThumbItem *item = new ThumbItem(
fi->fileName(),
QDir::cleanPath(fi->absoluteFilePath()), fi->isDir());
itemList.append(item);
if (itemHash)
itemHash->insert(item->GetName(), item);
if (thumbGen)
thumbGen->addFile(item->GetName());
}
}
return isGallery;
}
QString GalleryUtil::GetCaption(const QString &filePath)
{
QString caption("");
try
{
#ifdef EXIF_SUPPORT
char *exifvalue = new char[1024];
ExifData *data = exif_data_new_from_file(
filePath.toLocal8Bit().constData());
if (data)
{
for (int i = 0; i < EXIF_IFD_COUNT; i++)
{
ExifEntry *entry = exif_content_get_entry (data->ifd[i],
EXIF_TAG_USER_COMMENT);
if (entry)
{
#if NEW_LIB_EXIF
exif_entry_get_value(entry, exifvalue, 1023);
caption = exifvalue;
#else
caption = exif_entry_get_value(entry);
#endif
// Found one, done
if(!caption.trimmed().isEmpty())
break;
}
entry = exif_content_get_entry (data->ifd[i],
EXIF_TAG_IMAGE_DESCRIPTION);
if (entry)
{
#if NEW_LIB_EXIF
exif_entry_get_value(entry, exifvalue, 1023);
caption = exifvalue;
#else
caption = exif_entry_get_value(entry);
#endif
// Found one, done
if(!caption.trimmed().isEmpty())
break;
}
}
exif_data_free(data);
}
else
{
VERBOSE(VB_FILE, LOC_ERR +
QString("Could not load exif data from '%1'")
.arg(filePath));
}
delete [] exifvalue;
#endif // EXIF_SUPPORT
}
catch (...)
{
VERBOSE(VB_IMPORTANT, LOC_ERR +
QString("Failed to extract EXIF headers from '%1'")
.arg(filePath));
}
return caption;
}
bool GalleryUtil::Copy(const QFileInfo &src, QFileInfo &dst)
{
if (src.isDir())
return CopyDirectory(src, dst);
dst = MakeUnique(dst);
if (!FileCopy(src, dst))
return false;
MSqlQuery query(MSqlQuery::InitCon());
query.prepare("INSERT INTO gallerymetadata (image, angle) "
"SELECT :IMAGENEW , angle "
"FROM gallerymetadata "
"WHERE image = :IMAGEOLD");
query.bindValue(":IMAGENEW", dst.absoluteFilePath());
query.bindValue(":IMAGEOLD", src.absoluteFilePath());
if (query.exec())
return true;
// try to undo copy on DB failure
FileDelete(dst);
return false;
}
bool GalleryUtil::Move(const QFileInfo &src, QFileInfo &dst)
{
if (src.isDir())
return MoveDirectory(src, dst);
dst = MakeUnique(dst);
if (!FileMove(src, dst))
return false;
MSqlQuery query(MSqlQuery::InitCon());
query.prepare("UPDATE gallerymetadata "
"SET image = :IMAGENEW "
"WHERE image = :IMAGEOLD");
query.bindValue(":IMAGENEW", dst.absoluteFilePath());
query.bindValue(":IMAGEOLD", src.absoluteFilePath());
if (query.exec())
return true;
// try to undo move on DB failure
FileMove(dst, src);
return false;
}
bool GalleryUtil::Delete(const QFileInfo &file)
{
if (!file.exists())
return false;
if (file.isDir())
return DeleteDirectory(file);
MSqlQuery query(MSqlQuery::InitCon());
query.prepare("DELETE FROM gallerymetadata "
"WHERE image = :IMAGE ;");
query.bindValue(":IMAGE", file.absoluteFilePath());
if (query.exec())
return FileDelete(file);
return false;
}
bool GalleryUtil::Rename(const QString &currDir, const QString &oldName,
const QString &newName)
{
// make sure there isn't already a file/directory with the same name
QFileInfo fi(currDir + '/' + newName);
if (fi.exists())
return false;
fi.setFile(currDir + '/' + oldName);
if (fi.isDir())
return RenameDirectory(currDir, oldName, newName);
// rename the file
QDir cdir(currDir);
if (!cdir.rename(oldName, newName))
return false;
// rename the file's thumbnail if it exists
if (QFile::exists(currDir + "/.thumbcache/" + oldName))
{
QDir d(currDir + "/.thumbcache/");
d.rename(oldName, newName);
}
int prefixLen = gCoreContext->GetSetting("GalleryDir").length();
QString path = GetConfDir() + "/MythGallery";
path += currDir.right(currDir.length() - prefixLen);
path += QString("/.thumbcache/");
if (QFile::exists(path + oldName))
{
QDir d(path);
d.rename(oldName, newName);
}
// fix up the metadata in the database
MSqlQuery query(MSqlQuery::InitCon());
query.prepare("UPDATE gallerymetadata "
"SET image = :IMAGENEW "
"WHERE image = :IMAGEOLD");
query.bindValue(":IMAGENEW", QString(currDir + '/' + newName));
query.bindValue(":IMAGEOLD", QString(currDir + '/' + oldName));
if (query.exec())
return true;
// try to undo rename on DB failure
cdir.rename(newName, oldName);
return false;
}
QSize GalleryUtil::ScaleToDest(const QSize &src, const QSize &dest, ScaleMax scaleMax)
{
QSize sz = src;
// calculate screen pixel aspect ratio
double pixelAspect = GetMythUI()->GetPixelAspectRatio();
// calculate image aspect ratio
double imageAspect = 1.0;
if ((sz.width() > 0) && (sz.height() > 0))
imageAspect = (double)sz.width() / (double)sz.height();
int scaleWidth = sz.width();
int scaleHeight = sz.height();
switch (scaleMax)
{
case kScaleToFill:
// scale-max to dest width for most images
scaleWidth = dest.width();
scaleHeight = (int)((float)dest.width() * pixelAspect / imageAspect);
if (scaleHeight < dest.height())
{
// scale-max to dest height for extra wide images
scaleWidth = (int)((float)dest.height() * imageAspect / pixelAspect);
scaleHeight = dest.height();
}
break;
case kReduceToFit:
// Reduce to fit (but never enlarge)
if (scaleWidth <= dest.width() && scaleHeight <= dest.height())
break;
// Fall through
case kScaleToFit:
// scale-min to dest height for most images
scaleWidth = (int)((float)dest.height() * imageAspect / pixelAspect);
scaleHeight = dest.height();
if (scaleWidth > dest.width())
{
// scale-min to dest width for extra wide images
scaleWidth = dest.width();
scaleHeight = (int)((float)dest.width() * pixelAspect / imageAspect);
}
break;
default:
break;
}
if (scaleWidth != sz.width() || scaleHeight != sz.height())
sz.scale(scaleWidth, scaleHeight, Qt::KeepAspectRatio);
return sz;
}
bool GalleryUtil::CopyDirectory(const QFileInfo src, QFileInfo &dst)
{
QDir srcDir(src.absoluteFilePath());
dst = MakeUniqueDirectory(dst);
if (!dst.exists())
{
srcDir.mkdir(dst.absoluteFilePath());
dst.refresh();
}
if (!dst.exists() || !dst.isDir())
return false;
bool ok = true;
QDir dstDir(dst.absoluteFilePath());
QFileInfoList list = srcDir.entryInfoList();
QFileInfoList::const_iterator it = list.begin();
for (; it != list.end(); ++it)
{
const QString fn = it->fileName();
if (fn != "." && fn != "..")
{
QFileInfo dfi(dstDir, fn);
ok &= Copy(*it, dfi);
}
}
return ok;
}
bool GalleryUtil::MoveDirectory(const QFileInfo src, QFileInfo &dst)
{
QDir srcDir(src.absoluteFilePath());
dst = MakeUniqueDirectory(dst);
if (!dst.exists())
{
srcDir.mkdir(dst.absoluteFilePath());
dst.refresh();
}
if (!dst.exists() || !dst.isDir())
return false;
bool ok = true;
QDir dstDir(dst.absoluteFilePath());
QFileInfoList list = srcDir.entryInfoList();
QFileInfoList::const_iterator it = list.begin();
for (; it != list.end(); ++it)
{
const QString fn = it->fileName();
if (fn != "." && fn != "..")
{
QFileInfo dfi(dstDir, fn);
ok &= Move(*it, dfi);
}
}
return ok && FileDelete(src);
}
bool GalleryUtil::DeleteDirectory(const QFileInfo &dir)
{
if (!dir.exists())
return false;
QDir srcDir(dir.absoluteFilePath());
QFileInfoList list = srcDir.entryInfoList();
QFileInfoList::const_iterator it = list.begin();
for (; it != list.end(); ++it)
{
const QString fn = it->fileName();
if (fn != "." && fn != "..")
Delete(*it);
}
return FileDelete(dir);
}
bool GalleryUtil::RenameDirectory(const QString &currDir, const QString &oldName,
const QString &newName)
{
// rename the directory
QDir cdir(currDir);
if (!cdir.rename(oldName, newName))
return false;
// rename the directory's thumbnail if it exists in the parent directory
if (QFile::exists(currDir + "/.thumbcache/" + oldName))
{
QDir d(currDir + "/.thumbcache/");
d.rename(oldName, newName);
}
// also look in HOME directory for any thumbnails
int prefixLen = gCoreContext->GetSetting("GalleryDir").length();
QString path = GetConfDir() + "/MythGallery";
path += currDir.right(currDir.length() - prefixLen) + '/';
if (QFile::exists(path + oldName))
{
QDir d(path);
d.rename(oldName, newName);
// rename this directory's thumbnail
path += QString(".thumbcache/");
if (QFile::exists(path + oldName))
{
QDir d(path);
d.rename(oldName, newName);
}
}
// fix up the metadata in the database
MSqlQuery query(MSqlQuery::InitCon());
query.prepare("SELECT image, angle FROM gallerymetadata "
"WHERE image LIKE :IMAGEOLD");
query.bindValue(":IMAGEOLD", QString(currDir + '/' + oldName + '%'));
if (query.exec())
{
while (query.next())
{
QString oldImage = query.value(0).toString();
QString newImage = oldImage;
newImage = newImage.replace(currDir + '/' + oldName,
currDir + '/' + newName);
MSqlQuery subquery(MSqlQuery::InitCon());
subquery.prepare("UPDATE gallerymetadata "
"SET image = :IMAGENEW "
"WHERE image = :IMAGEOLD");
subquery.bindValue(":IMAGENEW", newImage);
subquery.bindValue(":IMAGEOLD", oldImage);
if (!subquery.exec())
MythDB::DBError("GalleryUtil::RenameDirectory - update image",
subquery);
}
}
return true;
}
static QFileInfo MakeUnique(const QFileInfo &dest)
{
QFileInfo newDest = dest;
for (uint i = 0; newDest.exists(); i++)
{
QString basename = QString("%1_%2.%3")
.arg(dest.baseName()).arg(i).arg(dest.completeSuffix());
newDest.setFile(dest.dir(), basename);
VERBOSE(VB_GENERAL, LOC_ERR +
QString("Need to find a new name for '%1' trying '%2'")
.arg(dest.absoluteFilePath()).arg(newDest.absoluteFilePath()));
}
return newDest;
}
static QFileInfo MakeUniqueDirectory(const QFileInfo &dest)
{
QFileInfo newDest = dest;
for (uint i = 0; newDest.exists() && !newDest.isDir(); i++)
{
QString fullname = QString("%1_%2").arg(dest.absoluteFilePath()).arg(i);
newDest.setFile(fullname);
VERBOSE(VB_GENERAL, LOC_ERR +
QString("Need to find a new name for '%1' trying '%2'")
.arg(dest.absoluteFilePath()).arg(newDest.absoluteFilePath()));
}
return newDest;
}
static bool FileCopy(const QFileInfo &src, const QFileInfo &dst)
{
const int bufferSize = 16*1024;
QFile s(src.absoluteFilePath());
QFile d(dst.absoluteFilePath());
char buffer[bufferSize];
int len;
if (!s.open(QIODevice::ReadOnly))
return false;
if (!d.open(QIODevice::WriteOnly))
{
s.close();
return false;
}
len = s.read(buffer, bufferSize);
do
{
d.write(buffer, len);
len = s.read(buffer, bufferSize);
} while (len > 0);
s.close();
d.close();
return true;
}
static bool FileMove(const QFileInfo &src, const QFileInfo &dst)
{
// attempt to rename the file,
// this will fail if files are on different partitions
QByteArray source = src.absoluteFilePath().toLocal8Bit();
QByteArray dest = dst.absoluteFilePath().toLocal8Bit();
if (rename(source.constData(), dest.constData()) == 0)
{
return true;
}
// src and dst are on different mount points, move manually.
if (errno == EXDEV)
{
if (FileCopy(src, dst))
return FileDelete(src);
}
return false;
}
static bool FileDelete(const QFileInfo &file)
{
if (!file.isDir())
return QFile::remove(file.absoluteFilePath());
// delete .thumbcache
QDir srcDir(file.absoluteFilePath());
QFileInfo tc(srcDir, ".thumbcache");
GalleryUtil::Delete(tc);
srcDir.rmdir(srcDir.absolutePath());
return true;
}