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