summaryrefslogtreecommitdiffstats
path: root/kmrml/kmrml/mrml_view.cpp
blob: 5874c996c0d0b55aa7b5566ecb47c2588618d472 (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
/* This file is part of the KDE project
   Copyright (C) 2001,2002 Carsten Pfeiffer <pfeiffer@kde.org>

   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 of the License, 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.

   You should have received a copy of the GNU General Public License
   along with this program; see the file COPYING.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include <tqdom.h>
#include <tqlabel.h>
#include <tqpainter.h>
#include <tqtimer.h>
#include <tqtooltip.h>

#include <kcursor.h>
#include <kdatastream.h>
#include <klocale.h>
#include <kcombobox.h>
#include <kmimetype.h>
#include <kurl.h>
#include <kurldrag.h>

#include "loader.h"
#include "mrml_creator.h"
#include "mrml_view.h"

using namespace KMrml;

MrmlView::MrmlView( TQWidget *tqparent, const char *name )
    : TQScrollView( tqparent, name )
{
    setStaticBackground( true );
    setResizePolicy( Manual );
    setHScrollBarMode( AlwaysOff );
    enableClipper( true ); // ### test this

    m_items.setAutoDelete( true );

    connect( Loader::self(), TQT_SIGNAL( finished(const KURL&, const TQByteArray&)),
             TQT_SLOT( slotDownloadFinished( const KURL&, const TQByteArray& )));

    m_timer = new TQTimer( this );
    connect( m_timer, TQT_SIGNAL( timeout() ), TQT_SLOT( slotLayout() ));

    // we need a pixmap to be shown when no thumbnail is available for a
    // query result image
    TQLabel l( i18n( "No thumbnail available" ), 0L );
    l.setFixedSize( 80, 80 );
    l.tqsetAlignment( WordBreak | AlignCenter );
//     l.setFrameStyle( TQLabel::Box | TQLabel::Plain );
//     l.setLineWidth( 1 );
    l.setPaletteBackgroundColor( TQt::white );
    l.setPaletteForegroundColor( TQt::black );
    m_unavailablePixmap = TQPixmap::grabWidget( &l );
}

MrmlView::~MrmlView()
{
}

MrmlViewItem * MrmlView::addItem( const KURL& url, const KURL& thumbURL,
                                  const TQString& similarity )
{
    bool ok;
    double value = similarity.toDouble( &ok );
    if ( !ok || value < 0.05 )
        return 0L;

    return addItem( url, thumbURL, value );
}

MrmlViewItem * MrmlView::addItem( const KURL& url, const KURL& thumbURL,
                                  double similarity )
{
    if ( !url.isValid() ) {
        qWarning( "MrmlPart: received malformed URL from query: %s",
                  url.prettyURL().isNull() ? "(null)" : url.prettyURL().latin1() );
        return 0L;
    }

//     qDebug("** url: %s", thumbURL.url().latin1());

    MrmlViewItem *item = new MrmlViewItem( url, thumbURL, similarity, this );
    TQPixmap *pixmap = getPixmap( thumbURL );
    if ( pixmap )
        item->setPixmap( *pixmap );

    m_items.append( item );

    m_timer->start( 0, true );
    return item;
}

void MrmlView::addRelevanceToQuery( TQDomDocument& document,
                                    TQDomElement& tqparent )
{
    TQPtrListIterator<MrmlViewItem> it( m_items );
    for( ; it.current(); ++it ) {
        it.current()->createRelevanceElement( document, tqparent );
    }
}

void MrmlView::clear()
{
    m_items.clear(); // items are deleted and removed from scrollview
    setContentsPos( 0, 0 );
}

TQPixmap * MrmlView::getPixmap( const KURL& url )
{
    TQString u = url.url();
    TQPixmap *pix = m_pixmapCache.find( u );
    if ( pix )
        return pix;

    if ( url.isLocalFile() ) {
        TQPixmap p;
        if ( !p.load( url.path() ) )
             p = m_unavailablePixmap;

        m_pixmapCache.insert( u, p );
        return m_pixmapCache.find( u );
    }
    else { // remote url, download with KIO
        Loader::self()->requestDownload( url );
    }

    return 0L;
}

void MrmlView::slotDownloadFinished( const KURL& url, const TQByteArray& data )
{
    TQPtrListIterator<MrmlViewItem> it( m_items );
    for( ; it.current(); ++it ) {
        MrmlViewItem *item = it.current();
        if ( item->thumbURL() == url )
        {
            TQPixmap p;
            if ( data.isEmpty() || !p.loadFromData( data ) )
                p = m_unavailablePixmap;

            m_pixmapCache.insert( url.url(), p );
            item->setPixmap( p );

            slotLayout();
            return;
        }
    }
}

void MrmlView::stopDownloads()
{
    Loader *loader = Loader::self();
    TQPtrListIterator<MrmlViewItem> it( m_items );
    for( ; it.current(); ++it ) {
        MrmlViewItem *item = it.current();
        if ( !item->hasRemotePixmap() )
            loader->removeDownload( item->url() );
    }
}

void MrmlView::slotLayout()
{
    int itemWidth = 0;
    TQPtrListIterator<MrmlViewItem> it( m_items );

    for ( ; it.current(); ++it ) {
        itemWidth = TQMAX( itemWidth, it.current()->tqsizeHint().width() );
    }

    if ( itemWidth == 0 )
        return;


    uint itemsPerRow = visibleWidth() / itemWidth;
    int margin = (visibleWidth() - (itemsPerRow * itemWidth)) / 2;
    int rowHeight = 0;
    uint item = 0;
    uint y = 5;

    // pointing to the first item of a row
    TQPtrListIterator<MrmlViewItem> rowIt( m_items );

    for ( it.toFirst(); it.current(); ++it ) {
        if ( item >= itemsPerRow ) {
            item = 0;
            y += rowHeight;
            rowHeight = 0;
        }

        if ( item == 0 )
            rowIt = it;

        rowHeight = TQMAX( rowHeight, it.current()->tqsizeHint().height() );
        addChild( it.current(), margin + item * itemWidth, y );
        it.current()->show();

        item++;

        // resize all items of the current row so they all have the same size
        if ( item >= itemsPerRow || it.atLast() )
        {
            for ( uint i = 0; (i < itemsPerRow && rowIt.current()); i++ )
            {
                rowIt.current()->resize( itemWidth, rowHeight );
                ++rowIt;
            }
        }
    }

    resizeContents( visibleWidth(), y + rowHeight );
}

void MrmlView::resizeEvent( TQResizeEvent *e )
{
    int oldW = visibleWidth();
    TQScrollView::resizeEvent( e );

    if ( visibleWidth() != oldW )
        slotLayout();
}

void MrmlView::saveState( TQDataStream& stream )
{
    stream << m_items.count();
    TQPtrListIterator<MrmlViewItem> it( m_items );
    for( ; it.current(); ++it ) {
        stream << *it.current();
    }

}

void MrmlView::restoreState( TQDataStream& stream )
{
    stopDownloads();
    clear();

    int count;
    stream >> count;

    KURL url, thumbURL;
    double similarity;
    TQ_UINT32 relevance;
    MrmlViewItem *item;


    for ( int i = 0; i < count; i++ )
    {
        stream >> url;
        stream >> thumbURL;
        stream >> similarity;
        stream >> relevance;

        item = addItem( url, thumbURL, similarity );
        if ( item )
            item->setRelevance( (MrmlViewItem::Relevance) relevance );
    }
}

TQDataStream& KMrml::operator<<( TQDataStream& stream,
                                const KMrml::MrmlViewItem& item )
{
    return stream << item.url()
                  << item.thumbURL()
                  << item.similarity()
                  << static_cast<TQ_UINT32>( item.relevance() );
}

///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////


MrmlViewItem::MrmlViewItem( const KURL& url, const KURL& thumbURL,
                            double similarity, MrmlView *view,
                            const char *name )
    : TQFrame( view->viewport() , name ),
      m_view( view ),
      m_url( url ),
      m_thumbURL( thumbURL ),
      similarityFullWidth( 120 ), // ###
      m_hasRemotePixmap( false )
{
    if ( m_similarity != -1 )
        m_similarity = TQMAX( 0.0, TQMIN( 1.0, similarity ));
    setFrameStyle( Panel | Sunken );
    setMouseTracking( true );

    m_combo = new KComboBox( this );
    TQToolTip::add( m_combo, i18n("You can refine queries by giving feedback about the current result and pressing the Search button again.") );
    m_combo->insertItem( i18n("Relevant"),   Relevant );
    m_combo->insertItem( i18n("Neutral"),    Neutral );
    m_combo->insertItem( i18n("Irrelevant"), Irrelevant );
    m_combo->adjustSize();
    m_combo->setCurrentItem( Neutral );

    /*
    if ( similarity > -1 )
        TQToolTip::add( this, TQString::tqfromLatin1("<qt>%1<br>%1</qt>")
                       .tqarg( url )
                       .tqarg(i18n("Similarity: %1").tqarg( TQString::number(similarity))));
    else
        TQToolTip::add( this, TQString::tqfromLatin1("<qt>%1</qt>").tqarg( url ) );
    */

    setMinimumSize( 130, 130 ); // ###
}

MrmlViewItem::~MrmlViewItem()
{
}

void MrmlViewItem::setPixmap( const TQPixmap& pix )
{
    if ( !m_url.isLocalFile() )
        m_hasRemotePixmap = true;

    m_pixmap = pix;
    adjustSize();
    update();
}

void MrmlViewItem::paintEvent( TQPaintEvent *e )
{
    TQFrame::paintEvent( e );

    if ( !m_pixmap.isNull() ) {
        bitBlt( this, pixmapX(), pixmapY(),
                &m_pixmap, 0, 0, m_pixmap.width(), m_pixmap.height(),
                CopyROP );
    }

    if ( m_similarity >= 0 ) {
        TQPainter p( this );
        TQPen pen( tqcolorGroup().highlight(), 1, TQPen::SolidLine );
        p.setPen( pen );
        int x = margin;
        int y = m_combo->y() - similarityHeight - 2;
        int w = (int) (similarityFullWidth * m_similarity);
        int h = similarityHeight;
        p.drawRect( x, y, similarityFullWidth, h );
        p.fillRect( x, y, w, h, tqcolorGroup().highlight() );
    }
}

void MrmlViewItem::resizeEvent( TQResizeEvent *e )
{
    TQFrame::resizeEvent( e );

    int y = height() - m_combo->height() - margin;
    m_combo->move( width()/2 - m_combo->width()/2, y );
}

TQSize MrmlViewItem::tqsizeHint() const
{
    int w = TQMAX( TQMAX(minimumHeight(), m_combo->width()), m_pixmap.width() );
    w += 2 * margin;

    int h = m_pixmap.isNull() ? margin : margin + spacing + m_pixmap.height();
    h += (m_similarity > -1) ? similarityHeight + spacing : 0;
    h += m_combo->height() + margin;

    return TQSize( w, h );
}

void MrmlViewItem::mousePressEvent( TQMouseEvent *e )
{
    TQFrame::mousePressEvent( e );
    pressedPos.setX( 0 );
    pressedPos.setY( 0 );


    if ( e->button() == Qt::LeftButton || e->button() == Qt::MidButton ) {
        if ( hitsPixmap( e->pos() ) )
            pressedPos = e->pos();
    }
    else if ( e->button() == Qt::RightButton && hitsPixmap( e->pos() ) )
        emit view()->activated( m_url, e->button() );
}

void MrmlViewItem::mouseMoveEvent( TQMouseEvent *e )
{
    if ( hitsPixmap( e->pos() ) ) {
        if ( !ownCursor() ) { // nice hacklet :)
            setCursor( KCursor::handCursor() );
            emit view()->onItem( m_url );
        }
    }
    else {
        if ( ownCursor() ) {
            unsetCursor();
            emit view()->onItem( KURL() );
        }
    }

    if ( (e->state() & Qt::LeftButton) && !pressedPos.isNull() ) {
        TQPoint dist = e->pos() - pressedPos;
        if ( dist.manhattanLength() > KGlobalSettings::dndEventDelay() ) {
            // start drag here
            KURL::List urls;
            // ### support multiple files?
            urls.append( m_url );
            KURLDrag *drag = new KURLDrag( urls, this );
            drag->setPixmap( KMimeType::pixmapForURL( m_url ) );
            drag->drag();
        }
    }
}

void MrmlViewItem::mouseReleaseEvent( TQMouseEvent *e )
{
    if ( hitsPixmap( e->pos() )) {
        TQPoint dist = e->pos() - pressedPos;
        if ( dist.manhattanLength() < KGlobalSettings::dndEventDelay() ) {
            emit view()->activated( m_url, e->button() );
        }
    }
}

bool MrmlViewItem::hitsPixmap( const TQPoint& pos ) const
{
    if ( m_pixmap.isNull() )
        return false;

    if ( pos.x() > pixmapX() && pos.x() < pixmapX() + m_pixmap.width() &&
         pos.y() > pixmapY() && pos.y() < pixmapY() + m_pixmap.height() )
        return true;
    return false;
}

void MrmlViewItem::createRelevanceElement( TQDomDocument& document,
                                           TQDomElement& tqparent )
{
    int rel = m_combo->currentItem();
    if ( rel == Neutral )
        return;

    MrmlCreator::createRelevanceElement( document, tqparent, m_url.url(),
        (rel == Relevant) ? MrmlCreator::Relevant : MrmlCreator::Irrelevant );
}

MrmlViewItem::Relevance MrmlViewItem::relevance() const
{
    return (Relevance) m_combo->currentItem();
}

void MrmlViewItem::setRelevance( Relevance relevance )
{
    m_combo->setCurrentItem( relevance );
}

///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////


int MrmlViewItemList::compareItems( TQPtrCollection::Item item1,
                                    TQPtrCollection::Item item2 )
{
    double s1 = (static_cast<MrmlViewItem*>( item1 ))->similarity();
    double s2 = (static_cast<MrmlViewItem*>( item2 ))->similarity();

    if ( s1 < s2 )
        return 1;
    else if ( s1 > s2 )
        return -1;
    else
        return 0;
}

#include "mrml_view.moc"