summaryrefslogtreecommitdiff
path: root/src/modules/partition/gui/PartitionLabelsView.cpp
blob: b5fd0fc9111069eb4da1156877d2bd6c7111c6b5 (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
/* === This file is part of Calamares - <https://github.com/calamares> ===
 *
 *   Copyright 2014, Aurélien Gâteau <agateau@kde.org>
 *   Copyright 2015-2016, Teo Mrnjavac <teo@kde.org>
 *
 *   Calamares 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 3 of the License, or
 *   (at your option) any later version.
 *
 *   Calamares 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 Calamares. If not, see <http://www.gnu.org/licenses/>.
 */

#include "PartitionLabelsView.h"

#include <core/PartitionModel.h>
#include <core/ColorUtils.h>

#include <utils/CalamaresUtilsGui.h>
#include <utils/Logger.h>

#include <kpmcore/core/device.h>
#include <kpmcore/fs/filesystem.h>

#include <KFormat>

// Qt
#include <QGuiApplication>
#include <QMouseEvent>
#include <QPainter>


static const int LAYOUT_MARGIN = 4;
static const int LABEL_PARTITION_SQUARE_MARGIN =
        qMax( QFontMetrics( CalamaresUtils::defaultFont() ).ascent() - 2, 18 );
static const int LABELS_MARGIN = LABEL_PARTITION_SQUARE_MARGIN;
static const int CORNER_RADIUS = 2;


static QStringList
buildUnknownDisklabelTexts( Device* dev )
{
    QStringList texts = { QObject::tr( "Unpartitioned space or unknown partition table" ),
                          KFormat().formatByteSize( dev->totalLogical() * dev->logicalSize() ) };
    return texts;
}


PartitionLabelsView::PartitionLabelsView( QWidget* parent )
    : QAbstractItemView( parent )
    , m_canBeSelected( []( const QModelIndex& ) { return true; } )
    , m_extendedPartitionHidden( false )
{
    setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed );
    setFrameStyle( QFrame::NoFrame );
    setSelectionBehavior( QAbstractItemView::SelectRows );
    setSelectionMode( QAbstractItemView::SingleSelection );
    this->setObjectName("partitionLabel");
    // Debug
    connect( this, &PartitionLabelsView::clicked,
             this, [=]( const QModelIndex& index )
    {
        cDebug() << "Clicked row" << index.row();
    } );
    setMouseTracking( true );
}


PartitionLabelsView::~PartitionLabelsView()
{
}


QSize
PartitionLabelsView::minimumSizeHint() const
{
    return sizeHint();
}



QSize
PartitionLabelsView::sizeHint() const
{
    QAbstractItemModel* modl = model();
    if ( modl )
    {
        return QSize( -1, LAYOUT_MARGIN + sizeForAllLabels( rect().width() ).height() );
    }
    return QSize();
}


void
PartitionLabelsView::paintEvent( QPaintEvent* event )
{
    Q_UNUSED( event )

    QPainter painter( viewport() );
    painter.fillRect( rect(), palette().window() );
    painter.setRenderHint( QPainter::Antialiasing );

    QRect lRect = labelsRect();

    drawLabels( &painter, lRect, QModelIndex() );
}


QRect
PartitionLabelsView::labelsRect() const
{
    return rect().adjusted( 0, LAYOUT_MARGIN, 0, 0 );
}


static void
drawPartitionSquare( QPainter* painter, const QRect& rect, const QBrush& brush )
{
    painter->fillRect( rect.adjusted( 1, 1, -1, -1 ), brush );
    painter->setRenderHint( QPainter::Antialiasing, true );
    painter->setPen( QPalette().shadow().color() );
    painter->translate( .5, .5 );
    painter->drawRoundedRect( rect.adjusted( 0, 0, -1, -1 ), CORNER_RADIUS, CORNER_RADIUS );
    painter->translate( -.5, -.5 );
}


static void
drawSelectionSquare( QPainter* painter, const QRect& rect, const QBrush& brush )
{
    painter->save();
    painter->setPen( QPen( brush.color().darker(), 1 ) );
    QColor highlightColor = QPalette().highlight().color();
    highlightColor = highlightColor.lighter( 500 );
    highlightColor.setAlpha( 120 );
    painter->setBrush( highlightColor );
    painter->translate( .5, .5 );
    painter->drawRoundedRect( rect.adjusted( 0, 0, -1, -1 ), CORNER_RADIUS, CORNER_RADIUS );
    painter->translate( -.5, -.5 );
    painter->restore();
}


QModelIndexList
PartitionLabelsView::getIndexesToDraw( const QModelIndex& parent ) const
{
    QModelIndexList list;

    QAbstractItemModel* modl = model();
    if ( !modl )
        return list;

    for ( int row = 0; row < modl->rowCount( parent ); ++row )
    {
        QModelIndex index = modl->index( row, 0, parent );

        //HACK: horrible special casing follows.
        //      To save vertical space, we choose to hide short instances of free space.
        //      Arbitrary limit: 10MB.
        const qint64 maxHiddenB = 10000000;
        if ( index.data( PartitionModel::IsFreeSpaceRole ).toBool() &&
             index.data( PartitionModel::SizeRole ).toLongLong() <  maxHiddenB )
            continue;

        if ( !modl->hasChildren( index ) || !m_extendedPartitionHidden )
            list.append( index );

        if ( modl->hasChildren( index ) )
            list.append( getIndexesToDraw( index ) );
    }
    return list;
}


QStringList
PartitionLabelsView::buildTexts( const QModelIndex& index ) const
{
    QString firstLine, secondLine;

    if ( index.data( PartitionModel::IsPartitionNewRole ).toBool() )
    {
        QString label = index.data( PartitionModel::FileSystemLabelRole ).toString();

        if ( !label.isEmpty() )
        {
            firstLine = label;
        }
        else
        {
            QString mountPoint = index.sibling( index.row(),
                                                PartitionModel::MountPointColumn )
                                      .data().toString();
            if ( mountPoint == "/" )
                firstLine = m_customNewRootLabel.isEmpty() ?
                                tr( "Root" ) :
                                m_customNewRootLabel;
            else if ( mountPoint == "/home" )
                firstLine = tr( "Home" );
            else if ( mountPoint == "/boot" )
                firstLine = tr( "Boot" );
            else if ( mountPoint.contains( "/efi" ) &&
                      index.data( PartitionModel::FileSystemTypeRole ).toInt() == FileSystem::Fat32 )
                firstLine = tr( "EFI system" );
            else if ( index.data( PartitionModel::FileSystemTypeRole ).toInt() == FileSystem::LinuxSwap )
                firstLine = tr( "Swap" );
            else if ( !mountPoint.isEmpty() )
                firstLine = tr( "New partition for %1" ).arg( mountPoint );
            else
                firstLine = tr( "New partition" );
        }
    }
    else if ( index.data( PartitionModel::OsproberNameRole ).toString().isEmpty() )
    {
        firstLine = index.data().toString();
        if ( firstLine.startsWith( "/dev/" ) )
            firstLine.remove( 0, 5 );   // "/dev/"
    }
    else
        firstLine = index.data( PartitionModel::OsproberNameRole ).toString();

    if ( index.data( PartitionModel::IsFreeSpaceRole ).toBool() ||
         index.data( PartitionModel::FileSystemTypeRole ).toInt() == FileSystem::Extended )
        secondLine = index.sibling( index.row(),
                                    PartitionModel::SizeColumn )
                          .data().toString();
    else
        //: size[number]  filesystem[name]
        secondLine = tr( "%1  %2" )
                     .arg( index.sibling( index.row(),
                                          PartitionModel::SizeColumn )
                                .data().toString() )
                     .arg( index.sibling( index.row(),
                                          PartitionModel::FileSystemColumn )
                                .data().toString() );

    return { firstLine, secondLine };
}


void
PartitionLabelsView::drawLabels( QPainter* painter,
                                 const QRect& rect,
                                 const QModelIndex& parent )
{
    PartitionModel* modl = qobject_cast< PartitionModel* >( model() );
    if ( !modl )
        return;

    const QModelIndexList indexesToDraw = getIndexesToDraw( parent );

    int label_x = rect.x();
    int label_y = rect.y();
    for ( const QModelIndex& index : indexesToDraw )
    {
        QStringList texts = buildTexts( index );

        QSize labelSize = sizeForLabel( texts );

        QColor labelColor = index.data( Qt::DecorationRole ).value< QColor >();

        if ( label_x + labelSize.width() > rect.width() ) //wrap to new line if overflow
        {
            label_x = rect.x();
            label_y += labelSize.height() + labelSize.height() / 4;
        }

        // Draw hover
        if ( selectionMode() != QAbstractItemView::NoSelection && // no hover without selection
             m_hoveredIndex.isValid() &&
             index == m_hoveredIndex )
        {
            painter->save();
            QRect labelRect( QPoint( label_x, label_y ), labelSize );
            labelRect.adjust( 0, -LAYOUT_MARGIN, 0, -2*LAYOUT_MARGIN );
            painter->translate( 0.5, 0.5 );
            QRect hoverRect = labelRect.adjusted( 0, 0, -1, -1 );
            painter->setBrush( QPalette().background().color().lighter( 102 ) );
            painter->setPen( Qt::NoPen );
            painter->drawRoundedRect( hoverRect, CORNER_RADIUS, CORNER_RADIUS );

            painter->translate( -0.5, -0.5 );
            painter->restore();
        }

        // Is this element the selected one?
        bool sel = selectionMode() != QAbstractItemView::NoSelection &&
                   index.isValid() &&
                   selectionModel() &&
                   !selectionModel()->selectedIndexes().isEmpty() &&
                   selectionModel()->selectedIndexes().first() == index;

        drawLabel( painter, texts, labelColor, QPoint( label_x, label_y ), sel );

        label_x += labelSize.width() + LABELS_MARGIN;
    }

    if ( !modl->rowCount() &&
         !modl->device()->partitionTable() ) // No disklabel or unknown
    {
        QStringList texts = buildUnknownDisklabelTexts( modl->device() );
        QColor labelColor = ColorUtils::unknownDisklabelColor();
        drawLabel( painter, texts, labelColor, QPoint( rect.x(), rect.y() ), false /*can't be selected*/ );
    }
}


QSize
PartitionLabelsView::sizeForAllLabels( int maxLineWidth ) const
{
    PartitionModel* modl = qobject_cast< PartitionModel* >( model() );
    if ( !modl )
        return QSize();

    const QModelIndexList indexesToDraw = getIndexesToDraw( QModelIndex() );

    int lineLength = 0;
    int numLines = 1;
    int singleLabelHeight = 0;
    for ( const QModelIndex& index : indexesToDraw )
    {
        QStringList texts = buildTexts( index );

        QSize labelSize = sizeForLabel( texts );

        if ( lineLength + labelSize.width() > maxLineWidth )
        {
            numLines++;
            lineLength = labelSize.width();
        }
        else
        {
            lineLength += LABELS_MARGIN + labelSize.width();
        }

        singleLabelHeight = qMax( singleLabelHeight, labelSize.height() );
    }

    if ( !modl->rowCount() &&
         !modl->device()->partitionTable() ) // Unknown or no disklabel
    {
        singleLabelHeight = sizeForLabel( buildUnknownDisklabelTexts( modl->device() ) )
                            .height();
    }

    int totalHeight = numLines * singleLabelHeight +
                      ( numLines - 1 ) * singleLabelHeight / 4; //spacings

    return QSize( maxLineWidth, totalHeight );
}


QSize
PartitionLabelsView::sizeForLabel( const QStringList& text ) const
{
    int vertOffset = 0;
    int width = 0;
    for ( const QString& textLine : text )
    {
        QSize textSize = fontMetrics().size( Qt::TextSingleLine, textLine );

        vertOffset += textSize.height();
        width = qMax( width, textSize.width() );
    }
    width += LABEL_PARTITION_SQUARE_MARGIN; //for the color square
    return QSize( width, vertOffset );
}


void
PartitionLabelsView::drawLabel( QPainter* painter,
                                const QStringList& text,
                                const QColor& color,
                                const QPoint& pos,
                                bool selected )
{
    painter->setPen( Qt::black );
    int vertOffset = 0;
    int width = 0;
    for ( const QString& textLine : text )
    {
        QSize textSize = painter->fontMetrics().size( Qt::TextSingleLine, textLine );
        painter->drawText( pos.x()+LABEL_PARTITION_SQUARE_MARGIN,
                           pos.y() + vertOffset + textSize.height() / 2,
                           textLine );
        vertOffset += textSize.height();
        painter->setPen( Qt::gray );
        width = qMax( width, textSize.width() );
    }

    QRect partitionSquareRect( pos.x(),
                               pos.y() - 3,
                               LABEL_PARTITION_SQUARE_MARGIN - 5,
                               LABEL_PARTITION_SQUARE_MARGIN - 5 );
    drawPartitionSquare( painter, partitionSquareRect, color );

    if ( selected )
        drawSelectionSquare( painter, partitionSquareRect.adjusted( 2, 2, -2, -2 ), color );

    painter->setPen( Qt::black );
}


QModelIndex
PartitionLabelsView::indexAt( const QPoint& point ) const
{
    PartitionModel* modl = qobject_cast< PartitionModel* >( model() );
    if ( !modl )
        return QModelIndex();

    const QModelIndexList indexesToDraw = getIndexesToDraw( QModelIndex() );

    QRect rect = this->rect();
    int label_x = rect.x();
    int label_y = rect.y();
    for ( const QModelIndex& index : indexesToDraw )
    {
        QStringList texts = buildTexts( index );

        QSize labelSize = sizeForLabel( texts );

        if ( label_x + labelSize.width() > rect.width() ) //wrap to new line if overflow
        {
            label_x = rect.x();
            label_y += labelSize.height() + labelSize.height() / 4;
        }

        QRect labelRect( QPoint( label_x, label_y ), labelSize );
        if ( labelRect.contains( point ) )
            return index;

        label_x += labelSize.width() + LABELS_MARGIN;
    }

    return QModelIndex();
}


QRect
PartitionLabelsView::visualRect( const QModelIndex& idx ) const
{
    PartitionModel* modl = qobject_cast< PartitionModel* >( model() );
    if ( !modl )
        return QRect();

    const QModelIndexList indexesToDraw = getIndexesToDraw( QModelIndex() );

    QRect rect = this->rect();
    int label_x = rect.x();
    int label_y = rect.y();
    for ( const QModelIndex& index : indexesToDraw )
    {
        QStringList texts = buildTexts( index );

        QSize labelSize = sizeForLabel( texts );

        if ( label_x + labelSize.width() > rect.width() ) //wrap to new line if overflow
        {
            label_x = rect.x();
            label_y += labelSize.height() + labelSize.height() / 4;
        }

        if ( idx.isValid() && idx == index )
            return QRect( QPoint( label_x, label_y ), labelSize );

        label_x += labelSize.width() + LABELS_MARGIN;
    }

    return QRect();
}


QRegion
PartitionLabelsView::visualRegionForSelection( const QItemSelection& selection ) const
{
    Q_UNUSED( selection )

    return QRegion();
}


int
PartitionLabelsView::horizontalOffset() const
{
    return 0;
}


int
PartitionLabelsView::verticalOffset() const
{
    return 0;
}


void
PartitionLabelsView::scrollTo( const QModelIndex& index, ScrollHint hint )
{
    Q_UNUSED( index )
    Q_UNUSED( hint )
}


void
PartitionLabelsView::setCustomNewRootLabel( const QString& text )
{
    m_customNewRootLabel = text;
    viewport()->repaint();
}


void
PartitionLabelsView::setSelectionModel( QItemSelectionModel* selectionModel )
{
    QAbstractItemView::setSelectionModel( selectionModel );
    connect( selectionModel, &QItemSelectionModel::selectionChanged,
             this, [=]
    {
        viewport()->repaint();
    } );
}


void
PartitionLabelsView::setSelectionFilter( SelectionFilter canBeSelected )
{
    m_canBeSelected = canBeSelected;
}


void
PartitionLabelsView::setExtendedPartitionHidden( bool hidden )
{
    m_extendedPartitionHidden = hidden;
}


QModelIndex
PartitionLabelsView::moveCursor( CursorAction cursorAction, Qt::KeyboardModifiers modifiers )
{
    Q_UNUSED( cursorAction )
    Q_UNUSED( modifiers )

    return QModelIndex();
}


bool
PartitionLabelsView::isIndexHidden( const QModelIndex& index ) const
{
    Q_UNUSED( index )

    return false;
}


void
PartitionLabelsView::setSelection( const QRect& rect, QItemSelectionModel::SelectionFlags flags )
{
    QModelIndex eventIndex = indexAt( rect.topLeft() );
    if ( m_canBeSelected( eventIndex ) )
        selectionModel()->select( eventIndex, flags );
}


void
PartitionLabelsView::mouseMoveEvent( QMouseEvent* event )
{
    QModelIndex candidateIndex = indexAt( event->pos() );
    QPersistentModelIndex oldHoveredIndex = m_hoveredIndex;
    if ( candidateIndex.isValid() )
    {
        m_hoveredIndex = candidateIndex;
    }
    else
    {
        m_hoveredIndex = QModelIndex();
        QGuiApplication::restoreOverrideCursor();
    }

    if ( oldHoveredIndex != m_hoveredIndex )
    {
        if ( m_hoveredIndex.isValid() && !m_canBeSelected( m_hoveredIndex ) )
            QGuiApplication::setOverrideCursor( Qt::ForbiddenCursor );
        else
            QGuiApplication::restoreOverrideCursor();

        viewport()->repaint();
    }
}


void
PartitionLabelsView::leaveEvent( QEvent* event )
{
    Q_UNUSED( event )

    QGuiApplication::restoreOverrideCursor();
    if ( m_hoveredIndex.isValid() )
    {
        m_hoveredIndex = QModelIndex();
        viewport()->repaint();
    }
}


void
PartitionLabelsView::mousePressEvent( QMouseEvent* event )
{
    QModelIndex candidateIndex = indexAt( event->pos() );
    if ( m_canBeSelected( candidateIndex ) )
        QAbstractItemView::mousePressEvent( event );
    else
        event->accept();
}


void
PartitionLabelsView::updateGeometries()
{
    updateGeometry(); //get a new rect() for redrawing all the labels
}