add more spacing
[personal-kdebase.git] / runtime / kioslave / thumbnail / thumbnail.cpp
blob7e722044bfe7a8833d149bebb7442990d9fb85e9
1 /* This file is part of the KDE libraries
2 Copyright (C) 2000 Malte Starostik <malte@kde.org>
3 2000 Carsten Pfeiffer <pfeiffer@kde.org>
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
15 You should have received a copy of the GNU Library General Public License
16 along with this library; see the file COPYING.LIB. If not, write to
17 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
21 #include "thumbnail.h"
23 #include <stdlib.h>
24 #include <unistd.h>
25 #ifdef __FreeBSD__
26 #include <machine/param.h>
27 #endif
28 #include <sys/types.h>
29 #ifndef Q_WS_WIN
30 #include <sys/ipc.h>
31 #include <sys/shm.h>
32 #endif
34 #include <QtCore/QBuffer>
35 #include <QtCore/QFile>
36 #include <QtGui/QBitmap>
37 #include <QtGui/QImage>
38 #include <QtGui/QPainter>
39 #include <QtGui/QPixmap>
41 #include <kurl.h>
42 #include <kapplication.h>
43 #include <kcmdlineargs.h>
44 #include <kaboutdata.h>
45 #include <kglobal.h>
46 #include <kiconloader.h>
47 #include <kmimetype.h>
48 #include <klibloader.h>
49 #include <kdebug.h>
50 #include <kservice.h>
51 #include <kservicetype.h>
52 #include <kservicetypetrader.h>
53 #include <kmimetypetrader.h>
54 #include <kfilemetainfo.h>
55 #include <klocale.h>
57 #include <config-runtime.h> // For HAVE_NICE
58 #include <kio/thumbcreator.h>
59 #include <kconfiggroup.h>
61 // Fix thumbnail: protocol
62 #define THUMBNAIL_HACK (1)
64 #ifdef THUMBNAIL_HACK
65 # include <QFileInfo>
66 #endif
68 // Recognized metadata entries:
69 // mimeType - the mime type of the file, used for the overlay icon if any
70 // width - maximum width for the thumbnail
71 // height - maximum height for the thumbnail
72 // iconSize - the size of the overlay icon to use if any
73 // iconAlpha - the transparency value used for icon overlays
74 // plugin - the name of the plugin library to be used for thumbnail creation.
75 // Provided by the application to save an addition KTrader
76 // query here.
77 // shmid - the shared memory segment id to write the image's data to.
78 // The segment is assumed to provide enough space for a 32-bit
79 // image sized width x height pixels.
80 // If this is given, the data returned by the slave will be:
81 // int width
82 // int height
83 // int depth
84 // Otherwise, the data returned is the image in PNG format.
86 using namespace KIO;
88 extern "C"
90 KDE_EXPORT int kdemain(int argc, char **argv);
94 int kdemain(int argc, char **argv)
96 #ifdef HAVE_NICE
97 nice( 5 );
98 #endif
100 // creating KApplication in a slave in not a very good idea,
101 // as dispatchLoop() doesn't allow it to process its messages,
102 // so it for example wouldn't reply to ksmserver - on the other
103 // hand, this slave uses QPixmaps for some reason, and they
104 // need QApplication
105 // and HTML previews need even KApplication :(
106 putenv(strdup("SESSION_MANAGER="));
107 //KApplication::disableAutoDcopRegistration();
108 KAboutData about("kio_thumbnail", 0, ki18n("kio_thumbmail"), "KDE 4.x.x");
109 KCmdLineArgs::init(&about);
111 KApplication app( true);
113 if (argc != 4)
115 kError(7115) << "Usage: kio_thumbnail protocol domain-socket1 domain-socket2" << endl;
116 exit(-1);
119 ThumbnailProtocol slave(argv[2], argv[3]);
120 slave.dispatchLoop();
122 return 0;
125 ThumbnailProtocol::ThumbnailProtocol(const QByteArray &pool, const QByteArray &app)
126 : SlaveBase("thumbnail", pool, app)
128 m_iconSize = 0;
131 ThumbnailProtocol::~ThumbnailProtocol()
133 qDeleteAll( m_creators );
134 m_creators.clear();
137 void ThumbnailProtocol::get(const KUrl &url)
139 m_mimeType = metaData("mimeType");
140 kDebug(7115) << "Wanting MIME Type:" << m_mimeType;
141 #ifdef THUMBNAIL_HACK
142 // ### HACK
143 bool direct=false;
144 if (m_mimeType.isEmpty())
146 kDebug(7115) << "PATH: " << url.path();
147 QFileInfo info(url.path());
148 if (info.isDir())
150 // We cannot process a directory
151 error(KIO::ERR_IS_DIRECTORY,url.path());
152 return;
154 else if (!info.exists())
156 // The file does not exist
157 error(KIO::ERR_DOES_NOT_EXIST,url.path());
158 return;
160 else if (!info.isReadable())
162 // The file is not readable!
163 error(KIO::ERR_COULD_NOT_READ,url.path());
164 return;
166 m_mimeType = KMimeType::findByUrl(url)->name();
167 kDebug(7115) << "Guessing MIME Type:" << m_mimeType;
168 direct=true; // thumbnail: was probably called from Konqueror
170 #endif
172 if (m_mimeType.isEmpty())
174 error(KIO::ERR_INTERNAL, i18n("No MIME Type specified."));
175 return;
178 m_width = metaData("width").toInt();
179 m_height = metaData("height").toInt();
180 int iconSize = metaData("iconSize").toInt();
182 if (m_width < 0 || m_height < 0)
184 error(KIO::ERR_INTERNAL, i18n("No or invalid size specified."));
185 return;
187 #ifdef THUMBNAIL_HACK
188 else if (!m_width || !m_height)
190 kDebug(7115) << "Guessing height, width, icon size!";
191 m_width=128;
192 m_height=128;
193 iconSize=128;
195 #endif
197 if (!iconSize)
198 iconSize = KIconLoader::global()->currentSize(KIconLoader::Desktop);
199 if (iconSize != m_iconSize) {
200 m_iconDict.clear();
202 m_iconSize = iconSize;
204 m_iconAlpha = metaData("iconAlpha").toInt();
206 QImage img;
208 KConfigGroup group( KGlobal::config(), "PreviewSettings" );
211 // ### KFMI
212 bool kfmiThumb = false;
213 if (group.readEntry( "UseFileThumbnails", true)) {
214 KService::Ptr service =
215 KMimeTypeTrader::self()->preferredService( m_mimeType, "KFilePlugin");
217 if (service && service->isValid() &&
218 service->property("SupportsThumbnail").toBool())
220 // was: KFileMetaInfo info(url.path(), m_mimeType, KFileMetaInfo::Thumbnail);
221 // but m_mimeType and WhatFlags are now unused in KFileMetaInfo, and not present in the
222 // call that takes a KUrl
223 KFileMetaInfo info(url);
224 if (info.isValid())
226 KFileMetaInfoItem item = info.item("thumbnail");
227 if (item.isValid() && item.value().type() == QVariant::Image)
229 img = item.value().value<QImage>();
230 kDebug(7115) << "using KFMI for the thumbnail\n";
231 kfmiThumb = true;
236 ThumbCreator::Flags flags = ThumbCreator::None;
238 if (!kfmiThumb)
240 kDebug(7115) << "using thumb creator for the thumbnail\n";
241 QString plugin = metaData("plugin");
242 #ifdef THUMBNAIL_HACK
243 if (plugin.isEmpty())
245 KService::List offers = KMimeTypeTrader::self()->query( m_mimeType, QLatin1String( "ThumbCreator" ) );
247 if(!offers.isEmpty())
249 KService::Ptr serv;
250 serv = offers.first();
251 plugin = serv->library();
254 kDebug(7115) << "Guess plugin: " << plugin;
255 #endif
256 if (plugin.isEmpty())
258 error(KIO::ERR_INTERNAL, i18n("No plugin specified."));
259 return;
262 ThumbCreator *creator = m_creators[plugin];
263 if (!creator)
265 // Don't use KLibFactory here, this is not a QObject and
266 // neither is ThumbCreator
267 KLibrary *library = KLibLoader::self()->library(plugin);
268 if (library)
270 newCreator create = (newCreator)library->resolveFunction("new_creator");
271 if (create)
272 creator = create();
274 if (!creator)
276 error(KIO::ERR_INTERNAL, i18n("Cannot load ThumbCreator %1", plugin));
277 return;
279 m_creators.insert(plugin, creator);
282 if (!creator->create(url.path(), m_width, m_height, img))
284 error(KIO::ERR_INTERNAL, i18n("Cannot create thumbnail for %1", url.path()));
285 return;
287 flags = creator->flags();
290 if (img.width() > m_width || img.height() > m_height)
292 double imgRatio = (double)img.height() / (double)img.width();
293 if (imgRatio > (double)m_height / (double)m_width)
294 img = img.scaled( int(qMax((double)m_height / imgRatio, 1.0)), m_height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
295 else
296 img = img.scaled(m_width, int(qMax((double)m_width * imgRatio, 1.0)), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
299 if ((flags & ThumbCreator::BlendIcon) && KIconLoader::global()->alphaBlending(KIconLoader::Desktop))
301 // blending the mimetype icon in
302 QImage icon = getIcon();
304 int x = img.width() - icon.width() - 4;
305 x = qMax( x, 0 );
306 int y = img.height() - icon.height() - 6;
307 y = qMax( y, 0 );
308 QPainter p(&img);
309 p.setOpacity(m_iconAlpha/255.0);
310 p.drawImage(x, y, icon);
313 if (img.isNull())
315 error(KIO::ERR_INTERNAL, i18n("Failed to create a thumbnail."));
316 return;
319 const QString shmid = metaData("shmid");
320 if (shmid.isEmpty())
322 #ifdef THUMBNAIL_HACK
323 if (direct)
325 // If thumbnail was called directly from Konqueror, then the image needs to be raw
326 //kDebug(7115) << "RAW IMAGE TO STREAM";
327 QBuffer buf;
328 if (!buf.open(QIODevice::WriteOnly))
330 error(KIO::ERR_INTERNAL, i18n("Could not write image."));
331 return;
333 img.save(&buf,"PNG");
334 buf.close();
335 data(buf.buffer());
337 else
338 #endif
340 QByteArray imgData;
341 QDataStream stream( &imgData, QIODevice::WriteOnly );
342 //kDebug(7115) << "IMAGE TO STREAM";
343 stream << img;
344 data(imgData);
347 else
349 #ifndef Q_WS_WIN
350 QByteArray imgData;
351 QDataStream stream( &imgData, QIODevice::WriteOnly );
352 //kDebug(7115) << "IMAGE TO SHMID";
353 void *shmaddr = shmat(shmid.toInt(), 0, 0);
354 if (shmaddr == (void *)-1)
356 error(KIO::ERR_INTERNAL, i18n("Failed to attach to shared memory segment %1", shmid));
357 return;
359 if (img.width() * img.height() > m_width * m_height)
361 error(KIO::ERR_INTERNAL, i18n("Image is too big for the shared memory segment"));
362 shmdt((char*)shmaddr);
363 return;
365 if( img.depth() != 32 ) // KIO::PreviewJob and this code below completely ignores colortable :-/,
366 img = img.convertToFormat(QImage::Format_ARGB32); // so make sure there is none
367 // Keep in sync with kdelibs/kio/kio/previewjob.cpp
368 stream << img.width() << img.height() << quint8(img.format());
369 memcpy(shmaddr, img.bits(), img.numBytes());
370 shmdt((char*)shmaddr);
371 data(imgData);
372 #endif
374 finished();
377 const QImage ThumbnailProtocol::getIcon()
379 if ( !m_iconDict.contains(m_mimeType) ) { // generate it
380 QImage icon( KIconLoader::global()->loadMimeTypeIcon( KMimeType::mimeType(m_mimeType)->iconName(), KIconLoader::Desktop, m_iconSize ).toImage() );
381 icon = icon.convertToFormat( QImage::Format_ARGB32 );
382 m_iconDict.insert( m_mimeType, icon );
384 return icon;
387 return m_iconDict.value( m_mimeType );