]> git.sesse.net Git - kdenlive/blob - src/titlewidget.cpp
1edc631e6f3fc0538df431dd16e5b0e79eb1df83
[kdenlive] / src / titlewidget.cpp
1 /***************************************************************************
2                           titlewidget.cpp  -  description
3                              -------------------
4     begin                : Feb 28 2008
5     copyright            : (C) 2008 by Marco Gittler
6     email                : g.marco@freenet.de
7  ***************************************************************************/
8
9 /***************************************************************************
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General Public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  ***************************************************************************/
17
18 #include "titlewidget.h"
19 #include "kdenlivesettings.h"
20
21 #include <cmath>
22
23 #include <KDebug>
24 #include <KGlobalSettings>
25 #include <KFileDialog>
26 #include <KStandardDirs>
27 #include <KMessageBox>
28 #include <kio/netaccess.h>
29
30 #include <QDomDocument>
31 #include <QGraphicsItem>
32 #include <QGraphicsSvgItem>
33 #include <QTimer>
34 #include <QToolBar>
35 #include <QMenu>
36 #include <QSignalMapper>
37 #include <QTextBlockFormat>
38 #include <QTextCursor>
39
40 int settingUp = false;
41
42 const int IMAGEITEM = 7;
43 const int RECTITEM = 3;
44 const int TEXTITEM = 8;
45 static bool insertingValues = false;
46
47 TitleWidget::TitleWidget(KUrl url, Timecode tc, QString projectTitlePath, Render *render, QWidget *parent) :
48         QDialog(parent),
49         Ui::TitleWidget_UI(),
50         m_startViewport(NULL),
51         m_endViewport(NULL),
52         m_render(render),
53         m_count(0),
54         m_unicodeDialog(new UnicodeDialog(UnicodeDialog::InputHex)),
55         m_projectTitlePath(projectTitlePath),
56         m_tc(tc)
57 {
58     setupUi(this);
59     setFont(KGlobalSettings::toolBarFont());
60     //toolBox->setFont(KGlobalSettings::toolBarFont());
61     frame_properties->setEnabled(false);
62     rect_properties->setFixedHeight(frame_properties->height() + 4);
63     no_properties->setFixedHeight(frame_properties->height() + 4);
64     image_properties->setFixedHeight(frame_properties->height() + 4);
65     text_properties->setFixedHeight(frame_properties->height() + 4);
66     frame_properties->setFixedHeight(frame_toolbar->height());
67     m_frameWidth = render->renderWidth();
68     m_frameHeight = render->renderHeight();
69     showToolbars(TITLE_NONE);
70
71     //TODO: get default title duration instead of hardcoded one
72     title_duration->setText(m_tc.getTimecode(GenTime(5000 / 1000.0)));
73
74     connect(kcolorbutton, SIGNAL(clicked()), this, SLOT(slotChangeBackground())) ;
75     connect(horizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(slotChangeBackground())) ;
76
77     connect(fontColorButton, SIGNAL(clicked()), this, SLOT(slotUpdateText())) ;
78     connect(font_family, SIGNAL(currentFontChanged(const QFont &)), this, SLOT(slotUpdateText())) ;
79     connect(font_size, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateText())) ;
80     connect(textAlpha, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateText()));
81     connect(font_weight_box, SIGNAL(currentIndexChanged(int)), this, SLOT(slotUpdateText()));
82
83     connect(rectFAlpha, SIGNAL(valueChanged(int)), this, SLOT(rectChanged()));
84     connect(rectBAlpha, SIGNAL(valueChanged(int)), this, SLOT(rectChanged()));
85     connect(rectFColor, SIGNAL(clicked()), this, SLOT(rectChanged()));
86     connect(rectBColor, SIGNAL(clicked()), this, SLOT(rectChanged()));
87     connect(rectLineWidth, SIGNAL(valueChanged(int)), this, SLOT(rectChanged()));
88
89     connect(startViewportX, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
90     connect(startViewportY, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
91     connect(startViewportSize, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
92     connect(endViewportX, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
93     connect(endViewportY, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
94     connect(endViewportSize, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
95
96     connect(zValue, SIGNAL(valueChanged(int)), this, SLOT(zIndexChanged(int)));
97     connect(itemzoom, SIGNAL(valueChanged(int)), this, SLOT(itemScaled(int)));
98     connect(itemrotate, SIGNAL(valueChanged(int)), this, SLOT(itemRotate(int)));
99     connect(itemhcenter, SIGNAL(clicked()), this, SLOT(itemHCenter()));
100     connect(itemvcenter, SIGNAL(clicked()), this, SLOT(itemVCenter()));
101
102     connect(origin_x_left, SIGNAL(clicked()), this, SLOT(slotOriginXClicked()));
103     connect(origin_y_top, SIGNAL(clicked()), this, SLOT(slotOriginYClicked()));
104
105     m_signalMapper = new QSignalMapper(this);
106     m_signalMapper->setMapping(value_w, ValueWidth);
107     m_signalMapper->setMapping(value_h, ValueHeight);
108     connect(value_w, SIGNAL(valueChanged(int)), m_signalMapper, SLOT(map()));
109     connect(value_h, SIGNAL(valueChanged(int)), m_signalMapper, SLOT(map()));
110     connect(m_signalMapper, SIGNAL(mapped(int)), this, SLOT(slotValueChanged(int)));
111
112     connect(value_x, SIGNAL(valueChanged(int)), this, SLOT(slotAdjustSelectedItem()));
113     connect(value_y, SIGNAL(valueChanged(int)), this, SLOT(slotAdjustSelectedItem()));
114     connect(value_w, SIGNAL(valueChanged(int)), this, SLOT(slotAdjustSelectedItem()));
115     connect(value_h, SIGNAL(valueChanged(int)), this, SLOT(slotAdjustSelectedItem()));
116     connect(buttonFitZoom, SIGNAL(clicked()), this, SLOT(slotAdjustZoom()));
117     connect(buttonRealSize, SIGNAL(clicked()), this, SLOT(slotZoomOneToOne()));
118     connect(buttonItalic, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
119     connect(buttonUnder, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
120     connect(buttonAlignLeft, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
121     connect(buttonAlignRight, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
122     connect(buttonAlignCenter, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
123     connect(buttonAlignNone, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
124     //connect(buttonInsertUnicode, SIGNAL(clicked()), this, SLOT(slotInsertUnicode()));
125     connect(displayBg, SIGNAL(stateChanged(int)), this, SLOT(displayBackgroundFrame()));
126
127     connect(m_unicodeDialog, SIGNAL(charSelected(QString)), this, SLOT(slotInsertUnicodeString(QString)));
128
129     // mbd
130     connect(this, SIGNAL(accepted()), this, SLOT(slotAccepted()));
131
132     font_weight_box->blockSignals(true);
133     font_weight_box->addItem(i18nc("Font style", "Light"), QFont::Light);
134     font_weight_box->addItem(i18nc("Font style", "Normal"), QFont::Normal);
135     font_weight_box->addItem(i18nc("Font style", "Demi-Bold"), QFont::DemiBold);
136     font_weight_box->addItem(i18nc("Font style", "Bold"), QFont::Bold);
137     font_weight_box->addItem(i18nc("Font style", "Black"), QFont::Black);
138     font_weight_box->setToolTip(i18n("Font weight"));
139     font_weight_box->setCurrentIndex(1);
140     font_weight_box->blockSignals(false);
141
142     buttonFitZoom->setIcon(KIcon("zoom-fit-best"));
143     buttonRealSize->setIcon(KIcon("zoom-original"));
144     buttonItalic->setIcon(KIcon("format-text-italic"));
145     buttonUnder->setIcon(KIcon("format-text-underline"));
146     buttonAlignCenter->setIcon(KIcon("format-justify-center"));
147     buttonAlignLeft->setIcon(KIcon("format-justify-left"));
148     buttonAlignRight->setIcon(KIcon("format-justify-right"));
149     buttonAlignNone->setIcon(KIcon("kdenlive-align-none"));
150
151     buttonAlignNone->setToolTip(i18n("No alignment"));
152     buttonAlignRight->setToolTip(i18n("Align right"));
153     buttonAlignLeft->setToolTip(i18n("Align left"));
154     buttonAlignCenter->setToolTip(i18n("Align center"));
155
156     m_unicodeAction = new QAction(KIcon("kdenlive-insert-unicode"), QString(), this);
157     m_unicodeAction->setShortcut(Qt::SHIFT + Qt::CTRL + Qt::Key_U);
158     m_unicodeAction->setToolTip(i18n("Insert Unicode character") + ' ' + m_unicodeAction->shortcut().toString());
159     connect(m_unicodeAction, SIGNAL(triggered()), this, SLOT(slotInsertUnicode()));
160     buttonInsertUnicode->setDefaultAction(m_unicodeAction);
161
162     origin_x_left->setToolTip(i18n("Invert x axis and change 0 point"));
163     origin_y_top->setToolTip(i18n("Invert y axis and change 0 point"));
164     rectBColor->setToolTip(i18n("Select fill color"));
165     rectFColor->setToolTip(i18n("Select border color"));
166     rectBAlpha->setToolTip(i18n("Fill transparency"));
167     rectFAlpha->setToolTip(i18n("Border transparency"));
168     zoom_slider->setToolTip(i18n("Zoom"));
169     buttonRealSize->setToolTip(i18n("Original size (1:1)"));
170     buttonFitZoom->setToolTip(i18n("Fit zoom"));
171     kcolorbutton->setToolTip(i18n("Select background color"));
172     horizontalSlider->setToolTip(i18n("Background Transparency"));
173
174     itemhcenter->setIcon(KIcon("kdenlive-align-hor"));
175     itemhcenter->setToolTip(i18n("Align item horizontally"));
176     itemvcenter->setIcon(KIcon("kdenlive-align-vert"));
177     itemvcenter->setToolTip(i18n("Align item vertically"));
178
179     QHBoxLayout *layout = new QHBoxLayout;
180     frame_toolbar->setLayout(layout);
181     layout->setContentsMargins(2, 2, 2, 2);
182     QToolBar *m_toolbar = new QToolBar("titleToolBar", this);
183
184     m_buttonCursor = m_toolbar->addAction(KIcon("transform-move"), QString());
185     m_buttonCursor->setCheckable(true);
186     m_buttonCursor->setShortcut(Qt::ALT + Qt::Key_S);
187     m_buttonCursor->setToolTip(i18n("Selection Tool") + ' ' + m_buttonCursor->shortcut().toString());
188     connect(m_buttonCursor, SIGNAL(triggered()), this, SLOT(slotSelectTool()));
189
190     m_buttonText = m_toolbar->addAction(KIcon("insert-text"), QString());
191     m_buttonText->setCheckable(true);
192     m_buttonText->setShortcut(Qt::ALT + Qt::Key_T);
193     m_buttonText->setToolTip(i18n("Add Text") + ' ' + m_buttonText->shortcut().toString());
194     connect(m_buttonText, SIGNAL(triggered()), this, SLOT(slotTextTool()));
195
196     m_buttonRect = m_toolbar->addAction(KIcon("kdenlive-insert-rect"), QString());
197     m_buttonRect->setCheckable(true);
198     m_buttonRect->setShortcut(Qt::ALT + Qt::Key_R);
199     m_buttonRect->setToolTip(i18n("Add Rectangle") + ' ' + m_buttonRect->shortcut().toString());
200     connect(m_buttonRect, SIGNAL(triggered()), this, SLOT(slotRectTool()));
201
202     m_buttonImage = m_toolbar->addAction(KIcon("insert-image"), QString());
203     m_buttonImage->setCheckable(false);
204     m_buttonImage->setShortcut(Qt::ALT + Qt::Key_I);
205     m_buttonImage->setToolTip(i18n("Add Image") + ' ' + m_buttonImage->shortcut().toString());
206     connect(m_buttonImage, SIGNAL(triggered()), this, SLOT(slotImageTool()));
207
208     m_toolbar->addSeparator();
209
210     m_buttonLoad = m_toolbar->addAction(KIcon("document-open"), i18n("Open Document"));
211     m_buttonLoad->setCheckable(false);
212     m_buttonLoad->setShortcut(Qt::CTRL + Qt::Key_O);
213     connect(m_buttonLoad, SIGNAL(triggered()), this, SLOT(loadTitle()));
214
215     m_buttonSave = m_toolbar->addAction(KIcon("document-save-as"), i18n("Save As"));
216     m_buttonSave->setCheckable(false);
217     m_buttonSave->setShortcut(Qt::CTRL + Qt::Key_S);
218     connect(m_buttonSave, SIGNAL(triggered()), this, SLOT(saveTitle()));
219
220     layout->addWidget(m_toolbar);
221
222     // initialize graphic scene
223     m_scene = new GraphicsSceneRectMove(this);
224     graphicsView->setScene(m_scene);
225     m_titledocument.setScene(m_scene, m_frameWidth, m_frameHeight);
226     connect(m_scene, SIGNAL(changed(QList<QRectF>)), this, SLOT(slotChanged()));
227
228     // a gradient background
229     /*QRadialGradient *gradient = new QRadialGradient(0, 0, 10);
230     gradient->setSpread(QGradient::ReflectSpread);
231     scene->setBackgroundBrush(*gradient);*/
232
233     m_frameImage = new QGraphicsPixmapItem();
234     QTransform qtrans;
235     qtrans.scale(2.0, 2.0);
236     m_frameImage->setTransform(qtrans);
237     m_frameImage->setZValue(-1200);
238     m_frameImage->setFlags(QGraphicsItem::ItemClipsToShape);
239     displayBackgroundFrame();
240     graphicsView->scene()->addItem(m_frameImage);
241
242     connect(m_scene, SIGNAL(selectionChanged()), this , SLOT(selectionChanged()));
243     connect(m_scene, SIGNAL(itemMoved()), this , SLOT(selectionChanged()));
244     connect(m_scene, SIGNAL(sceneZoom(bool)), this , SLOT(slotZoom(bool)));
245     connect(m_scene, SIGNAL(actionFinished()), this , SLOT(slotSelectTool()));
246     //connect(m_scene, SIGNAL(actionFinished()), this , SLOT(selectionChanged()));
247     connect(m_scene, SIGNAL(newRect(QGraphicsRectItem *)), this , SLOT(slotNewRect(QGraphicsRectItem *)));
248     connect(m_scene, SIGNAL(newText(QGraphicsTextItem *)), this , SLOT(slotNewText(QGraphicsTextItem *)));
249     connect(zoom_slider, SIGNAL(valueChanged(int)), this , SLOT(slotUpdateZoom(int)));
250
251     QPen framepen(Qt::DotLine);
252     framepen.setColor(Qt::red);
253
254     m_frameBorder = new QGraphicsRectItem(QRectF(0, 0, m_frameWidth, m_frameHeight));
255     m_frameBorder->setPen(framepen);
256     m_frameBorder->setZValue(-1100);
257     m_frameBorder->setBrush(Qt::transparent);
258     m_frameBorder->setFlags(QGraphicsItem::ItemClipsToShape);
259     graphicsView->scene()->addItem(m_frameBorder);
260
261     // mbd: load saved settings
262     readChoices();
263
264     initViewports();
265     graphicsView->show();
266     //graphicsView->setRenderHint(QPainter::Antialiasing);
267     graphicsView->setInteractive(true);
268     //graphicsView->resize(400, 300);
269     kDebug() << "// TITLE WIDGWT: " << graphicsView->viewport()->width() << "x" << graphicsView->viewport()->height();
270     //toolBox->setItemEnabled(2, false);
271     if (!url.isEmpty()) loadTitle(url);
272     else {
273         slotTextTool();
274         QTimer::singleShot(200, this, SLOT(slotAdjustZoom()));
275     }
276 }
277
278 TitleWidget::~TitleWidget()
279 {
280     delete m_buttonRect;
281     delete m_buttonText;
282     delete m_buttonImage;
283     delete m_buttonCursor;
284     delete m_buttonSave;
285     delete m_buttonLoad;
286     delete m_unicodeAction;
287
288     delete m_unicodeDialog;
289     delete m_frameBorder;
290     delete m_frameImage;
291     delete m_startViewport;
292     delete m_endViewport;
293     delete m_scene;
294     delete m_signalMapper;
295 }
296
297 //static
298 QStringList TitleWidget::getFreeTitleInfo(const KUrl &projectUrl, bool isClone)
299 {
300     QStringList result;
301     QString titlePath = projectUrl.path(KUrl::AddTrailingSlash) + "titles/";
302     KStandardDirs::makeDir(titlePath);
303     titlePath.append((isClone == false) ? "title" : "clone");
304     int counter = 0;
305     QString path;
306     while (path.isEmpty() || QFile::exists(path)) {
307         counter++;
308         path = titlePath + QString::number(counter).rightJustified(3, '0', false) + ".png";
309     }
310     result.append(((isClone == false) ? i18n("Title") : i18n("Clone")) + ' ' + QString::number(counter).rightJustified(3, '0', false));
311     result.append(path);
312     return result;
313 }
314
315 QString TitleWidget::getTitleResourceFromName(const KUrl &projectUrl, const QString &titleName)
316 {
317     QStringList result;
318     QString titlePath = projectUrl.path(KUrl::AddTrailingSlash) + "titles/";
319     KStandardDirs::makeDir(titlePath);
320     return titlePath + titleName + ".png";
321 }
322
323 //virtual
324 void TitleWidget::resizeEvent(QResizeEvent * /*event*/)
325 {
326     //slotAdjustZoom();
327 }
328
329 void TitleWidget::slotTextTool()
330 {
331     m_scene->setTool(TITLE_TEXT);
332     showToolbars(TITLE_TEXT);
333     checkButton(TITLE_TEXT);
334 }
335
336 void TitleWidget::slotRectTool()
337 {
338     m_scene->setTool(TITLE_RECTANGLE);
339     showToolbars(TITLE_RECTANGLE);
340     checkButton(TITLE_RECTANGLE);
341 }
342
343 void TitleWidget::slotSelectTool()
344 {
345     m_scene->setTool(TITLE_SELECT);
346
347     // Find out which toolbars need to be shown, depending on selected item
348     TITLETOOL t = TITLE_SELECT;
349     QList<QGraphicsItem *> l = graphicsView->scene()->selectedItems();
350     if (l.size() > 0) {
351         switch (l.at(0)->type()) {
352         case TEXTITEM:
353             t = TITLE_TEXT;
354             break;
355         case RECTITEM:
356             t = TITLE_RECTANGLE;
357             break;
358         case IMAGEITEM:
359             t = TITLE_IMAGE;
360             break;
361         }
362     }
363     enableToolbars(t);
364     showToolbars(t);
365
366     if (l.size() > 0) {
367         updateCoordinates(l.at(0));
368         updateDimension(l.at(0));
369         updateRotZoom(l.at(0));
370     }
371
372     checkButton(TITLE_SELECT);
373 }
374
375 void TitleWidget::slotImageTool()
376 {
377     KUrl url = KFileDialog::getOpenUrl(KUrl(), "*.svg *.png *.jpg *.jpeg *.gif *.raw", this, i18n("Load Image"));
378     if (!url.isEmpty()) {
379         if (url.path().endsWith(".svg")) {
380             QGraphicsSvgItem *svg = new QGraphicsSvgItem(url.toLocalFile());
381             svg->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
382             svg->setZValue(m_count++);
383             svg->setData(Qt::UserRole, url.path());
384             graphicsView->scene()->addItem(svg);
385         } else {
386             QPixmap pix(url.path());
387             QGraphicsPixmapItem *image = new QGraphicsPixmapItem(pix);
388             image->setShapeMode(QGraphicsPixmapItem::BoundingRectShape);
389             image->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
390             image->setData(Qt::UserRole, url.path());
391             image->setZValue(m_count++);
392             graphicsView->scene()->addItem(image);
393         }
394     }
395     m_scene->setTool(TITLE_SELECT);
396     showToolbars(TITLE_SELECT);
397     checkButton(TITLE_NONE);
398 }
399
400 void TitleWidget::showToolbars(TITLETOOL toolType)
401 {
402     switch (toolType) {
403     case TITLE_TEXT:
404         rect_properties->setHidden(true);
405         image_properties->setHidden(true);
406         no_properties->setHidden(true);
407         text_properties->setHidden(false);
408         break;
409     case TITLE_RECTANGLE:
410         image_properties->setHidden(true);
411         no_properties->setHidden(true);
412         text_properties->setHidden(true);
413         rect_properties->setHidden(false);
414         break;
415     case TITLE_IMAGE:
416         no_properties->setHidden(true);
417         text_properties->setHidden(true);
418         rect_properties->setHidden(true);
419         image_properties->setHidden(false);
420         break;
421     default:
422         text_properties->setHidden(true);
423         rect_properties->setHidden(true);
424         image_properties->setHidden(true);
425         no_properties->setHidden(false);
426         break;
427     }
428 }
429
430 void TitleWidget::enableToolbars(TITLETOOL toolType)
431 {
432     // TITLETOOL is defined in graphicsscenerectmove.h
433     bool bFrame = false;
434     bool bText = false;
435     bool bRect = false;
436     bool bImage = false;
437     bool bValue_w = false;
438     bool bValue_h = false;
439
440     switch (toolType) {
441     case TITLE_SELECT:
442         break;
443     case TITLE_TEXT:
444         bFrame = true;
445         bText = true;
446         break;
447     case TITLE_RECTANGLE:
448         bFrame = true;
449         bRect = true;
450         bValue_w = true;
451         bValue_h = true;
452         break;
453     case TITLE_IMAGE:
454         bFrame = true;
455         bValue_w = true;
456         bValue_h = true;
457         bImage = true;
458         break;
459     default:
460         break;
461     }
462     frame_properties->setEnabled(bFrame);
463     text_properties->setEnabled(bText);
464     rect_properties->setEnabled(bRect);
465     image_properties->setEnabled(bImage);
466     value_w->setEnabled(bValue_w);
467     value_h->setEnabled(bValue_h);
468 }
469
470 void TitleWidget::checkButton(TITLETOOL toolType)
471 {
472     bool bSelect = false;
473     bool bText = false;
474     bool bRect = false;
475     bool bImage = false;
476
477     switch (toolType) {
478     case TITLE_SELECT:
479         bSelect = true;
480         break;
481     case TITLE_TEXT:
482         bText = true;
483         break;
484     case TITLE_RECTANGLE:
485         bRect = true;
486         break;
487     case TITLE_IMAGE:
488         bImage = true;
489         break;
490     case TITLE_NONE:
491         break;
492     }
493
494     m_buttonCursor->setChecked(bSelect);
495     m_buttonText->setChecked(bText);
496     m_buttonRect->setChecked(bRect);
497     m_buttonImage->setChecked(bImage);
498 }
499
500 void TitleWidget::displayBackgroundFrame()
501 {
502     if (!displayBg->isChecked()) {
503         QPixmap bg(m_frameWidth / 2, m_frameHeight / 2);
504         QPixmap pattern(20, 20);
505         pattern.fill();
506         QPainter p;
507         p.begin(&pattern);
508         p.fillRect(QRect(0, 0, 10, 10), QColor(210, 210, 210));
509         p.fillRect(QRect(10, 10, 20, 20), QColor(210, 210, 210));
510         p.end();
511         QBrush br(pattern);
512
513         p.begin(&bg);
514         p.fillRect(bg.rect(), br);
515         p.end();
516         m_frameImage->setPixmap(bg);
517     } else {
518         m_frameImage->setPixmap(m_render->extractFrame((int) m_render->seekPosition().frames(m_render->fps()), m_frameWidth / 2, m_frameHeight / 2));
519     }
520 }
521
522 void TitleWidget::initViewports()
523 {
524     m_startViewport = new QGraphicsPolygonItem(QPolygonF(QRectF(0, 0, 0, 0)));
525     m_endViewport = new QGraphicsPolygonItem(QPolygonF(QRectF(0, 0, 0, 0)));
526
527     QPen startpen(Qt::DotLine);
528     QPen endpen(Qt::DashDotLine);
529     startpen.setColor(QColor(100, 200, 100, 140));
530     endpen.setColor(QColor(200, 100, 100, 140));
531
532     m_startViewport->setPen(startpen);
533     m_endViewport->setPen(endpen);
534
535     startViewportSize->setValue(100);
536     endViewportSize->setValue(100);
537
538     m_startViewport->setZValue(-1000);
539     m_endViewport->setZValue(-1000);
540
541     m_startViewport->setFlags(/*QGraphicsItem::ItemIsMovable|*/QGraphicsItem::ItemIsSelectable);
542     m_endViewport->setFlags(/*QGraphicsItem::ItemIsMovable|*/QGraphicsItem::ItemIsSelectable);
543
544     graphicsView->scene()->addItem(m_startViewport);
545     graphicsView->scene()->addItem(m_endViewport);
546 }
547
548 void TitleWidget::slotUpdateZoom(int pos)
549 {
550     m_scene->setZoom((double) pos / 100);
551     zoom_label->setText(QString::number(pos) + '%');
552 }
553
554 void TitleWidget::slotZoom(bool up)
555 {
556     int pos = zoom_slider->value();
557     if (up) pos++;
558     else pos--;
559     zoom_slider->setValue(pos);
560 }
561
562 void TitleWidget::slotAdjustZoom()
563 {
564     /*double scalex = graphicsView->width() / (double)(m_frameWidth * 1.2);
565     double scaley = graphicsView->height() / (double)(m_frameHeight * 1.2);
566     if (scalex > scaley) scalex = scaley;
567     int zoompos = (int)(scalex * 7 + 0.5);*/
568     graphicsView->fitInView(m_frameBorder, Qt::KeepAspectRatio);
569     int zoompos = graphicsView->matrix().m11() * 100;
570     zoom_slider->setValue(zoompos);
571     graphicsView->centerOn(m_frameBorder);
572 }
573
574 void TitleWidget::slotZoomOneToOne()
575 {
576     zoom_slider->setValue(100);
577     graphicsView->centerOn(m_frameBorder);
578 }
579
580 void TitleWidget::slotNewRect(QGraphicsRectItem * rect)
581 {
582     updateAxisButtons(rect); // back to default
583
584     QColor f = rectFColor->color();
585     f.setAlpha(rectFAlpha->value());
586     QPen penf(f);
587     penf.setWidth(rectLineWidth->value());
588     rect->setPen(penf);
589     QColor b = rectBColor->color();
590     b.setAlpha(rectBAlpha->value());
591     rect->setBrush(QBrush(b));
592     rect->setZValue(m_count++);
593     //setCurrentItem(rect);
594     //graphicsView->setFocus();
595 }
596
597 void TitleWidget::slotNewText(QGraphicsTextItem *tt)
598 {
599     updateAxisButtons(tt); // back to default
600
601     QFont font = font_family->currentFont();
602     font.setPixelSize(font_size->value());
603     // mbd: issue 551:
604     font.setWeight(font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
605     font.setItalic(buttonItalic->isChecked());
606     font.setUnderline(buttonUnder->isChecked());
607
608     tt->setFont(font);
609     QColor color = fontColorButton->color();
610     color.setAlpha(textAlpha->value());
611     tt->setDefaultTextColor(color);
612     tt->setZValue(m_count++);
613     setCurrentItem(tt);
614 }
615
616 void TitleWidget::setFontBoxWeight(int weight)
617 {
618     int index = font_weight_box->findData(weight);
619     if (index < 0) {
620         index = font_weight_box->findData(QFont::Normal);
621     }
622     font_weight_box->setCurrentIndex(index);
623 }
624
625 void TitleWidget::setCurrentItem(QGraphicsItem *item)
626 {
627     m_scene->setSelectedItem(item);
628 }
629
630 void TitleWidget::zIndexChanged(int v)
631 {
632     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
633     if (l.size() >= 1) {
634         l[0]->setZValue(v);
635     }
636 }
637
638 void TitleWidget::selectionChanged()
639 {
640     if (m_scene->tool() != TITLE_SELECT) return;
641     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
642     //toolBox->setItemEnabled(2, false);
643     //toolBox->setItemEnabled(3, false);
644     value_x->blockSignals(true);
645     value_y->blockSignals(true);
646     value_w->blockSignals(true);
647     value_h->blockSignals(true);
648     itemzoom->blockSignals(true);
649     itemrotate->blockSignals(true);
650     if (l.size() == 0) {
651         bool blockX = !origin_x_left->signalsBlocked();
652         bool blockY = !origin_y_top->signalsBlocked();
653         if (blockX) origin_x_left->blockSignals(true);
654         if (blockY) origin_y_top->blockSignals(true);
655         origin_x_left->setChecked(false);
656         origin_y_top->setChecked(false);
657         updateTextOriginX();
658         updateTextOriginY();
659         enableToolbars(TITLE_NONE);
660         if (blockX) origin_x_left->blockSignals(false);
661         if (blockY) origin_y_top->blockSignals(false);
662     } else if (l.size() == 1) {
663         if (l.at(0)->type() == TEXTITEM) {
664             showToolbars(TITLE_TEXT);
665             QGraphicsTextItem* i = static_cast <QGraphicsTextItem *>(l.at(0));
666             //if (l[0]->hasFocus())
667             toolBox->setCurrentIndex(0);
668             //toolBox->setItemEnabled(2, true);
669             font_size->blockSignals(true);
670             font_family->blockSignals(true);
671             font_weight_box->blockSignals(true);
672             buttonItalic->blockSignals(true);
673             buttonUnder->blockSignals(true);
674             fontColorButton->blockSignals(true);
675             textAlpha->blockSignals(true);
676             buttonAlignLeft->blockSignals(true);
677             buttonAlignRight->blockSignals(true);
678             buttonAlignNone->blockSignals(true);
679             buttonAlignCenter->blockSignals(true);
680
681             QFont font = i->font();
682             font_family->setCurrentFont(font);
683             font_size->setValue(font.pixelSize());
684             buttonItalic->setChecked(font.italic());
685             buttonUnder->setChecked(font.underline());
686             setFontBoxWeight(font.weight());
687
688             QColor color = i->defaultTextColor();
689             fontColorButton->setColor(color);
690             textAlpha->setValue(color.alpha());
691
692             QTextCursor cur = i->textCursor();
693             QTextBlockFormat format = cur.blockFormat();
694             if (i->textWidth() == -1) buttonAlignNone->setChecked(true);
695             else if (format.alignment() == Qt::AlignHCenter) buttonAlignCenter->setChecked(true);
696             else if (format.alignment() == Qt::AlignRight) buttonAlignRight->setChecked(true);
697             else if (format.alignment() == Qt::AlignLeft) buttonAlignLeft->setChecked(true);
698
699             font_size->blockSignals(false);
700             font_family->blockSignals(false);
701             font_weight_box->blockSignals(false);
702             buttonItalic->blockSignals(false);
703             buttonUnder->blockSignals(false);
704             fontColorButton->blockSignals(false);
705             textAlpha->blockSignals(false);
706             buttonAlignLeft->blockSignals(false);
707             buttonAlignRight->blockSignals(false);
708             buttonAlignNone->blockSignals(false);
709             buttonAlignCenter->blockSignals(false);
710
711             updateAxisButtons(i);
712             updateCoordinates(i);
713             updateDimension(i);
714             enableToolbars(TITLE_TEXT);
715
716         } else if ((l.at(0))->type() == RECTITEM) {
717             showToolbars(TITLE_RECTANGLE);
718             settingUp = true;
719             QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(l.at(0));
720             toolBox->setCurrentIndex(0);
721             //toolBox->setItemEnabled(3, true);
722             rectFAlpha->setValue(rec->pen().color().alpha());
723             rectBAlpha->setValue(rec->brush().color().alpha());
724             //kDebug() << rec->brush().color().alpha();
725             QColor fcol = rec->pen().color();
726             QColor bcol = rec->brush().color();
727             //fcol.setAlpha(255);
728             //bcol.setAlpha(255);
729             rectFColor->setColor(fcol);
730             rectBColor->setColor(bcol);
731             settingUp = false;
732             rectLineWidth->setValue(rec->pen().width());
733
734             updateAxisButtons(l.at(0));
735             updateCoordinates(rec);
736             updateDimension(rec);
737             enableToolbars(TITLE_RECTANGLE);
738
739         } else if (l.at(0)->type() == IMAGEITEM) {
740             showToolbars(TITLE_IMAGE);
741
742             updateCoordinates(l.at(0));
743             updateDimension(l.at(0));
744
745             enableToolbars(TITLE_IMAGE);
746
747         } else {
748             //toolBox->setCurrentIndex(0);
749             showToolbars(TITLE_NONE);
750             enableToolbars(TITLE_NONE);
751             /*frame_properties->setEnabled(false);
752             text_properties->setEnabled(false);
753             rect_properties->setEnabled(false);*/
754         }
755         zValue->setValue((int)l.at(0)->zValue());
756         itemzoom->setValue((int)(m_transformations.value(l.at(0)).scalex * 100.0 + 0.5));
757         itemrotate->setValue((int)(m_transformations.value(l.at(0)).rotate));
758         value_x->blockSignals(false);
759         value_y->blockSignals(false);
760         value_w->blockSignals(false);
761         value_h->blockSignals(false);
762         itemzoom->blockSignals(false);
763         itemrotate->blockSignals(false);
764     }
765 }
766
767 void TitleWidget::slotValueChanged(int type)
768 {
769     QList<QGraphicsItem *> l = graphicsView->scene()->selectedItems();
770     if (l.size() > 0 && l.at(0)->type() == IMAGEITEM) {
771
772         int val = 0;
773         switch (type) {
774         case ValueWidth:
775             val = value_w->value();
776             break;
777         case ValueHeight:
778             val = value_h->value();
779             break;
780         }
781
782         QGraphicsItem *i = l.at(0);
783         Transform t = m_transformations.value(i);
784
785         // Ratio width:height
786         double phi = (double) i->boundingRect().width() / i->boundingRect().height();
787         double alpha = (double) t.rotate / 180.0 * M_PI;
788
789         // New length
790         double length = val;
791
792         // Scaling factor
793         double scale = 1;
794
795         switch (type) {
796         case ValueWidth:
797             // Add 0.5 because otherwise incrementing by 1 might have no effect
798             length = val / (cos(alpha) + 1 / phi * sin(alpha)) + 0.5;
799             scale = length / i->boundingRect().width();
800             break;
801         case ValueHeight:
802             length = val / (phi * sin(alpha) + cos(alpha)) + 0.5;
803             scale = length / i->boundingRect().height();
804             break;
805         }
806
807         t.scalex = scale;
808         t.scaley = scale;
809         QTransform qtrans;
810         qtrans.scale(scale, scale);
811         qtrans.rotate(t.rotate);
812         i->setTransform(qtrans);
813         m_transformations[i] = t;
814
815         updateDimension(i);
816         updateRotZoom(i);
817     }
818 }
819
820 /** \brief Updates position/size of the selected item when a value
821  * of an item (coordinates, size) has changed */
822 void TitleWidget::slotAdjustSelectedItem()
823 {
824     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
825     if (l.size() >= 1) {
826         if (l.at(0)->type() == RECTITEM) {
827             //rect item
828             QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(l.at(0));
829             updatePosition(rec);
830             rec->setRect(QRect(0, 0, value_w->value(), value_h->value()));
831         } else if (l.at(0)->type() == TEXTITEM) {
832             //text item
833             updatePosition(l.at(0));
834         } else if (l.at(0)->type() == IMAGEITEM) {
835             //image item
836             updatePosition(l.at(0));
837         }
838     }
839 }
840
841 /** \brief Updates width/height int the text fields, regarding transformation matrix */
842 void TitleWidget::updateDimension(QGraphicsItem *i)
843 {
844     value_w->blockSignals(true);
845     value_h->blockSignals(true);
846
847
848     if (i->type() == IMAGEITEM) {
849         // Get multipliers for rotation/scaling
850
851         /*Transform t = m_transformations.value(i);
852         QRectF r = i->boundingRect();
853         int width = (int) ( abs(r.width()*t.scalex * cos(t.rotate/180.0*M_PI))
854                     + abs(r.height()*t.scaley * sin(t.rotate/180.0*M_PI)) );
855         int height = (int) ( abs(r.height()*t.scaley * cos(t.rotate/180*M_PI))
856                     + abs(r.width()*t.scalex * sin(t.rotate/180*M_PI)) );*/
857
858         value_w->setValue(i->sceneBoundingRect().width());
859         value_h->setValue(i->sceneBoundingRect().height());
860     } else if (i->type() == RECTITEM) {
861         QGraphicsRectItem *r = static_cast <QGraphicsRectItem *>(i);
862         value_w->setValue((int) r->rect().width());
863         value_h->setValue((int) r->rect().height());
864     } else if (i->type() == TEXTITEM) {
865         QGraphicsTextItem *t = static_cast <QGraphicsTextItem *>(i);
866         value_w->setValue((int) t->boundingRect().width());
867         value_h->setValue((int) t->boundingRect().height());
868     }
869
870     value_w->blockSignals(false);
871     value_h->blockSignals(false);
872 }
873
874 /** \brief Updates the coordinates in the text fields from the item */
875 void TitleWidget::updateCoordinates(QGraphicsItem *i)
876 {
877     // Block signals emitted by this method
878     value_x->blockSignals(true);
879     value_y->blockSignals(true);
880
881     if (i->type() == TEXTITEM) {
882
883         QGraphicsTextItem *rec = static_cast <QGraphicsTextItem *>(i);
884
885         // Set the correct x coordinate value
886         if (origin_x_left->isChecked()) {
887             // Origin (0 point) is at m_frameWidth, coordinate axis is inverted
888             value_x->setValue((int)(m_frameWidth - rec->pos().x() - rec->boundingRect().width()));
889         } else {
890             // Origin is at 0 (default)
891             value_x->setValue((int) rec->pos().x());
892         }
893
894         // Same for y
895         if (origin_y_top->isChecked()) {
896             value_y->setValue((int)(m_frameHeight - rec->pos().y() - rec->boundingRect().height()));
897         } else {
898             value_y->setValue((int) rec->pos().y());
899         }
900
901     } else if (i->type() == RECTITEM) {
902
903         QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(i);
904
905         if (origin_x_left->isChecked()) {
906             // Origin (0 point) is at m_frameWidth
907             value_x->setValue((int)(m_frameWidth - rec->pos().x() - rec->rect().width()));
908         } else {
909             // Origin is at 0 (default)
910             value_x->setValue((int) rec->pos().x());
911         }
912
913         if (origin_y_top->isChecked()) {
914             value_y->setValue((int)(m_frameHeight - rec->pos().y() - rec->rect().height()));
915         } else {
916             value_y->setValue((int) rec->pos().y());
917         }
918
919     } else if (i->type() == IMAGEITEM) {
920
921         if (origin_x_left->isChecked()) {
922             value_x->setValue((int)(m_frameWidth - i->pos().x() - i->sceneBoundingRect().width()));
923         } else {
924             value_x->setValue((int) i->pos().x());
925         }
926
927         if (origin_y_top->isChecked()) {
928             value_y->setValue((int)(m_frameHeight - i->pos().y() - i->sceneBoundingRect().height()));
929         } else {
930             value_y->setValue((int) i->pos().y());
931         }
932
933     }
934
935     // Stop blocking signals now
936     value_x->blockSignals(false);
937     value_y->blockSignals(false);
938 }
939
940 void TitleWidget::updateRotZoom(QGraphicsItem *i)
941 {
942     itemzoom->blockSignals(true);
943     itemrotate->blockSignals(false);
944
945     Transform t = m_transformations.value(i);
946     itemzoom->setValue((int)(t.scalex * 100.0 + 0.5));
947     itemrotate->setValue((int)(t.rotate));
948
949     itemzoom->blockSignals(false);
950     itemrotate->blockSignals(false);
951 }
952
953 /** \brief Updates the position of an item by reading coordinates from the text fields */
954 void TitleWidget::updatePosition(QGraphicsItem *i)
955 {
956     if (i->type() == TEXTITEM) {
957         QGraphicsTextItem *rec = static_cast <QGraphicsTextItem *>(i);
958
959         int posX;
960         if (origin_x_left->isChecked()) {
961             /* Origin of the x axis is at m_frameWidth,
962              * and distance from right border of the item to the right
963              * border of the frame is taken.
964              * See comment to slotOriginXClicked().
965              */
966             posX = m_frameWidth - value_x->value() - rec->boundingRect().width();
967         } else {
968             posX = value_x->value();
969         }
970
971         int posY;
972         if (origin_y_top->isChecked()) {
973             /* Same for y axis */
974             posY = m_frameHeight - value_y->value() - rec->boundingRect().height();
975         } else {
976             posY = value_y->value();
977         }
978
979         rec->setPos(posX, posY);
980
981     } else if (i->type() == RECTITEM) {
982
983         QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(i);
984
985         int posX;
986         if (origin_x_left->isChecked()) {
987             posX = m_frameWidth - value_x->value() - rec->rect().width();
988         } else {
989             posX = value_x->value();
990         }
991
992         int posY;
993         if (origin_y_top->isChecked()) {
994             posY = m_frameHeight - value_y->value() - rec->rect().height();
995         } else {
996             posY = value_y->value();
997         }
998
999         rec->setPos(posX, posY);
1000
1001     } else if (i->type() == IMAGEITEM) {
1002         int posX;
1003         if (origin_x_left->isChecked()) {
1004             // Use the sceneBoundingRect because this also regards transformations like zoom
1005             posX = m_frameWidth - value_x->value() - i->sceneBoundingRect().width();
1006         } else {
1007             posX = value_x->value();
1008         }
1009
1010         int posY;
1011         if (origin_y_top->isChecked()) {
1012             posY = m_frameHeight - value_y->value() - i->sceneBoundingRect().height();
1013         } else {
1014             posY = value_y->value();
1015         }
1016
1017         i->setPos(posX, posY);
1018
1019     }
1020
1021 }
1022
1023 void TitleWidget::updateTextOriginX()
1024 {
1025     if (origin_x_left->isChecked()) {
1026         origin_x_left->setText(i18n("\u2212X"));
1027     } else {
1028         origin_x_left->setText(i18n("+X"));
1029     }
1030 }
1031
1032 void TitleWidget::slotOriginXClicked()
1033 {
1034     // Update the text displayed on the button.
1035     updateTextOriginX();
1036
1037     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1038     if (l.size() >= 1) {
1039         updateCoordinates(l.at(0));
1040
1041         // Remember x axis setting
1042         l.at(0)->setData(TitleDocument::OriginXLeft, origin_x_left->isChecked() ?
1043                          TitleDocument::AxisInverted : TitleDocument::AxisDefault);
1044     }
1045     graphicsView->setFocus();
1046 }
1047
1048 void TitleWidget::updateTextOriginY()
1049 {
1050     if (origin_y_top->isChecked()) {
1051         origin_y_top->setText(i18n("\u2212Y"));
1052     } else {
1053         origin_y_top->setText(i18n("+Y"));
1054     }
1055 }
1056
1057 void TitleWidget::slotOriginYClicked()
1058 {
1059     // Update the text displayed on the button.
1060     updateTextOriginY();
1061
1062     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1063     if (l.size() >= 1) {
1064         updateCoordinates(l.at(0));
1065
1066         l.at(0)->setData(TitleDocument::OriginYTop, origin_y_top->isChecked() ?
1067                          TitleDocument::AxisInverted : TitleDocument::AxisDefault);
1068
1069     }
1070     graphicsView->setFocus();
1071 }
1072
1073 void TitleWidget::updateAxisButtons(QGraphicsItem *i)
1074 {
1075     int xAxis = i->data(TitleDocument::OriginXLeft).toInt();
1076     int yAxis = i->data(TitleDocument::OriginYTop).toInt();
1077     origin_x_left->blockSignals(true);
1078     origin_y_top->blockSignals(true);
1079
1080     if (xAxis == TitleDocument::AxisInverted) {
1081         origin_x_left->setChecked(true);
1082     } else {
1083         origin_x_left->setChecked(false);
1084     }
1085     updateTextOriginX();
1086
1087     if (yAxis == TitleDocument::AxisInverted) {
1088         origin_y_top->setChecked(true);
1089     } else {
1090         origin_y_top->setChecked(false);
1091     }
1092     updateTextOriginY();
1093
1094     origin_x_left->blockSignals(false);
1095     origin_y_top->blockSignals(false);
1096 }
1097
1098 void TitleWidget::slotChangeBackground()
1099 {
1100     QColor color = kcolorbutton->color();
1101     color.setAlpha(horizontalSlider->value());
1102     m_frameBorder->setBrush(QBrush(color));
1103 }
1104
1105 /**
1106  * Something (yeah) has changed in our QGraphicsScene.
1107  */
1108 void TitleWidget::slotChanged()
1109 {
1110     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1111     if (l.size() >= 1 && l.at(0)->type() == TEXTITEM) {
1112         textChanged(static_cast <QGraphicsTextItem *>(l.at(0)));
1113     }
1114 }
1115
1116 /**
1117  * If the user has set origin_x_left (everything also for y),
1118  * we need to look whether a text element has been selected. If yes,
1119  * we need to ensure that the right border of the text field
1120  * remains fixed also when some text has been entered.
1121  *
1122  * This is also known as right-justified, with the difference that
1123  * it is not valid for text but for its boundingRect. Text may still
1124  * be left-justified.
1125  */
1126 void TitleWidget::textChanged(QGraphicsTextItem *i)
1127 {
1128
1129     updateDimension(i);
1130
1131     if (origin_x_left->isChecked() || origin_y_top->isChecked()) {
1132
1133         if (!i->toPlainText().isEmpty()) {
1134             updatePosition(i);
1135         } else {
1136             /*
1137              * Don't do anything if the string is empty. If the position
1138              * would be updated here, a newly created text field would
1139              * be set to the position of the last selected text field.
1140              */
1141         }
1142     }
1143 }
1144
1145 void TitleWidget::slotInsertUnicode()
1146 {
1147     m_unicodeDialog->exec();
1148 }
1149
1150 void TitleWidget::slotInsertUnicodeString(QString text)
1151 {
1152     QList<QGraphicsItem *> l = graphicsView->scene()->selectedItems();
1153     if (l.size() > 0) {
1154         if (l.at(0)->type() == TEXTITEM) {
1155             QGraphicsTextItem *t = static_cast <QGraphicsTextItem *>(l.at(0));
1156             t->textCursor().insertText(text);
1157         }
1158     }
1159 }
1160
1161 void TitleWidget::slotUpdateText()
1162 {
1163     QFont font = font_family->currentFont();
1164     font.setPixelSize(font_size->value());
1165     font.setItalic(buttonItalic->isChecked());
1166     font.setUnderline(buttonUnder->isChecked());
1167     font.setWeight(font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
1168     QColor color = fontColorButton->color();
1169     color.setAlpha(textAlpha->value());
1170
1171     QGraphicsTextItem* item = NULL;
1172     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1173     if (l.size() == 1 && l.at(0)->type() == TEXTITEM) {
1174         item = static_cast <QGraphicsTextItem *>(l.at(0));
1175     }
1176     if (!item) return;
1177     //if (item->textCursor().selection ().isEmpty())
1178     QTextCursor cur = item->textCursor();
1179     QTextBlockFormat format = cur.blockFormat();
1180     if (buttonAlignLeft->isChecked() || buttonAlignCenter->isChecked() || buttonAlignRight->isChecked()) {
1181         item->setTextWidth(item->boundingRect().width());
1182         if (buttonAlignCenter->isChecked()) format.setAlignment(Qt::AlignHCenter);
1183         else if (buttonAlignRight->isChecked()) format.setAlignment(Qt::AlignRight);
1184         else if (buttonAlignLeft->isChecked()) format.setAlignment(Qt::AlignLeft);
1185     } else {
1186         format.setAlignment(Qt::AlignLeft);
1187         item->setTextWidth(-1);
1188     }
1189
1190     {
1191         item->setFont(font);
1192         item->setDefaultTextColor(color);
1193         cur.select(QTextCursor::Document);
1194         cur.setBlockFormat(format);
1195         item->setTextCursor(cur);
1196         cur.clearSelection();
1197         item->setTextCursor(cur);
1198
1199     }
1200 }
1201
1202 void TitleWidget::rectChanged()
1203 {
1204     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1205     if (l.size() == 1 && l.at(0)->type() == RECTITEM && !settingUp) {
1206         QGraphicsRectItem *rec = static_cast<QGraphicsRectItem *>(l.at(0));
1207         QColor f = rectFColor->color();
1208         f.setAlpha(rectFAlpha->value());
1209         QPen penf(f);
1210         penf.setWidth(rectLineWidth->value());
1211         rec->setPen(penf);
1212         QColor b = rectBColor->color();
1213         b.setAlpha(rectBAlpha->value());
1214         rec->setBrush(QBrush(b));
1215     }
1216 }
1217
1218 void TitleWidget::itemScaled(int val)
1219 {
1220     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1221     if (l.size() == 1) {
1222         Transform x = m_transformations.value(l.at(0));
1223         x.scalex = (double)val / 100.0;
1224         x.scaley = (double)val / 100.0;
1225         QTransform qtrans;
1226         qtrans.scale(x.scalex, x.scaley);
1227         qtrans.rotate(x.rotate);
1228         l[0]->setTransform(qtrans);
1229         m_transformations[l.at(0)] = x;
1230         updateDimension(l.at(0));
1231     }
1232 }
1233
1234 void TitleWidget::itemRotate(int val)
1235 {
1236     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1237     if (l.size() == 1) {
1238         Transform x = m_transformations[l.at(0)];
1239         x.rotate = (double)val;
1240         QTransform qtrans;
1241         qtrans.scale(x.scalex, x.scaley);
1242         qtrans.rotate(x.rotate);
1243         l[0]->setTransform(qtrans);
1244         m_transformations[l.at(0)] = x;
1245         updateDimension(l.at(0));
1246     }
1247 }
1248
1249 void TitleWidget::itemHCenter()
1250 {
1251     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1252     if (l.size() == 1) {
1253         QGraphicsItem *item = l.at(0);
1254         QRectF br;
1255         br = item->sceneBoundingRect();
1256         int width = (int)br.width();
1257         int newPos = (int)((m_frameWidth - width) / 2);
1258         newPos += item->pos().x() - br.left(); // Check item transformation
1259         item->setPos(newPos, item->pos().y());
1260         updateCoordinates(item);
1261     }
1262 }
1263
1264 void TitleWidget::itemVCenter()
1265 {
1266     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1267     if (l.size() == 1) {
1268         QGraphicsItem *item = l.at(0);
1269         QRectF br;
1270         br = item->sceneBoundingRect();
1271         int height = (int)br.height();
1272         int newPos = (int)((m_frameHeight - height) / 2);
1273         newPos += item->pos().y() - br.top(); // Check item transformation
1274         item->setPos(item->pos().x(), newPos);
1275         updateCoordinates(item);
1276     }
1277 }
1278
1279 void TitleWidget::setupViewports()
1280 {
1281     //double aspect_ratio = 4.0 / 3.0;//read from project
1282     //better zoom centered, but render uses only the created rect, so no problem to change the zoom function
1283     QRectF sp(0, 0, startViewportSize->value() * m_frameWidth / 100.0 , startViewportSize->value()* m_frameHeight / 100.0);
1284     QRectF ep(0, 0, endViewportSize->value() * m_frameWidth / 100.0, endViewportSize->value() * m_frameHeight / 100.0);
1285     // use a polygon thiat uses 16:9 and 4:3 rects forpreview the size in all aspect ratios ?
1286     QPolygonF spoly(sp);
1287     QPolygonF epoly(ep);
1288     spoly.translate(startViewportX->value(), startViewportY->value());
1289     epoly.translate(endViewportX->value(), endViewportY->value());
1290     m_startViewport->setPolygon(spoly);
1291     m_endViewport->setPolygon(epoly);
1292     if (! insertingValues) {
1293         m_startViewport->setData(0, startViewportX->value());
1294         m_startViewport->setData(1, startViewportY->value());
1295         m_startViewport->setData(2, startViewportSize->value());
1296
1297         m_endViewport->setData(0, endViewportX->value());
1298         m_endViewport->setData(1, endViewportY->value());
1299         m_endViewport->setData(2, endViewportSize->value());
1300     }
1301 }
1302
1303 void TitleWidget::loadTitle(KUrl url)
1304 {
1305     if (url.isEmpty()) url = KFileDialog::getOpenUrl(KUrl(m_projectTitlePath), "application/x-kdenlivetitle", this, i18n("Load Title"));
1306     if (!url.isEmpty()) {
1307         QList<QGraphicsItem *> items = m_scene->items();
1308         for (int i = 0; i < items.size(); i++) {
1309             if (items.at(i)->zValue() > -1000) delete items.at(i);
1310         }
1311         m_scene->clearTextSelection();
1312         QDomDocument doc;
1313         QString tmpfile;
1314
1315         if (KIO::NetAccess::download(url, tmpfile, 0)) {
1316             QFile file(tmpfile);
1317             if (file.open(QIODevice::ReadOnly)) {
1318                 doc.setContent(&file, false);
1319                 file.close();
1320             } else return;
1321             KIO::NetAccess::removeTempFile(tmpfile);
1322         }
1323         setXml(doc);
1324         /*int out;
1325         m_count = m_titledocument.loadDocument(url, m_startViewport, m_endViewport, &out) + 1;
1326         adjustFrameSize();
1327         title_duration->setText(m_tc.getTimecode(GenTime(out, m_render->fps())));
1328         insertingValues = true;
1329         startViewportX->setValue(m_startViewport->data(0).toInt());
1330         startViewportY->setValue(m_startViewport->data(1).toInt());
1331         startViewportSize->setValue(m_startViewport->data(2).toInt());
1332         endViewportX->setValue(m_endViewport->data(0).toInt());
1333         endViewportY->setValue(m_endViewport->data(1).toInt());
1334         endViewportSize->setValue(m_endViewport->data(2).toInt());
1335
1336         insertingValues = false;
1337         slotSelectTool();
1338         slotAdjustZoom();*/
1339     }
1340 }
1341
1342 void TitleWidget::saveTitle(KUrl url)
1343 {
1344     if (url.isEmpty()) url = KFileDialog::getSaveUrl(KUrl(m_projectTitlePath), "application/x-kdenlivetitle", this, i18n("Save Title"));
1345     if (!url.isEmpty()) {
1346         if (m_titledocument.saveDocument(url, m_startViewport, m_endViewport, m_tc.getFrameCount(title_duration->text())) == false)
1347             KMessageBox::error(this, i18n("Cannot write to file %1", url.path()));
1348     }
1349 }
1350
1351 QDomDocument TitleWidget::xml()
1352 {
1353     QDomDocument doc = m_titledocument.xml(m_startViewport, m_endViewport);
1354     doc.documentElement().setAttribute("out", m_tc.getFrameCount(title_duration->text()));
1355     if (cropImage->isChecked()) {
1356         doc.documentElement().setAttribute("crop", 1);
1357     }
1358     return doc;
1359 }
1360
1361 int TitleWidget::duration() const
1362 {
1363     return m_tc.getFrameCount(title_duration->text());
1364 }
1365
1366 void TitleWidget::setXml(QDomDocument doc)
1367 {
1368     int out;
1369     m_count = m_titledocument.loadFromXml(doc, m_startViewport, m_endViewport, &out);
1370     adjustFrameSize();
1371     title_duration->setText(m_tc.getTimecode(GenTime(out, m_render->fps())));
1372     /*if (doc.documentElement().hasAttribute("out")) {
1373     GenTime duration = GenTime(doc.documentElement().attribute("out").toDouble() / 1000.0);
1374     title_duration->setText(m_tc.getTimecode(duration));
1375     }
1376     else title_duration->setText(m_tc.getTimecode(GenTime(5000)));*/
1377
1378     QDomElement e = doc.documentElement();
1379     cropImage->setChecked(e.hasAttribute("crop"));
1380     m_transformations.clear();
1381     QList <QGraphicsItem *> items = graphicsView->scene()->items();
1382     const double PI = 4.0 * atan(1.0);
1383     for (int i = 0; i < items.count(); i++) {
1384         QTransform t = items.at(i)->transform();
1385         Transform x;
1386         x.scalex = t.m11();
1387         x.scaley = t.m22();
1388         x.rotate = 180. / PI * atan2(-t.m21(), t.m11());
1389         m_transformations[items.at(i)] = x;
1390     }
1391     // mbd: Update the GUI color selectors to match the stuff from the loaded document
1392     QColor background_color = m_titledocument.getBackgroundColor();
1393     horizontalSlider->blockSignals(true);
1394     kcolorbutton->blockSignals(true);
1395     horizontalSlider->setValue(background_color.alpha());
1396     background_color.setAlpha(255);
1397     kcolorbutton->setColor(background_color);
1398     horizontalSlider->blockSignals(false);
1399     kcolorbutton->blockSignals(false);
1400
1401     startViewportX->setValue(m_startViewport->data(0).toInt());
1402     startViewportY->setValue(m_startViewport->data(1).toInt());
1403     startViewportSize->setValue(m_startViewport->data(2).toInt());
1404     endViewportX->setValue(m_endViewport->data(0).toInt());
1405     endViewportY->setValue(m_endViewport->data(1).toInt());
1406     endViewportSize->setValue(m_endViewport->data(2).toInt());
1407
1408     QTimer::singleShot(200, this, SLOT(slotAdjustZoom()));
1409     slotSelectTool();
1410 }
1411
1412 const QRect TitleWidget::renderedRect()
1413 {
1414     int minX = 0;
1415     int minY = 0;
1416     int maxX = m_frameWidth;
1417     int maxY = m_frameHeight;
1418     if (!cropImage->isChecked()) {
1419         m_scene->removeItem(m_startViewport);
1420         m_scene->removeItem(m_endViewport);
1421         QRect boundingRect = m_scene->itemsBoundingRect().toRect();
1422         if (boundingRect.left() < 0) minX = boundingRect.left();
1423         if (boundingRect.top() < 0) minY = boundingRect.top();
1424         if (boundingRect.right() > maxX) maxX = boundingRect.right();
1425         if (boundingRect.bottom() > maxY) maxY = boundingRect.bottom();
1426         if (minX < 0) {
1427             maxX = maxX - minX;
1428         }
1429         if (minY < 0) {
1430             maxY = maxY - minY;
1431         }
1432     }
1433     QRect rect(minX, minY, maxX, maxY);
1434     return rect;
1435 }
1436
1437 QImage TitleWidget::renderedPixmap()
1438 {
1439     QRect rect = renderedRect();
1440     QImage pix(rect.width(), rect.height(), QImage::Format_ARGB32);
1441     pix.fill(Qt::transparent);
1442     QPainter painter(&pix);
1443     painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing);
1444     m_scene->clearTextSelection();
1445     QPen framepen = m_frameBorder->pen();
1446     m_frameBorder->setPen(Qt::NoPen);
1447     m_startViewport->setVisible(false);
1448     m_endViewport->setVisible(false);
1449     m_frameImage->setVisible(false);
1450
1451     m_scene->render(&painter, QRectF(), rect); //QRectF(minX, minY, maxX - minX, maxY - minY));
1452     painter.end();
1453     m_frameBorder->setPen(framepen);
1454     m_startViewport->setVisible(true);
1455     m_endViewport->setVisible(true);
1456     m_frameImage->setVisible(true);
1457     return pix;
1458 }
1459
1460 /** \brief Connected to the accepted signal - calls writeChoices */
1461 void TitleWidget::slotAccepted()
1462 {
1463     writeChoices();
1464 }
1465
1466 /** \brief Store the current choices of font, background and rect values */
1467 void TitleWidget::writeChoices()
1468 {
1469     // Get a pointer to a shared configuration instance, then get the TitleWidget group.
1470     KSharedConfigPtr config = KGlobal::config();
1471     KConfigGroup titleConfig(config, "TitleWidget");
1472     // Write the entries
1473     titleConfig.writeEntry("font_family", font_family->currentFont());
1474     //titleConfig.writeEntry("font_size", font_size->value());
1475     titleConfig.writeEntry("font_pixel_size", font_size->value());
1476     titleConfig.writeEntry("font_color", fontColorButton->color());
1477     titleConfig.writeEntry("font_alpha", textAlpha->value());
1478     titleConfig.writeEntry("font_weight", font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
1479     titleConfig.writeEntry("font_italic", buttonItalic->isChecked());
1480     titleConfig.writeEntry("font_underlined", buttonUnder->isChecked());
1481
1482     titleConfig.writeEntry("rect_foreground_color", rectFColor->color());
1483     titleConfig.writeEntry("rect_foreground_alpha", rectFAlpha->value());
1484     titleConfig.writeEntry("rect_background_color", rectBColor->color());
1485     titleConfig.writeEntry("rect_background_alpha", rectBAlpha->value());
1486     titleConfig.writeEntry("rect_line_width", rectLineWidth->value());
1487
1488     titleConfig.writeEntry("background_color", kcolorbutton->color());
1489     titleConfig.writeEntry("background_alpha", horizontalSlider->value());
1490
1491     titleConfig.writeEntry("crop_image", cropImage->isChecked());
1492
1493     //! \todo Not sure if I should sync - it is probably safe to do it
1494     config->sync();
1495
1496 }
1497
1498 /** \brief Read the last stored choices into the dialog */
1499 void TitleWidget::readChoices()
1500 {
1501     // Get a pointer to a shared configuration instance, then get the TitleWidget group.
1502     KSharedConfigPtr config = KGlobal::config();
1503     KConfigGroup titleConfig(config, "TitleWidget");
1504     // read the entries
1505     font_family->setCurrentFont(titleConfig.readEntry("font_family", font_family->currentFont()));
1506     font_size->setValue(titleConfig.readEntry("font_pixel_size", font_size->value()));
1507     fontColorButton->setColor(titleConfig.readEntry("font_color", fontColorButton->color()));
1508     textAlpha->setValue(titleConfig.readEntry("font_alpha", textAlpha->value()));
1509     int weight;
1510     if (titleConfig.readEntry("font_bold", false)) weight = QFont::Bold;
1511     else weight = titleConfig.readEntry("font_weight", font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
1512     setFontBoxWeight(weight);
1513     buttonItalic->setChecked(titleConfig.readEntry("font_italic", buttonItalic->isChecked()));
1514     buttonUnder->setChecked(titleConfig.readEntry("font_underlined", buttonUnder->isChecked()));
1515
1516     rectFColor->setColor(titleConfig.readEntry("rect_foreground_color", rectFColor->color()));
1517     rectFAlpha->setValue(titleConfig.readEntry("rect_foreground_alpha", rectFAlpha->value()));
1518     rectBColor->setColor(titleConfig.readEntry("rect_background_color", rectBColor->color()));
1519     rectBAlpha->setValue(titleConfig.readEntry("rect_background_alpha", rectBAlpha->value()));
1520     rectLineWidth->setValue(titleConfig.readEntry("rect_line_width", rectLineWidth->value()));
1521
1522     kcolorbutton->setColor(titleConfig.readEntry("background_color", kcolorbutton->color()));
1523     horizontalSlider->setValue(titleConfig.readEntry("background_alpha", horizontalSlider->value()));
1524
1525     cropImage->setChecked(titleConfig.readEntry("crop_image", cropImage->isChecked()));
1526 }
1527
1528 void TitleWidget::adjustFrameSize()
1529 {
1530     m_frameWidth = m_titledocument.frameWidth();
1531     m_frameHeight = m_titledocument.frameHeight();
1532     m_frameBorder->setRect(0, 0, m_frameWidth, m_frameHeight);
1533     displayBackgroundFrame();
1534 }
1535
1536
1537
1538