summaryrefslogtreecommitdiffstats
path: root/digikam/digikam/kipiinterface.cpp
blob: 950b5e3eba65fadb56c51c2d32ed677c11dd099f (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
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
/* ============================================================
 *
 * This file is a part of digiKam project
 * http://www.digikam.org
 *
 * Date        : 2004-08-02
 * Description : digiKam kipi library interface.
 *
 * Copyright (C) 2004-2005 by Renchi Raju <renchi@pooh.tam.uiuc.edu>
 * Copyright (C) 2004-2005 by Ralf Holzer <ralf at well.com>
 * Copyright (C) 2004-2007 by Gilles Caulier <caulier dot gilles at gmail dot com>
 *
 * 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.
 *
 * ============================================================ */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

// C Ansi includes

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

// TQt includes.

#include <tqdir.h>
#include <tqdatetime.h>
#include <tqfileinfo.h>
#include <tqfile.h>
#include <tqregexp.h>

// KDE includes.

#include <klocale.h>
#include <tdeconfig.h>
#include <tdefilemetainfo.h>
#include <tdeio/netaccess.h>

// libKipi includes.

#include <libkipi/version.h>

// Local includes.

#include "constants.h"
#include "ddebug.h"
#include "albummanager.h"
#include "albumitemhandler.h"
#include "album.h"
#include "albumdb.h"
#include "albumsettings.h"
#include "dmetadata.h"
#include "imageattributeswatch.h"
#include "kipiinterface.h"
#include "kipiinterface.moc"

namespace Digikam
{

//-- Image Info ------------------------------------------------------------------

DigikamImageInfo::DigikamImageInfo( KIPI::Interface* interface, const KURL& url )
                : KIPI::ImageInfoShared( interface, url ), palbum_(0)
{
}

DigikamImageInfo::~DigikamImageInfo()
{
}

PAlbum* DigikamImageInfo::parentAlbum()
{
    if (!palbum_)
    {
        KURL u(_url.directory());
        palbum_ = AlbumManager::instance()->findPAlbum(u);
    }
    return palbum_;
}

TQString DigikamImageInfo::title()
{
    return _url.fileName();
}

TQString DigikamImageInfo::description()
{
    PAlbum* p = parentAlbum();

    if (p)
    {
        AlbumDB* db = AlbumManager::instance()->albumDB();
        return db->getItemCaption(p->id(), _url.fileName());
    }

    return TQString();
}

void DigikamImageInfo::setTitle( const TQString& newName )
{
    // Here we get informed that a plugin has renamed the file 
    
    PAlbum* p = parentAlbum();

    if ( p && !newName.isEmpty() )
    {
        AlbumDB* db = AlbumManager::instance()->albumDB();
        db->moveItem(p->id(), _url.fileName(), p->id(), newName);
        _url = _url.upURL();
        _url.addPath(newName);
    }
}

void DigikamImageInfo::setDescription( const TQString& description )
{
    PAlbum* p = parentAlbum();

    if ( p  )
    {
        AlbumDB* db = AlbumManager::instance()->albumDB();
        TQ_LLONG imageId = db->getImageId(p->id(), _url.filename());
        db->setItemCaption(imageId, description);
        ImageAttributesWatch::instance()->imageCaptionChanged(imageId);

        // See B.K.O #140133. Do not set here metadata comments of picture.
        // Only the database comments must be set.
    }
}

TQDateTime DigikamImageInfo::time( KIPI::TimeSpec /*spec*/ )
{
    PAlbum* p = parentAlbum();

    if (p)
    {
        AlbumDB* db = AlbumManager::instance()->albumDB();
        return db->getItemDate(p->id(), _url.fileName());
    }

    return TQDateTime();
}

void DigikamImageInfo::setTime(const TQDateTime& time, KIPI::TimeSpec)
{
    if ( !time.isValid() )
    {
        DWarning() << k_funcinfo << "Invalid datetime specified" << endl;
        return;
    }

    PAlbum* p = parentAlbum();

    if ( p )
    {
        AlbumDB* db = AlbumManager::instance()->albumDB();
        TQ_LLONG imageId = db->getImageId(p->id(), _url.filename());
        db->setItemDate(imageId, time);
        ImageAttributesWatch::instance()->imageDateChanged(imageId);
        AlbumManager::instance()->refreshItemHandler( _url );
    }
}

void DigikamImageInfo::cloneData( ImageInfoShared* other )
{
    setDescription( other->description() );
    setTime( other->time(KIPI::FromInfo), KIPI::FromInfo );
    addAttributes( other->attributes() );
}

TQMap<TQString, TQVariant> DigikamImageInfo::attributes()
{
    TQMap<TQString, TQVariant> res;

    PAlbum* p = parentAlbum();
    if (p)
    {
        AlbumDB* db      = AlbumManager::instance()->albumDB();
        TQ_LLONG imageId  = db->getImageId(p->id(), _url.filename());
        
        // Get digiKam Tags list of picture.
        TQStringList tags         = db->getItemTagNames(imageId); 
        res["tags"]              = tags;

        // Get digiKam Rating of picture.
        int rating               = db->getItemRating(imageId); 
        res["rating"]            = rating;

        // TODO: add here future picture attributes stored by digiKam database
    }
    return res;
}

void DigikamImageInfo::addAttributes(const TQMap<TQString, TQVariant>& res)
{
    PAlbum* p = parentAlbum();
    if (p)
    {
        AlbumDB* db                        = AlbumManager::instance()->albumDB();
        TQ_LLONG imageId                    = db->getImageId(p->id(), _url.filename());
        TQMap<TQString, TQVariant> attributes = res;
        
        // Set digiKam Tags list of picture.
        if (attributes.find("tags") != attributes.end())
        {
            TQStringList tags = attributes["tags"].asStringList();
            //TODO
        }

        // Set digiKam Rating of picture.
        if (attributes.find("rating") != attributes.end())
        {
            int rating = attributes["rating"].asInt();
	    if (rating >= RatingMin && rating <= RatingMax)
                db->setItemRating(imageId, rating); 
        }

        // TODO: add here future picture attributes stored by digiKam database
    }

    // To update sidebar content. Some kipi-plugins use this way to refresh sidebar 
    // using an empty TQMap(). 
    ImageAttributesWatch::instance()->fileMetadataChanged(_url);
}

void DigikamImageInfo::clearAttributes()
{
    // TODO ! This will used for the futures tags digiKam features.
}

int DigikamImageInfo::angle()
{
    AlbumSettings *settings = AlbumSettings::instance();
    if (settings->getExifRotate())
    {
        DMetadata metadata(_url.path());
        DMetadata::ImageOrientation orientation = metadata.getImageOrientation();
        
        switch (orientation) 
        {
            case DMetadata::ORIENTATION_ROT_180:
                return 180;
            case DMetadata::ORIENTATION_ROT_90:
            case DMetadata::ORIENTATION_ROT_90_HFLIP:
            case DMetadata::ORIENTATION_ROT_90_VFLIP:
                return 90;
            case DMetadata::ORIENTATION_ROT_270:
                return 270;
            default:
                return 0;
        }
    }
    
    return 0;
}

void DigikamImageInfo::setAngle( int )
{
    // TODO : add here a DMetadata call (thru Exiv2) to set Exif orientation tag.
}

//-- Image Collection ------------------------------------------------------------

DigikamImageCollection::DigikamImageCollection( Type tp, Album* album, const TQString& filter )
                      : tp_( tp ), album_(album), imgFilter_(filter)
{
    if (!album)
    {
        DWarning() << k_funcinfo << "This should not happen. No album specified" << endl;
    }
}

DigikamImageCollection::~DigikamImageCollection()
{
}

TQString DigikamImageCollection::name()
{
    if ( album_->type() == Album::TAG )
    {
        return i18n("Tag: %1").arg(album_->title());
    }
    else
        return album_->title();
}

TQString DigikamImageCollection::category()
{
    if ( album_->type() == Album::PHYSICAL )
    {
        PAlbum *p = dynamic_cast<PAlbum*>(album_);
        return p->collection();
    }
    else if ( album_->type() == Album::TAG )
    {
        TAlbum *p = dynamic_cast<TAlbum*>(album_);
        return i18n("Tag: %1").arg(p->tagPath());
    }
    else
        return TQString();
}

TQDate DigikamImageCollection::date()
{
    if ( album_->type() == Album::PHYSICAL )
    {
        PAlbum *p = dynamic_cast<PAlbum*>(album_);
        return p->date();
    }
    else
        return TQDate();
}

TQString DigikamImageCollection::comment()
{
    if ( album_->type() == Album::PHYSICAL )
    {
        PAlbum *p = dynamic_cast<PAlbum*>(album_);
        return p->caption();
    }
    else
        return TQString();
}

static TQValueList<TQRegExp> makeFilterList( const TQString &filter )
{
    TQValueList<TQRegExp> regExps;
    if ( filter.isEmpty() )
        return regExps;

    TQChar sep( ';' );
    int i = filter.find( sep, 0 );

    if ( i == -1 && filter.find( ' ', 0 ) != -1 )
        sep = TQChar( ' ' );

    TQStringList list = TQStringList::split( sep, filter );
    TQStringList::Iterator it = list.begin();
    
    while ( it != list.end() ) 
    {
        regExps << TQRegExp( (*it).stripWhiteSpace(), false, true );
        ++it;
    }
    
    return regExps;
}

static bool matchFilterList( const TQValueList<TQRegExp>& filters, const TQString &fileName )
{
    TQValueList<TQRegExp>::ConstIterator rit = filters.begin();
    
    while ( rit != filters.end() ) 
    {
        if ( (*rit).exactMatch(fileName) )
            return true;
        ++rit;
    }

    return false;
}

KURL::List DigikamImageCollection::images()
{
    switch ( tp_ )
    {
        case AllItems:
        {
            if (album_->type() == Album::PHYSICAL)
            {
                return imagesFromPAlbum(dynamic_cast<PAlbum*>(album_));
            }
            else if (album_->type() == Album::TAG)
            {
                return imagesFromTAlbum(dynamic_cast<TAlbum*>(album_));
            }
            else if (album_->type() == Album::DATE || 
                    album_->type() == Album::SEARCH)
            {
                AlbumItemHandler* handler = AlbumManager::instance()->getItemHandler();
    
                if (handler)
                {
                    return handler->allItems();
                }
    
                return KURL::List();
        }
            else
            {
                DWarning() << k_funcinfo << "Unknown album type" << endl;
                return KURL::List();
            }
    
            break;
        }
        case SelectedItems:
        {
            AlbumItemHandler* handler = AlbumManager::instance()->getItemHandler();
    
            if (handler)
            {
                return handler->selectedItems();
            }
    
            return KURL::List();
    
            break;
        }
        default:
            break;
    }

    // We should never reach here
    return KURL::List();
}

/** get the images from the Physical album in database and return the items found */

KURL::List DigikamImageCollection::imagesFromPAlbum(PAlbum* album) const
{
    // get the images from the database and return the items found

    AlbumDB* db = AlbumManager::instance()->albumDB();

    db->beginTransaction();

    TQStringList urls = db->getItemURLsInAlbum(album->id());

    db->commitTransaction();

    KURL::List urlList;

    TQValueList<TQRegExp> regex = makeFilterList(imgFilter_);
    
    for (TQStringList::iterator it = urls.begin(); it != urls.end(); ++it)
    {
        if (matchFilterList(regex, *it))
            urlList.append(*it);
    }

    return urlList;
}

/** get the images from the Tags album in database and return the items found */

KURL::List DigikamImageCollection::imagesFromTAlbum(TAlbum* album) const
{
    AlbumDB* db = AlbumManager::instance()->albumDB();

    db->beginTransaction();

    TQStringList urls = db->getItemURLsInTag(album->id());

    db->commitTransaction();

    KURL::List urlList;

    TQValueList<TQRegExp> regex = makeFilterList(imgFilter_);
    
    for (TQStringList::iterator it = urls.begin(); it != urls.end(); ++it)
    {
        if (matchFilterList(regex, *it))
            urlList.append(*it);
    }

    return urlList;
}

KURL DigikamImageCollection::path()
{
    if (album_->type() == Album::PHYSICAL)
    {
        PAlbum *p = dynamic_cast<PAlbum*>(album_);
        KURL url;
        url.setPath(p->folderPath());
        return url;
    }
    else
    {
        DWarning() << k_funcinfo << "Requesting kurl from a virtual album" << endl;
        return TQString();
    }
}

KURL DigikamImageCollection::uploadPath()
{
    if (album_->type() == Album::PHYSICAL)
    {
        PAlbum *p = dynamic_cast<PAlbum*>(album_);
        KURL url;
        url.setPath(p->folderPath());
        return url;
    }
    else
    {
        DWarning() << k_funcinfo << "Requesting kurl from a virtual album" << endl;
        return KURL();
    }
}

KURL DigikamImageCollection::uploadRoot()
{
    return KURL(AlbumManager::instance()->getLibraryPath() + '/');
}

TQString DigikamImageCollection::uploadRootName()
{
    return i18n("My Albums");
}

bool DigikamImageCollection::isDirectory()
{
    if (album_->type() == Album::PHYSICAL)
        return true;
    else
        return false;
}

bool DigikamImageCollection::operator==(ImageCollectionShared& imgCollection)
{
    DigikamImageCollection* thatCollection = static_cast<DigikamImageCollection*>(&imgCollection);
    return (album_ == thatCollection->album_);
}

//-- LibKipi interface -----------------------------------------------------------

DigikamKipiInterface::DigikamKipiInterface( TQObject *parent, const char *name)
                    : KIPI::Interface( parent, name )
{
    albumManager_ = AlbumManager::instance();
    albumDB_      = albumManager_->albumDB();

    connect( albumManager_, TQT_SIGNAL( signalAlbumItemsSelected( bool ) ),
             this, TQT_SLOT( slotSelectionChanged( bool ) ) );

    connect( albumManager_, TQT_SIGNAL( signalAlbumCurrentChanged(Album*) ),
             this, TQT_SLOT( slotCurrentAlbumChanged(Album*) ) );
}

DigikamKipiInterface::~DigikamKipiInterface()
{
}

KIPI::ImageCollection DigikamKipiInterface::currentAlbum()
{
    Album* currAlbum = albumManager_->currentAlbum();
    if ( currAlbum )
    {
        return KIPI::ImageCollection(
            new DigikamImageCollection( DigikamImageCollection::AllItems,
                                        currAlbum, fileExtensions() ) );
    }
    else
    {
        return KIPI::ImageCollection(0);
    }
}

KIPI::ImageCollection DigikamKipiInterface::currentSelection()
{
    Album* currAlbum = albumManager_->currentAlbum();
    if ( currAlbum )
    {
        return KIPI::ImageCollection(
            new DigikamImageCollection( DigikamImageCollection::SelectedItems,
                                        currAlbum, fileExtensions() ) );
    }
    else
    {
        return KIPI::ImageCollection(0);
    }
}

TQValueList<KIPI::ImageCollection> DigikamKipiInterface::allAlbums()
{
    TQValueList<KIPI::ImageCollection> result;

    TQString fileFilter(fileExtensions());

    AlbumList palbumList = albumManager_->allPAlbums();
    for ( AlbumList::Iterator it = palbumList.begin();
          it != palbumList.end(); ++it )
    {
        // don't add the root album
        if ((*it)->isRoot())
            continue;

        DigikamImageCollection* col = new DigikamImageCollection( DigikamImageCollection::AllItems,
                                                                  *it, fileFilter );
        result.append( KIPI::ImageCollection( col ) );
    }

    AlbumList talbumList = albumManager_->allTAlbums();
    for ( AlbumList::Iterator it = talbumList.begin();
          it != talbumList.end(); ++it )
    {
        // don't add the root album
        if ((*it)->isRoot())
            continue;

        DigikamImageCollection* col = new DigikamImageCollection( DigikamImageCollection::AllItems,
                                                                  *it, fileFilter );   
        result.append( KIPI::ImageCollection( col ) );
    }

    return result;
}

KIPI::ImageInfo DigikamKipiInterface::info( const KURL& url )
{
    return KIPI::ImageInfo( new DigikamImageInfo( this, url ) );
}

void DigikamKipiInterface::refreshImages( const KURL::List& urls )
{
    KURL::List ulist = urls;

    // Re-scan metadata from pictures. This way will update Metadata sidebar and database.
    for ( KURL::List::Iterator it = ulist.begin() ; it != ulist.end() ; ++it )
        ImageAttributesWatch::instance()->fileMetadataChanged(*it);
    
    // Refresh preview.
    albumManager_->refreshItemHandler(urls);
}

int DigikamKipiInterface::features() const
{
    return (

// HostSupportsTags feature require libkipi version > 1.4.0
#if KIPI_VERSION>0x000104
           KIPI::HostSupportsTags |
#endif
           KIPI::ImagesHasComments          | KIPI::AcceptNewImages            |
           KIPI::AlbumsHaveComments         | KIPI::ImageTitlesWritable        |
           KIPI::ImagesHasTime              | KIPI::AlbumsHaveCategory         |
           KIPI::AlbumsHaveCreationDate     | KIPI::AlbumsUseFirstImagePreview 
           );
}

bool DigikamKipiInterface::addImage( const KURL& url, TQString& errmsg )
{
    // Nota : All copy/move operations are processed by the plugins.

    if ( url.isValid() == false )
    {
        errmsg = i18n("Target URL %1 is not valid.").arg(url.path());
        return false;
    }

    PAlbum *targetAlbum = albumManager_->findPAlbum(url.directory());

    if ( !targetAlbum )
    {
        errmsg = i18n("Target album is not in the album library.");
        return false;
    }

    albumManager_->refreshItemHandler( url );

    return true;
}

void DigikamKipiInterface::delImage( const KURL& url )
{
    KURL rootURL(albumManager_->getLibraryPath());
    if ( !rootURL.isParentOf(url) )
    {
        DWarning() << k_funcinfo << "URL not in the album library" << endl;
    }

    // Is there a PAlbum for this url

    PAlbum *palbum = albumManager_->findPAlbum( KURL(url.directory()) );

    if ( palbum )
    {
        // delete the item from the database
        albumDB_->deleteItem( palbum->id(), url.fileName() );
    }
    else
    {
        DWarning() << k_funcinfo << "Cannot find Parent album in album library" << endl;
    }
}

void DigikamKipiInterface::slotSelectionChanged( bool b )
{
    emit selectionChanged( b );
}

void DigikamKipiInterface::slotCurrentAlbumChanged( Album *album )
{
    emit currentAlbumChanged( album != 0 );
}

TQString DigikamKipiInterface::fileExtensions()
{
    // do not save this into a local variable, as this
    // might change in the main app

    AlbumSettings* s = AlbumSettings::instance();
    return (s->getImageFileFilter() + ' ' +
            s->getMovieFileFilter() + ' ' +
            s->getAudioFileFilter() + ' ' +
            s->getRawFileFilter());
}

}  // namespace Digikam