Don't try to manipulate the viewfinder renderer if we fail to create it.
[harmattan/cameraplus] / lib / qtcamgraphicsviewfinder.cpp
1 #include "qtcamgraphicsviewfinder.h"
2 #include "qtcamconfig.h"
3 #include "qtcamdevice.h"
4 #include <QDebug>
5 #include "qtcamviewfinderrenderer.h"
6 #include <QPainter>
7 #include <QGraphicsSceneResizeEvent>
8
9 class QtCamGraphicsViewfinderPrivate {
10 public:
11   void ensureBackend() {
12     if (!renderer) {
13       renderer = QtCamViewfinderRenderer::create(conf, q_ptr);
14       if (!renderer) {
15         qCritical() << "Failed to create a viewfinder renderer";
16         return;
17       }
18
19       renderer->resize(q_ptr->size());
20       QObject::connect(renderer, SIGNAL(updateRequested()), q_ptr, SLOT(updateRequested()));
21     }
22   }
23
24   void resetBackend() {
25     if (renderer) {
26       renderer->reset();
27     }
28   }
29
30   QtCamViewfinderRenderer *renderer;
31   QtCamConfig *conf;
32   QtCamDevice *dev;
33   QtCamGraphicsViewfinder *q_ptr;
34 };
35
36 QtCamGraphicsViewfinder::QtCamGraphicsViewfinder(QtCamConfig *config, QGraphicsItem *parent) :
37   QGraphicsWidget(parent), d_ptr(new QtCamGraphicsViewfinderPrivate) {
38   d_ptr->conf = config;
39   d_ptr->dev = 0;
40   d_ptr->renderer = 0;
41   d_ptr->q_ptr = this;
42 }
43
44 QtCamGraphicsViewfinder::~QtCamGraphicsViewfinder() {
45   delete d_ptr; d_ptr = 0;
46 }
47
48 GstElement *QtCamGraphicsViewfinder::sinkElement() {
49   d_ptr->ensureBackend();
50
51   if (!d_ptr->renderer) {
52     return 0;
53   }
54
55   return d_ptr->renderer->sinkElement();
56 }
57
58 bool QtCamGraphicsViewfinder::setDevice(QtCamDevice *device) {
59   if (device && d_ptr->dev == device) {
60     return true;
61   }
62
63   if (d_ptr->dev) {
64     qWarning() << "QtCamGraphicsViewfinder: viewfinder cannot be replaced.";
65     return false;
66   }
67
68   if (!device) {
69     qWarning() << "QtCamGraphicsViewfinder: viewfinder cannot be unset.";
70     return false;
71   }
72
73   // This is to break the loop.
74   d_ptr->dev = device;
75   if (!device->setViewfinder(this)) {
76     d_ptr->dev = 0;
77     return false;
78   }
79
80   d_ptr->resetBackend();
81
82   return true;
83 }
84
85 void QtCamGraphicsViewfinder::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
86                                     QWidget *widget) {
87   Q_UNUSED(widget);
88   Q_UNUSED(option);
89
90   painter->fillRect(boundingRect(), Qt::black);
91
92   if (!d_ptr->renderer) {
93     return;
94   }
95
96   d_ptr->renderer->paint(painter);
97 }
98
99 void QtCamGraphicsViewfinder::resizeEvent(QGraphicsSceneResizeEvent *event) {
100   QGraphicsWidget::resizeEvent(event);
101
102   if (!d_ptr->renderer) {
103     return;
104   }
105
106   d_ptr->renderer->resize(event->newSize());
107 }
108
109 void QtCamGraphicsViewfinder::updateRequested() {
110   update();
111 }