summaryrefslogtreecommitdiffstats
path: root/src/widgets/qprogressbar.cpp
blob: 1219419e7236781180cfceb33d80fcf97ee1aa1a (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
/****************************************************************************
**
** Implementation of QProgressBar class
**
** Created : 970521
**
** Copyright (C) 1992-2008 Trolltech ASA.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free
** Software Foundation and appearing in the files LICENSE.GPL2
** and LICENSE.GPL3 included in the packaging of this file.
** Alternatively you may (at your option) use any later version
** of the GNU General Public License if such license has been
** publicly approved by Trolltech ASA (or its successors, if any)
** and the KDE Free Qt Foundation.
**
** Please review the following information to ensure GNU General
** Public Licensing requirements will be met:
** http://trolltech.com/products/qt/licenses/licensing/opensource/.
** If you are unsure which license is appropriate for your use, please
** review the following information:
** http://trolltech.com/products/qt/licenses/licensing/licensingoverview
** or contact the sales department at sales@trolltech.com.
**
** This file may be used under the terms of the Q Public License as
** defined by Trolltech ASA and appearing in the file LICENSE.QPL
** included in the packaging of this file.  Licensees holding valid Qt
** Commercial licenses may use this file in accordance with the Qt
** Commercial License Agreement provided with the Software.
**
** This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted
** herein.
**
**********************************************************************/

#include "qprogressbar.h"
#ifndef QT_NO_PROGRESSBAR
#include "qpainter.h"
#include "qdrawutil.h"
#include "qpixmap.h"
#include "qstyle.h"
#include "qwmatrix.h"
#include "../kernel/qinternal_p.h"
#if defined(QT_ACCESSIBILITY_SUPPORT)
#include "qaccessible.h"
#endif
#include <limits.h>

class QProgressBarPrivate
{
    public:
        QProgressBarPrivate() : last_painted_progress( 0 ) { }

    int last_painted_progress;
};

/*!
    \class QProgressBar qprogressbar.h
    \brief The QProgressBar widget provides a horizontal progress bar.

    \ingroup advanced
    \mainclass

    A progress bar is used to give the user an indication of the
    progress of an operation and to reassure them that the application
    is still running.

    The progress bar uses the concept of \e steps; you give it the
    total number of steps and the number of steps completed so far and
    it will display the percentage of steps that have been completed.
    You can specify the total number of steps in the constructor or
    later with setTotalSteps(). The current number of steps is set
    with setProgress(). The progress bar can be rewound to the
    beginning with reset().

    If the total is given as 0 the progress bar shows a busy indicator
    instead of a percentage of steps. This is useful, for example,
    when using QFtp or QHttp to download items when they are unable to
    determine the size of the item being downloaded.

    \sa QProgressDialog

    <img src=qprogbar-m.png> <img src=qprogbar-w.png>

    \sa QProgressDialog
    \link guibooks.html#fowler GUI Design Handbook: Progress Indicator\endlink
*/


/*!
    Constructs a progress bar.

    The total number of steps is set to 100 by default.

    The \a parent, \a name and widget flags, \a f, are passed on to
    the QFrame::QFrame() constructor.

    \sa setTotalSteps()
*/

QProgressBar::QProgressBar( QWidget *parent, const char *name, WFlags f )
    : QFrame( parent, name, f | WNoAutoErase ),
      total_steps( 100 ),
      progress_val( -1 ),
      percentage( -1 ),
      center_indicator( TRUE ),
      auto_indicator( TRUE ),
      percentage_visible( TRUE ),
      d( new QProgressBarPrivate ),
      m_orientation( Horizontal )
{
    setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
    initFrame();
}


/*!
    Constructs a progress bar.

    The \a totalSteps is the total number of steps that need to be
    completed for the operation which this progress bar represents.
    For example, if the operation is to examine 50 files, this value
    would be 50. Before examining the first file, call setProgress(0);
    call setProgress(50) after examining the last file.

    The \a parent, \a name and widget flags, \a f, are passed to the
    QFrame::QFrame() constructor.

    \sa setTotalSteps(), setProgress()
*/

QProgressBar::QProgressBar( int totalSteps,
			    QWidget *parent, const char *name, WFlags f )
    : QFrame( parent, name, f | WNoAutoErase ),
      total_steps( totalSteps ),
      progress_val( -1 ),
      percentage( -1 ),
      center_indicator( TRUE ),
      auto_indicator( TRUE ),
      percentage_visible( TRUE ),
      d( new QProgressBarPrivate ),
      m_orientation( Horizontal )
{
    setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
    initFrame();
}


/*!
    Destroys the object and frees any allocated ressources.
*/
 
QProgressBar::~QProgressBar()
{
    delete d;
}


/*!
    Reset the progress bar. The progress bar "rewinds" and shows no
    progress.
*/

void QProgressBar::reset()
{
    progress_val = -1;
    percentage = -1;
    setIndicator(progress_str, progress_val, total_steps);
    repaint( FALSE );
}


/*!
    \property QProgressBar::totalSteps
    \brief The total number of steps.

    If totalSteps is 0, the progress bar will display a busy
    indicator.

    \sa totalSteps()
*/

void QProgressBar::setTotalSteps( int totalSteps )
{
    total_steps = totalSteps;

    // Current progress is invalid if larger than total
    if ( total_steps < progress_val )
	progress_val = -1;

    if ( isVisible() &&
	 ( setIndicator(progress_str, progress_val, total_steps) || !total_steps ) )
	repaint( FALSE );
}


/*!
    \property QProgressBar::progress
    \brief The current amount of progress

    This property is -1 if progress counting has not started.
*/

void QProgressBar::setProgress( int progress )
{
    if ( progress == progress_val ||
	 progress < 0 || ( ( progress > total_steps ) && total_steps ) )
	return;

    const bool needRepaint = isVisible() && requireRepaint( progress );

    progress_val = progress;

    setIndicator( progress_str, progress_val, total_steps );

    if ( needRepaint ) {
        repaint( FALSE );
        d->last_painted_progress = progress;
    }

#if defined(QT_ACCESSIBILITY_SUPPORT)
    QAccessible::updateAccessibility( this, 0, QAccessible::ValueChanged );
#endif
}

/*!
    \overload

    Sets the amount of progress to \a progress and the total number of
    steps to \a totalSteps.

    \sa setTotalSteps()
*/

void QProgressBar::setProgress( int progress, int totalSteps )
{
    if ( total_steps != totalSteps )
	setTotalSteps( totalSteps );
    setProgress( progress );
}

/*!
  \property QProgressBar::progressString
  \brief the amount of progress as a string

    This property is QString::null if progress counting has not started.
*/


/*!
    \reimp
*/
QSize QProgressBar::sizeHint() const
{
    constPolish();
    QFontMetrics fm = fontMetrics();
    int cw = style().pixelMetric(QStyle::PM_ProgressBarChunkWidth, this);
    QSize sh = style().sizeFromContents(QStyle::CT_ProgressBar, this,
				    QSize( cw * 7 + fm.width( '0' ) * 4,
					   fm.height() + 8));
    if (m_orientation == Qt::Horizontal) {
        return sh;
    }
    else {
        return QSize(sh.height(), sh.width());
    }
}


/*!
    \reimp
*/
QSize QProgressBar::minimumSizeHint() const
{
    return sizeHint();
}

/*!
    \property QProgressBar::centerIndicator
    \brief whether the indicator string should be centered

    Changing this property sets \l QProgressBar::indicatorFollowsStyle
    to FALSE. The default is TRUE.
*/

void QProgressBar::setCenterIndicator( bool on )
{
    if ( !auto_indicator && on == center_indicator )
	return;
    auto_indicator = FALSE;
    center_indicator = on;
    repaint( FALSE );
}

/*!
    \property QProgressBar::indicatorFollowsStyle
    \brief whether the display of the indicator string should follow the GUI style

    The default is TRUE.

    \sa centerIndicator
*/

void QProgressBar::setIndicatorFollowsStyle( bool on )
{
    if ( on == auto_indicator )
	return;
    auto_indicator = on;
    repaint( FALSE );
}

/*!
    \property QProgressBar::percentageVisible
    \brief whether the current progress value is displayed

    The default is TRUE.

    \sa centerIndicator, indicatorFollowsStyle
*/
void QProgressBar::setPercentageVisible( bool on )
{
    if ( on == percentage_visible )
	return;
    percentage_visible = on;
    repaint( FALSE );
}

/*!
    \reimp
*/
void QProgressBar::show()
{
    setIndicator( progress_str, progress_val, total_steps );
    QFrame::show();
}

void QProgressBar::initFrame()
{
    setFrameStyle(QFrame::NoFrame);
}

/*!
    \reimp
*/
void QProgressBar::styleChange( QStyle& old )
{
    initFrame();
    QFrame::styleChange( old );
}

/*!
    This method returns whether changing the progress to the \a newValue
    would require a repaint of the progress bar. This allows efficient
    repainting.
*/
bool QProgressBar::requireRepaint( int newProgress ) const
{
    if ( newProgress == progress_val ||
         newProgress == d->last_painted_progress ) {
        return false;
    }

    const int width = contentsRect().width();
    if ( width == 0 ) {
        return false;
    }

    float progressPerPixel = 1.0;
    if ( total_steps > width ) {
        progressPerPixel = float( total_steps ) / float( width );
    }

    const int delta = d->last_painted_progress - newProgress;
    return QABS( delta ) >= progressPerPixel;
}

Qt::Orientation QProgressBar::orientation() const
{
    return m_orientation;
}

void QProgressBar::setOrientation(Orientation orient)
{
    m_orientation = orient;
    if (m_orientation == Qt::Horizontal) {
        setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
    }
    else {
        setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Expanding ) );
    }
}


/*!
    This method is called to generate the text displayed in the center
    (or in some styles, to the left) of the progress bar.

    The \a progress may be negative, indicating that the progress bar
    is in the "reset" state before any progress is set.

    The default implementation is the percentage of completion or
    blank in the reset state. The percentage is calculated based on
    the \a progress and \a totalSteps. You can set the \a indicator
    text if you wish.

    To allow efficient repainting of the progress bar, this method
    should return FALSE if the string is unchanged from the last call
    to this function.
*/

bool QProgressBar::setIndicator( QString & indicator, int progress,
				 int totalSteps )
{
    if ( !totalSteps )
	return FALSE;
    if ( progress < 0 ) {
	indicator = QString::fromLatin1("");
	return TRUE;
    } else {
	// Get the values down to something usable.
	if ( totalSteps > INT_MAX/1000 ) {
	    progress /= 1000;
	    totalSteps /= 1000;
	}

	int np = progress * 100 / totalSteps;
	if ( np != percentage ) {
	    percentage = np;
	    indicator.sprintf( "%d%%", np );
	    return TRUE;
	} else {
	    return FALSE;
	}
    }
}


/*!
    \reimp
*/
void QProgressBar::drawContents( QPainter *p )
{
	const QRect bar = contentsRect();
	
	QSharedDoubleBuffer buffer( p, bar.x(), bar.y(), bar.width(), bar.height() );
	
	QPoint pn = backgroundOffset();
	buffer.painter()->setBrushOrigin( -pn.x(), -pn.y() );

	const QPixmap *bpm = paletteBackgroundPixmap();
	if ( bpm ) {
		buffer.painter()->fillRect( bar, QBrush( paletteBackgroundColor(), *bpm ) );
	}
	else {
		buffer.painter()->fillRect( bar, paletteBackgroundColor() );
	}
	buffer.painter()->setFont( p->font() );

	QStyle::SFlags flags = QStyle::Style_Default;
	if (isEnabled()) {
		flags |= QStyle::Style_Enabled;
	}
	if (hasFocus()) {
		flags |= QStyle::Style_HasFocus;
	}
	if (hasMouse()) {
		flags |= QStyle::Style_MouseOver;
	}

	style().drawControl(QStyle::CE_ProgressBarGroove, buffer.painter(), this,
			QStyle::visualRect(style().subRect(QStyle::SR_ProgressBarGroove, this), this ),
			colorGroup(), flags);

	QWMatrix oldMatrix = buffer.painter()->worldMatrix();

	const QStyleControlElementData &ceData = populateControlElementDataFromWidget(this, QStyleOption());
	QStyle::ControlElementFlags elementFlags = getControlElementFlagsForObject(this, QStyleOption());

	QRect ceDataRectOrig = ceData.rect;

	// Draw contents
	if (m_orientation == Qt::Vertical) {
		// If oriented vertically, apply a 90 degree rotation matrix to the painter
		QWMatrix m;

// 		// Upside down
// 		m.rotate(90.0);
// 		m.translate(0, (bar.width())*(-1.0));

		// Right side up
		m.rotate(-90.0);
		m.translate((bar.height())*(-1.0), 0);

		buffer.painter()->setWorldMatrix(m, TRUE);

		const_cast<QStyleControlElementData&>(ceData).rect = QRect(ceData.rect.y(), ceData.rect.x(), ceData.rect.height(), ceData.rect.width());
	}

	style().drawControl(QStyle::CE_ProgressBarContents, buffer.painter(), ceData, elementFlags,
			QStyle::visualRect(style().subRect(QStyle::SR_ProgressBarContents, ceData, elementFlags, this), ceData, elementFlags),
			colorGroup(), flags, QStyleOption(), this);

	buffer.painter()->setWorldMatrix(oldMatrix, TRUE);

	if (percentageVisible()) {
		style().drawControl(QStyle::CE_ProgressBarLabel, buffer.painter(), this,
				QStyle::visualRect(style().subRect(QStyle::SR_ProgressBarLabel, this), this ),
				colorGroup(), flags);
	}

	const_cast<QStyleControlElementData&>(ceData).rect = ceDataRectOrig;
}

#endif