Debian Codegraph @

src/Gui/ProgressBar.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2004 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23
24 #include <QApplication>
25 #include <QElapsedTimer>
26 #include <QKeyEvent>
27 #include <QMessageBox>
28 #include <QMetaObject>
29 #include <QThread>
30 #include <QTime>
31 #include <QTimer>
32 #include <QWindow>
33
34
35 #include "ProgressBar.h"
36 #include "MainWindow.h"
37 #include "ProgressDialog.h"
38 #include "WaitCursor.h"
39
40
41 using namespace Gui;
42
43
44 namespace Gui
45 {
46 struct SequencerBarPrivate
47 {
48 ProgressBar* bar;
49 WaitCursor* waitCursor;
50 QElapsedTimer measureTime;
51 QElapsedTimer progressTime;
52 QElapsedTimer checkAbortTime;
53 QString text;
54 bool guiThread;
55 };
56
57 struct ProgressBarPrivate
58 {
59 QTimer* delayShowTimer;
60 int minimumDuration;
61 int observeEventFilter;
62
63 bool isModalDialog(QObject* o) const
64 {
65 QWidget* parent = qobject_cast<QWidget*>(o);
66 if (!parent) {
67 QWindow* window = qobject_cast<QWindow*>(o);
68 if (window) {
69 parent = QWidget::find(window->winId());
70 }
71 }
72 while (parent) {
73 auto* dlg = qobject_cast<QMessageBox*>(parent);
74 if (dlg && dlg->isModal()) {
75 return true;
76 }
77 auto* pd = qobject_cast<QProgressDialog*>(parent);
78 if (pd) {
79 return true;
80 }
81 parent = parent->parentWidget();
82 }
83
84 return false;
85 }
86 };
87 } // namespace Gui
88
89 SequencerBar* SequencerBar::_pclSingleton = nullptr;
90
91 SequencerBar* SequencerBar::instance()
92 {
93 // not initialized?
94 if (!_pclSingleton) {
95 _pclSingleton = new SequencerBar();
96 }
97
98 return _pclSingleton;
99 }
100
101 SequencerBar::SequencerBar()
102 {
103 d = new SequencerBarPrivate;
104 d->bar = nullptr;
105 d->waitCursor = nullptr;
106 d->guiThread = true;
107 }
108
109 SequencerBar::~SequencerBar()
110 {
111 delete d;
112 }
113
114 void SequencerBar::pause()
115 {
116 QThread* currentThread = QThread::currentThread();
117 QThread* thr = d->bar->thread(); // this is the main thread
118 d->bar->leaveControlEvents(d->guiThread);
119 if (thr != currentThread) {
120 return;
121 }
122
123 // allow key handling of dialog and restore cursor
124 d->waitCursor->restoreCursor();
125 QApplication::setOverrideCursor(Qt::ArrowCursor);
126 }
127
128 void SequencerBar::resume()
129 {
130 QThread* currentThread = QThread::currentThread();
131 QThread* thr = d->bar->thread(); // this is the main thread
132 if (thr == currentThread) {
133 QApplication::restoreOverrideCursor();
134 d->waitCursor->setWaitCursor();
135 }
136
137 // must be called as last to get control before WaitCursor
138 d->bar->enterControlEvents(d->guiThread); // grab again
139 }
140
141 void SequencerBar::startStep()
142 {
143 QThread* currentThread = QThread::currentThread();
144 QThread* thr = d->bar->thread(); // this is the main thread
145 if (thr != currentThread) {
146 d->guiThread = false;
147 QMetaObject::invokeMethod(
148 d->bar,
149 "setRangeEx",
150 Qt::QueuedConnection,
151 Q_ARG(int, 0),
152 Q_ARG(int, (int)nTotalSteps)
153 );
154 d->progressTime.start();
155 d->checkAbortTime.start();
156 d->measureTime.start();
157 QMetaObject::invokeMethod(d->bar, "aboutToShow", Qt::QueuedConnection);
158 d->bar->enterControlEvents(d->guiThread);
159 }
160 else {
161 d->guiThread = true;
162 d->bar->setRangeEx(0, (int)nTotalSteps);
163 d->progressTime.start();
164 d->checkAbortTime.start();
165 d->measureTime.start();
166 d->waitCursor = new Gui::WaitCursor;
167 d->bar->enterControlEvents(d->guiThread);
168 d->bar->aboutToShow();
169 }
170 }
171
172 void SequencerBar::checkAbort()
173 {
174 if (d->bar->thread() != QThread::currentThread()) {
175 return;
176 }
177 if (!wasCanceled()) {
178 if (d->checkAbortTime.elapsed() < 500) {
179 return;
180 }
181 d->checkAbortTime.restart();
182 qApp->processEvents();
183 return;
184 }
185 // restore cursor
186 pause();
187 bool ok = d->bar->canAbort();
188 // continue and show up wait cursor if needed
189 resume();
190
191 // force to abort the operation
192 if (ok) {
193 abort();
194 }
195 else {
196 rejectCancel();
197 }
198 }
199
200 void SequencerBar::nextStep(bool canAbort)
201 {
202 QThread* currentThread = QThread::currentThread();
203 QThread* thr = d->bar->thread(); // this is the main thread
204 if (thr != currentThread) {
205 if (wasCanceled() && canAbort) {
206 abort();
207 }
208 else {
209 setValue((int)nProgress + 1);
210 }
211 }
212 else {
213 if (wasCanceled() && canAbort) {
214 // restore cursor
215 pause();
216 bool ok = d->bar->canAbort();
217 // continue and show up wait cursor if needed
218 resume();
219
220 // force to abort the operation
221 if (ok) {
222 abort();
223 }
224 else {
225 rejectCancel();
226 setValue((int)nProgress + 1);
227 }
228 }
229 else {
230 setValue((int)nProgress + 1);
231 }
232 }
233 }
234
235 void SequencerBar::setProgress(size_t step)
236 {
237 QThread* currentThread = QThread::currentThread();
238 QThread* thr = d->bar->thread(); // this is the main thread
239 if (thr != currentThread) {
240 QMetaObject::invokeMethod(d->bar, "show", Qt::QueuedConnection);
241 }
242 else {
243 d->bar->show();
244 }
245
246 setValue((int)step);
247 }
248
249 void SequencerBar::setValue(int step)
250 {
251 QThread* currentThread = QThread::currentThread();
252 QThread* thr = d->bar->thread(); // this is the main thread
253 // if number of total steps is unknown then increment only by one
254 if (nTotalSteps == 0) {
255 int elapsed = d->progressTime.elapsed();
256 // allow an update every 100 milliseconds only
257 if (elapsed > 100) {
258 d->progressTime.restart();
259 if (thr != currentThread) {
260 QMetaObject::invokeMethod(
261 d->bar,
262 "setValueEx",
263 Qt::/*Blocking*/ QueuedConnection,
264 Q_ARG(int, d->bar->value() + 1)
265 );
266 }
267 else {
268 d->bar->setValueEx(d->bar->value() + 1);
269 qApp->processEvents();
270 }
271 }
272 }
273 else {
274 int elapsed = d->progressTime.elapsed();
275 // allow an update every 100 milliseconds only
276 if (elapsed > 100) {
277 d->progressTime.restart();
278 if (thr != currentThread) {
279 QMetaObject::invokeMethod(
280 d->bar,
281 "setValueEx",
282 Qt::/*Blocking*/ QueuedConnection,
283 Q_ARG(int, step)
284 );
285 if (d->bar->isVisible()) {
286 showRemainingTime();
287 }
288 }
289 else {
290 d->bar->setValueEx(step);
291 if (d->bar->isVisible()) {
292 showRemainingTime();
293 }
294 d->bar->resetObserveEventFilter();
295 qApp->processEvents();
296 }
297 }
298 }
299 }
300
301 void SequencerBar::showRemainingTime()
302 {
303 QThread* currentThread = QThread::currentThread();
304 QThread* thr = d->bar->thread(); // this is the main thread
305
306 int elapsed = d->measureTime.elapsed();
307 int progress = d->bar->value();
308 int totalSteps = d->bar->maximum() - d->bar->minimum();
309
310 QString txt = d->text;
311 // More than 5 percent complete or more than 5 secs have elapsed.
312 if (progress * 20 > totalSteps || elapsed > 5000) {
313 int rest = (int)((double)totalSteps / progress * elapsed) - elapsed;
314
315 // more than 1 secs have elapsed and at least 100 ms are remaining
316 if (elapsed > 1000 && rest > 100) {
317 QTime time(0, 0, 0);
318 time = time.addSecs(rest / 1000);
319 QString remain = Gui::ProgressBar::tr("Remaining: %1").arg(time.toString());
320 QString status = QStringLiteral("%1\t[%2]").arg(txt, remain);
321
322 if (thr != currentThread) {
323 QMetaObject::invokeMethod(
324 getMainWindow(),
325 "showMessage",
326 Qt::/*Blocking*/ QueuedConnection,
327 Q_ARG(QString, status)
328 );
329 }
330 else {
331 getMainWindow()->showMessage(status);
332 }
333 }
334 }
335 }
336
337 void SequencerBar::resetData()
338 {
339 QThread* currentThread = QThread::currentThread();
340 QThread* thr = d->bar->thread(); // this is the main thread
341 if (thr != currentThread) {
342 QMetaObject::invokeMethod(d->bar, "resetEx", Qt::QueuedConnection);
343 QMetaObject::invokeMethod(d->bar, "aboutToHide", Qt::QueuedConnection);
344 QMetaObject::invokeMethod(
345 getMainWindow(),
346 "showMessage",
347 Qt::/*Blocking*/ QueuedConnection,
348 Q_ARG(QString, QString())
349 );
350 QMetaObject::invokeMethod(
351 getMainWindow(),
352 "setPaneText",
353 Qt::/*Blocking*/ QueuedConnection,
354 Q_ARG(int, 1),
355 Q_ARG(QString, QString())
356 );
357 d->bar->leaveControlEvents(d->guiThread);
358 }
359 else {
360 d->bar->resetEx();
361 // Note: Under Qt 4.1.4 this forces to run QWindowsStyle::eventFilter() twice
362 // handling the same event thus a warning is printed. Possibly, this is a bug
363 // in Qt. The message is QEventDispatcherUNIX::unregisterTimer: invalid argument.
364 d->bar->aboutToHide();
365 delete d->waitCursor;
366 d->waitCursor = nullptr;
367 d->bar->leaveControlEvents(d->guiThread);
368 getMainWindow()->setPaneText(1, QString());
369 getMainWindow()->showMessage(QString());
370 }
371
372 SequencerBase::resetData();
373 }
374
375 void SequencerBar::abort()
376 {
377 // resets
378 resetData();
379 Base::AbortException exc("User aborted");
380 throw exc;
381 }
382
383 void SequencerBar::setText(const char* pszTxt)
384 {
385 QThread* currentThread = QThread::currentThread();
386 QThread* thr = d->bar->thread(); // this is the main thread
387
388 // print message to the statusbar
389 d->text = pszTxt ? QString::fromUtf8(pszTxt) : QLatin1String("");
390 if (thr != currentThread) {
391 QMetaObject::invokeMethod(
392 getMainWindow(),
393 "showMessage",
394 Qt::/*Blocking*/ QueuedConnection,
395 Q_ARG(QString, d->text)
396 );
397 }
398 else {
399 getMainWindow()->showMessage(d->text);
400 }
401 }
402
403 bool SequencerBar::isBlocking() const
404 {
405 return d->guiThread;
406 }
407
408 QProgressBar* SequencerBar::getProgressBar(QWidget* parent)
409 {
410 if (!d->bar) {
411 d->bar = new ProgressBar(this, parent);
412 }
413 return d->bar;
414 }
415
416 // -------------------------------------------------------
417
418 /* TRANSLATOR Gui::ProgressBar */
419
420 ProgressBar::ProgressBar(SequencerBar* s, QWidget* parent)
421 : QProgressBar(parent)
422 , sequencer(s)
423 {
424 #ifdef QT_WINEXTRAS_LIB
425 m_taskbarButton = nullptr;
426 m_taskbarButton = nullptr;
427 #endif
428 d = new Gui::ProgressBarPrivate;
429 d->minimumDuration = 2000; // 2 seconds
430 d->delayShowTimer = new QTimer(this);
431 d->delayShowTimer->setSingleShot(true);
432 connect(d->delayShowTimer, &QTimer::timeout, this, &ProgressBar::delayedShow);
433 d->observeEventFilter = 0;
434
435 setFixedWidth(120);
436
437 // write percentage to the center
438 setAlignment(Qt::AlignHCenter);
439 hide();
440 }
441
442 ProgressBar::~ProgressBar()
443 {
444 disconnect(d->delayShowTimer, &QTimer::timeout, this, &ProgressBar::delayedShow);
445 delete d->delayShowTimer;
446 delete d;
447 }
448
449 int ProgressBar::minimumDuration() const
450 {
451 return d->minimumDuration;
452 }
453
454 void ProgressBar::resetEx()
455 {
456 QProgressBar::reset();
457 #ifdef QT_WINEXTRAS_LIB
458 setupTaskBarProgress();
459 m_taskbarProgress->reset();
460 #endif
461 }
462
463 void ProgressBar::setRangeEx(int minimum, int maximum)
464 {
465 QProgressBar::setRange(minimum, maximum);
466 #ifdef QT_WINEXTRAS_LIB
467 setupTaskBarProgress();
468 m_taskbarProgress->setRange(minimum, maximum);
469 #endif
470 }
471
472 void ProgressBar::setValueEx(int value)
473 {
474 QProgressBar::setValue(value);
475 #ifdef QT_WINEXTRAS_LIB
476 setupTaskBarProgress();
477 m_taskbarProgress->setValue(value);
478 #endif
479 }
480
481 void ProgressBar::setMinimumDuration(int ms)
482 {
483 if (value() == 0) {
484 d->delayShowTimer->stop();
485 d->delayShowTimer->start(ms);
486 }
487
488 d->minimumDuration = ms;
489 }
490
491 void ProgressBar::aboutToShow()
492 {
493 // delay showing the bar
494 d->delayShowTimer->start(d->minimumDuration);
495 #ifdef QT_WINEXTRAS_LIB
496 setupTaskBarProgress();
497 m_taskbarProgress->show();
498 #endif
499 }
500
501 void ProgressBar::delayedShow()
502 {
503 if (!isVisible() && !sequencer->wasCanceled() && sequencer->isRunning()) {
504 show();
505 }
506 }
507
508 void ProgressBar::aboutToHide()
509 {
510 hide();
511 #ifdef QT_WINEXTRAS_LIB
512 setupTaskBarProgress();
513 m_taskbarProgress->hide();
514 #endif
515 }
516
517 bool ProgressBar::canAbort() const
518 {
519 auto ret = QMessageBox::question(
520 getMainWindow(),
521 tr("Aborting"),
522 tr("Abort the operation?"),
523 QMessageBox::Yes | QMessageBox::No,
524 QMessageBox::No
525 );
526
527 return (ret == QMessageBox::Yes) ? true : false;
528 }
529
530 void ProgressBar::showEvent(QShowEvent* e)
531 {
532 QProgressBar::showEvent(e);
533 d->delayShowTimer->stop();
534 }
535
536 void ProgressBar::hideEvent(QHideEvent* e)
537 {
538 QProgressBar::hideEvent(e);
539 d->delayShowTimer->stop();
540 }
541
542 void ProgressBar::resetObserveEventFilter()
543 {
544 d->observeEventFilter = 0;
545 }
546
547 void ProgressBar::enterControlEvents(bool grab)
548 {
549 qApp->installEventFilter(this);
550
551 // Make sure that we get the key events, otherwise the Inventor viewer usurps the key events
552 // This also disables accelerators.
553 #if defined(Q_OS_LINUX)
554 Q_UNUSED(grab)
555 #else
556 if (grab) {
557 grabKeyboard();
558 }
559 #endif
560 }
561
562 void ProgressBar::leaveControlEvents(bool release)
563 {
564 qApp->removeEventFilter(this);
565
566 #if defined(Q_OS_LINUX)
567 Q_UNUSED(release)
568 #else
569 // release the keyboard again
570 if (release) {
571 releaseKeyboard();
572 }
573 #endif
574 }
575
576 #ifdef QT_WINEXTRAS_LIB
577 void ProgressBar::setupTaskBarProgress()
578 {
579 if (!m_taskbarButton || !m_taskbarProgress) {
580 m_taskbarButton = new QWinTaskbarButton(this);
581 m_taskbarButton->setWindow(MainWindow::getInstance()->windowHandle());
582 // m_myButton->setOverlayIcon(QIcon(""));
583
584 m_taskbarProgress = m_taskbarButton->progress();
585 }
586 }
587 #endif
588
589 bool ProgressBar::eventFilter(QObject* o, QEvent* e)
590 {
591 if (sequencer->isRunning() && e) {
592 QThread* currentThread = QThread::currentThread();
593 QThread* thr = this->thread(); // this is the main thread
594 if (thr != currentThread) {
595 if (e->type() == QEvent::KeyPress) {
596 auto ke = static_cast<QKeyEvent*>(e);
597 if (ke->key() == Qt::Key_Escape) {
598 // cancel the operation
599 sequencer->tryToCancel();
600 return true;
601 }
602 }
603 return QProgressBar::eventFilter(o, e);
604 }
605
606 // main thread
607 switch (e->type()) {
608 // check for ESC
609 case QEvent::KeyPress: {
610 auto ke = static_cast<QKeyEvent*>(e);
611 if (ke->key() == Qt::Key_Escape) {
612 // eventFilter() was called from the application 50 times without performing a
613 // new step (app could hang)
614 if (d->observeEventFilter > 50) {
615 // tries to unlock the application if it hangs (probably due to incorrect
616 // usage of Base::Sequencer)
617 if (ke->modifiers() & (Qt::ControlModifier | Qt::AltModifier)) {
618 sequencer->resetData();
619 return true;
620 }
621 }
622
623 // cancel the operation
624 sequencer->tryToCancel();
625 }
626
627 return true;
628 } break;
629
630 // ignore all these events
631 case QEvent::KeyRelease:
632 case QEvent::Enter:
633 case QEvent::Leave:
634 case QEvent::MouseButtonDblClick:
635 case QEvent::MouseButtonRelease:
636 case QEvent::MouseMove:
637 case QEvent::NativeGesture:
638 case QEvent::ContextMenu: {
639 if (!d->isModalDialog(o)) {
640 return true;
641 }
642 } break;
643
644 // special case if the main window's close button was pressed
645 case QEvent::Close: {
646 // avoid to exit while app is working
647 // note: all other widget types are allowed to be closed anyway
648 if (o == getMainWindow()) {
649 e->ignore();
650 return true;
651 }
652 } break;
653
654 // do a system beep and ignore the event
655 case QEvent::MouseButtonPress: {
656 if (!d->isModalDialog(o)) {
657 QApplication::beep();
658 return true;
659 }
660 } break;
661
662 default: {
663 } break;
664 }
665
666 d->observeEventFilter++;
667 }
668
669 return QProgressBar::eventFilter(o, e);
670 }
671
672
673 #include "moc_ProgressBar.cpp"