summaryrefslogtreecommitdiffstats
path: root/kipi-plugins/jpeglossless/utils.cpp
blob: 4347c8cb0537b3d826ddbdb51b6432625171ada1 (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
/* ============================================================
 *
 * This file is a part of kipi-plugins project
 * http://www.kipi-plugins.org
 *
 * Date        : 2003-12-03
 * Description : misc utils to used in batch process
 * 
 * Copyright (C) 2003-2005 by Renchi Raju <renchi@pooh.tam.uiuc.edu>
 * Copyright (C) 2004-2007 by Marcel Wiesweg <marcel dot wiesweg at gmx dot de>
 * Copyright (C) 2006-2007 by Gilles Caulier <caulier dot gilles at gmail dot com>
 *
 * NOTE: Do not use kdDebug() in this implementation because 
 *       it will be multithreaded. Use qDebug() instead. 
 *       See B.K.O #133026 for details.
 *
 * This program is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General
 * Public License as published by the 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.
 * 
 * ============================================================ */

// C Ansi includes.

extern "C" 
{
#include <sys/types.h>
#include <sys/stat.h>
#include <utime.h>
#include <unistd.h>
}

// TQt includes.

#include <tqfileinfo.h>
#include <tqimage.h>
#include <tqstring.h>
#include <tqfile.h>
#include <tqdir.h>

// KDE includes.

#include <ktempfile.h>
#include <kprocess.h>
#include <klocale.h>
#include <kurl.h>

// LibKExiv2 includes. 

#include <libkexiv2/kexiv2.h>

// LibKDcraw includes.

#include <libkdcraw/version.h>
#include <libkdcraw/kdcraw.h>

#if KDCRAW_VERSION < 0x000106
#include <libkdcraw/dcrawbinary.h>
#endif

// Local includes.

#include "pluginsversion.h"
#include "utils.h"
#include "utils.moc"

namespace KIPIJPEGLossLessPlugin
{

Utils::Utils(TQObject *parent)
     : TQObject(parent)
{
}

Utils::~Utils()
{
}

bool Utils::updateMetadataImageMagick(const TQString& src, TQString& err)
{
    TQFileInfo finfo(src);
    if (src.isEmpty() || !finfo.isReadable())
    {
        err = i18n("unable to open source file");
        return false;
    }

    TQImage img(src);
    TQImage iptcPreview   = img.scale(1280, 1024, TQ_ScaleMin);
    TQImage exifThumbnail = iptcPreview.scale(160, 120, TQ_ScaleMin);

    KExiv2Iface::KExiv2 meta;
    meta.load(src);
    meta.setImageOrientation(KExiv2Iface::KExiv2::ORIENTATION_NORMAL);
    meta.setImageProgramId(TQString("Kipi-plugins"), TQString(kipiplugins_version));
    meta.setImageDimensions(img.size());
    meta.setExifThumbnail(exifThumbnail);
    meta.setImagePreview(iptcPreview);
    TQByteArray ba = meta.getExif();
    const uchar exifHeader[] = {0x45, 0x78, 0x69, 0x66, 0x00, 0x00};
    TQByteArray exifData = TQByteArray(ba.size() + sizeof(exifHeader));
    memcpy(exifData.data(), exifHeader, sizeof(exifHeader));
    memcpy(exifData.data()+sizeof(exifHeader), ba.data(), ba.size());
    TQByteArray iptcData = meta.getIptc(true);

    KTempFile exifTemp(TQString(), "kipipluginsiptc.app1");
    exifTemp.setAutoDelete(true);
    TQFile *exifFile = exifTemp.file();
    if ( !exifFile )
    {
        err = i18n("unable to open temp file");
        return false;
    }
    TQDataStream streamExif( exifFile );
    streamExif.writeRawBytes(exifData.data(), exifData.size());
    exifFile->close();

    KTempFile iptcTemp(TQString(), "kipipluginsiptc.8bim");
    iptcTemp.setAutoDelete(true);
    TQFile *iptcFile = iptcTemp.file();
    if ( !iptcFile )
    {
        err = i18n("Cannot rotate: unable to open temp file");
        return false;
    }
    TQDataStream streamIptc( iptcFile );
    streamIptc.writeRawBytes(iptcData.data(), iptcData.size());
    iptcFile->close();

    KProcess process;
    process.clearArguments();
    process << "mogrify";
    process << "-verbose";

    process << "-profile";
    process << exifTemp.name();

    process << "-profile";
    process << iptcTemp.name();

    process << src + TQString("[0]");

    qDebug("ImageMagick Command line args:");
    TQValueList<TQCString> args = process.args();
    for (TQValueList<TQCString>::iterator it = args.begin(); it != args.end(); ++it)
        qDebug("%s", (const char*)(*it));

    connect(&process, TQT_SIGNAL(receivedStderr(KProcess *, char*, int)),
            this, TQT_SLOT(slotReadStderr(KProcess*, char*, int)));

    if (!process.start(KProcess::Block, KProcess::Stderr))
        return false;

    if (!process.normalExit())
        return false;

    switch (process.exitStatus())
    {
        case 0:  // Process finished successfully !
        {
            return true;
            break;
        }
        case 15: //  process aborted !
        {
            return false;
            break;
        }
    }

    // Processing error !
    err = i18n("Cannot update metadata: %1").arg(m_stdErr.replace('\n', ' '));
    return false;
}

void Utils::slotReadStderr(KProcess*, char* buffer, int buflen)
{
    m_stdErr.append(TQString::fromLocal8Bit(buffer, buflen));
}

bool Utils::isJPEG(const TQString& file)
{
    TQString format = TQString(TQImageIO::imageFormat(file)).upper();
    return format=="JPEG";
}

bool Utils::isRAW(const TQString& file)
{
#if KDCRAW_VERSION < 0x000106
    TQString rawFilesExt(KDcrawIface::DcrawBinary::instance()->rawFiles());
#else
    TQString rawFilesExt(KDcrawIface::KDcraw::rawFiles());
#endif

    TQFileInfo fileInfo(file);
    if (rawFilesExt.upper().contains( fileInfo.extension(false).upper() ))
        return true;

    return false;
}

bool Utils::CopyFile(const TQString& src, const TQString& dst)
{
    TQFile sFile(src);
    TQFile dFile(dst);

    if ( !sFile.open(IO_ReadOnly) )
        return false;

    if ( !dFile.open(IO_WriteOnly) )
    {
        sFile.close();
        return false;
    }

    const int MAX_IPC_SIZE = (1024*32);
    char buffer[MAX_IPC_SIZE];

    TQ_LONG len;
    while ((len = sFile.readBlock(buffer, MAX_IPC_SIZE)) != 0)
    {
        if (len == -1 || dFile.writeBlock(buffer, (TQ_ULONG)len) == -1)
        {
            sFile.close();
            dFile.close();
            return false;
        }
    }

    sFile.close();
    dFile.close();

    return true;
}

bool Utils::MoveFile(const TQString& src, const TQString& dst)
{
    struct stat stbuf;
    if (::stat(TQFile::encodeName(dst), &stbuf) != 0)
    {
        qDebug("KIPIJPEGLossLessPlugin:MoveFile: failed to stat src");
        return false;
    }
    
    if (!CopyFile(src, dst))
        return false;

    struct utimbuf timbuf;
    timbuf.actime = stbuf.st_atime;
    timbuf.modtime = stbuf.st_mtime;
    if (::utime(TQFile::encodeName(dst), &timbuf) != 0)
    {
        qDebug("KIPIJPEGLossLessPlugin:MoveFile: failed to update dst time");
    }
    
    if (::unlink(TQFile::encodeName(src).data()) != 0)
    {
        qDebug("KIPIJPEGLossLessPlugin:MoveFile: failed to unlink src");
    }
    return true;
}

bool Utils::deleteDir(const TQString& dirPath)
{
    TQDir dir(dirPath);
    if (!dir.exists()) 
        return false;

    dir.setFilter(TQDir::Dirs | TQDir::Files | TQDir::NoSymLinks);

    const TQFileInfoList* infoList = dir.entryInfoList();
    if (!infoList) 
        return false;

    TQFileInfoListIterator it(*infoList);
    TQFileInfo* fi;

    while( (fi = it.current()) ) 
    {
        ++it;
        if(fi->fileName() == "." || fi->fileName() == ".." )
            continue;

        if( fi->isDir() ) 
        {
            deleteDir(fi->absFilePath());
        }
        else if( fi->isFile() )
            dir.remove(fi->absFilePath());
    }

    dir.rmdir(dir.absPath());
    return true;
}

}  // NameSpace KIPIJPEGLossLessPlugin