]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiExternal.cpp
If we are in a closeEvent, we don't want to close all buffers, because these may...
[lyx.git] / src / frontends / qt4 / GuiExternal.cpp
1 /**
2  * \file GuiExternal.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Angus Leeming
8  * \author Asger Alstrup
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "GuiExternal.h"
16
17 #include "FuncRequest.h"
18 #include "support/gettext.h"
19 #include "Length.h"
20 #include "LyXRC.h"
21
22 #include "insets/ExternalSupport.h"
23 #include "insets/ExternalTemplate.h"
24 #include "insets/InsetExternal.h"
25
26 #include "graphics/GraphicsCache.h"
27 #include "graphics/GraphicsCacheItem.h"
28 #include "graphics/GraphicsImage.h"
29
30 #include "support/convert.h"
31 #include "support/filetools.h"
32 #include "support/lstrings.h"
33 #include "support/lyxlib.h"
34 #include "support/os.h"
35
36 #include "LengthCombo.h"
37 #include "qt_helpers.h"
38 #include "Validator.h"
39
40 #include <QCheckBox>
41 #include <QGroupBox>
42 #include <QLineEdit>
43 #include <QPushButton>
44 #include <QTabWidget>
45 #include <QTextBrowser>
46
47 using namespace std;
48 using namespace lyx::support;
49
50 namespace lyx {
51 namespace frontend {
52
53 using namespace external;
54
55 namespace {
56
57 RotationDataType origins[] = {
58         RotationData::DEFAULT,
59         RotationData::TOPLEFT,
60         RotationData::BOTTOMLEFT,
61         RotationData::BASELINELEFT,
62         RotationData::CENTER,
63         RotationData::TOPCENTER,
64         RotationData::BOTTOMCENTER,
65         RotationData::BASELINECENTER,
66         RotationData::TOPRIGHT,
67         RotationData::BOTTOMRIGHT,
68         RotationData::BASELINERIGHT
69 };
70
71
72 // These are the strings, corresponding to the above, that the GUI should
73 // use. Note that they can/should be translated.
74 char const * const origin_gui_strs[] = {
75         N_("Default"),
76         N_("Top left"), N_("Bottom left"), N_("Baseline left"),
77         N_("Center"), N_("Top center"), N_("Bottom center"), N_("Baseline center"),
78         N_("Top right"), N_("Bottom right"), N_("Baseline right")
79 };
80
81 external::Template getTemplate(int i)
82 {
83         external::TemplateManager::Templates::const_iterator i1
84                 = external::TemplateManager::get().getTemplates().begin();
85         advance(i1, i);
86         return i1->second;
87 }
88
89 } // namespace anon
90
91
92 GuiExternal::GuiExternal(GuiView & lv)
93         : GuiDialog(lv, "external", qt_("External Material")), bbChanged_(false)
94 {
95         setupUi(this);
96
97         connect(okPB, SIGNAL(clicked()), this, SLOT(slotOK()));
98         connect(applyPB, SIGNAL(clicked()), this, SLOT(slotApply()));
99         connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
100
101         /*
102         connect(displayGB, SIGNAL(toggled(bool)),
103                 displayscaleED, SLOT(setEnabled(bool)));
104                 */
105         connect(originCO, SIGNAL(activated(int)),
106                 this, SLOT(change_adaptor()));
107         connect(aspectratioCB, SIGNAL(stateChanged(int)),
108                 this, SLOT(change_adaptor()));
109         connect(browsePB, SIGNAL(clicked()),
110                 this, SLOT(browseClicked()));
111         connect(externalCO, SIGNAL(activated(QString)),
112                 this, SLOT(templateChanged()));
113         connect(extraED, SIGNAL(textChanged(QString)),
114                 this, SLOT(extraChanged(QString)));
115         connect(extraFormatCO, SIGNAL(activated(QString)),
116                 this, SLOT(formatChanged(QString)));
117         connect(widthUnitCO, SIGNAL(activated(int)),
118                 this, SLOT(widthUnitChanged()));
119         connect(heightUnitCO, SIGNAL(selectionChanged(lyx::Length::UNIT)),
120                 this, SLOT(change_adaptor()));
121         connect(displayGB, SIGNAL(toggled(bool)),
122                 this, SLOT(change_adaptor()));
123         connect(displayscaleED, SIGNAL(textChanged(QString)),
124                 this, SLOT(change_adaptor()));
125         connect(angleED, SIGNAL(textChanged(QString)),
126                 this, SLOT(change_adaptor()));
127         connect(widthED, SIGNAL(textChanged(QString)),
128                 this, SLOT(sizeChanged()));
129         connect(heightED, SIGNAL(textChanged(QString)),
130                 this, SLOT(sizeChanged()));
131         connect(fileED, SIGNAL(textChanged(QString)),
132                 this, SLOT(change_adaptor()));
133         connect(clipCB, SIGNAL(stateChanged(int)),
134                 this, SLOT(change_adaptor()));
135         connect(getbbPB, SIGNAL(clicked()), this, SLOT(getbbClicked()));
136         connect(xrED, SIGNAL(textChanged(QString)), this, SLOT(bbChanged()));
137         connect(ytED, SIGNAL(textChanged(QString)), this, SLOT(bbChanged()));
138         connect(xlED, SIGNAL(textChanged(QString)), this, SLOT(bbChanged()));
139         connect(ybED, SIGNAL(textChanged(QString)), this, SLOT(bbChanged()));
140         connect(draftCB, SIGNAL(clicked()), this, SLOT(change_adaptor()));
141
142         QIntValidator * validator = new QIntValidator(displayscaleED);
143         validator->setBottom(1);
144         displayscaleED->setValidator(validator);
145
146         angleED->setValidator(new QDoubleValidator(-360, 360, 2, angleED));
147
148         xlED->setValidator(new QIntValidator(xlED));
149         ybED->setValidator(new QIntValidator(ybED));
150         xrED->setValidator(new QIntValidator(xrED));
151         ytED->setValidator(new QIntValidator(ytED));
152
153         widthED->setValidator(unsignedLengthValidator(widthED));
154         heightED->setValidator(unsignedLengthValidator(heightED));
155
156         setFocusProxy(fileED);
157
158         bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
159
160         bc().setOK(okPB);
161         bc().setApply(applyPB);
162         bc().setCancel(closePB);
163
164         bc().addReadOnly(fileED);
165         bc().addReadOnly(browsePB);
166         bc().addReadOnly(externalCO);
167         bc().addReadOnly(draftCB);
168         bc().addReadOnly(displayscaleED);
169         bc().addReadOnly(displayGB);
170         bc().addReadOnly(angleED);
171         bc().addReadOnly(originCO);
172         bc().addReadOnly(heightUnitCO);
173         bc().addReadOnly(heightED);
174         bc().addReadOnly(aspectratioCB);
175         bc().addReadOnly(widthUnitCO);
176         bc().addReadOnly(widthED);
177         bc().addReadOnly(clipCB);
178         bc().addReadOnly(getbbPB);
179         bc().addReadOnly(ytED);
180         bc().addReadOnly(xlED);
181         bc().addReadOnly(xrED);
182         bc().addReadOnly(ybED);
183         bc().addReadOnly(extraFormatCO);
184         bc().addReadOnly(extraED);
185
186         bc().addCheckedLineEdit(angleED, angleLA);
187         bc().addCheckedLineEdit(displayscaleED, scaleLA);
188         bc().addCheckedLineEdit(heightED, heightLA);
189         bc().addCheckedLineEdit(widthED, widthLA);
190         bc().addCheckedLineEdit(xlED, lbLA);
191         bc().addCheckedLineEdit(ybED, lbLA);
192         bc().addCheckedLineEdit(xrED, rtLA);
193         bc().addCheckedLineEdit(ytED, rtLA);
194         bc().addCheckedLineEdit(fileED, fileLA);
195
196         external::TemplateManager::Templates::const_iterator i1, i2;
197         i1 = external::TemplateManager::get().getTemplates().begin();
198         i2 = external::TemplateManager::get().getTemplates().end();
199         for (; i1 != i2; ++i1)
200                 externalCO->addItem(qt_(i1->second.lyxName));
201
202         // Fill the origins combo
203         for (size_t i = 0; i != sizeof(origins) / sizeof(origins[0]); ++i)
204                 originCO->addItem(qt_(origin_gui_strs[i]));
205
206         // add scale item
207         widthUnitCO->insertItem(0, qt_("Scale%"), "scale");
208 }
209
210
211 bool GuiExternal::activateAspectratio() const
212 {
213         if (usingScale())
214                 return false;
215
216         QString const wstr = widthED->text();
217         if (wstr.isEmpty())
218                 return false;
219         bool wIsDbl;
220         double val = wstr.trimmed().toDouble(&wIsDbl);
221         if (wIsDbl && float_equal(val, 0.0, 0.05))
222                 return false;
223         Length l;
224         if (!wIsDbl && (!isValidLength(fromqstr(wstr), &l) || l.zero()))
225                 return false;
226
227         QString const hstr = heightED->text();
228         if (hstr.isEmpty())
229                 return false;
230         bool hIsDbl;
231         val = hstr.trimmed().toDouble(&hIsDbl);
232         if (hIsDbl && float_equal(val, 0.0, 0.05))
233                 return false;
234         if (!hIsDbl && (!isValidLength(fromqstr(hstr), &l) || l.zero()))
235                 return false;
236
237         return true;
238 }
239
240
241 bool GuiExternal::usingScale() const
242 {
243         return (widthUnitCO->itemData(
244                 widthUnitCO->currentIndex()).toString() == "scale");
245 }
246
247
248 void GuiExternal::bbChanged()
249 {
250         bbChanged_ = true;
251         changed();
252 }
253
254
255 void GuiExternal::browseClicked()
256 {
257         int const choice =  externalCO->currentIndex();
258         QString const template_name = toqstr(getTemplate(choice).lyxName);
259         QString const str = browse(fileED->text(), template_name);
260         if (!str.isEmpty()) {
261                 fileED->setText(str);
262                 changed();
263         }
264 }
265
266
267 void GuiExternal::change_adaptor()
268 {
269         changed();
270 }
271
272
273 void GuiExternal::extraChanged(const QString & text)
274 {
275         extra_[extraFormatCO->currentText()] = text;
276         changed();
277 }
278
279
280 void GuiExternal::formatChanged(const QString & format)
281 {
282         extraED->setText(extra_[format]);
283 }
284
285
286 void GuiExternal::getbbClicked()
287 {
288         xlED->setText("0");
289         ybED->setText("0");
290         xrED->setText("0");
291         ytED->setText("0");
292
293         string const filename = fromqstr(fileED->text());
294         if (filename.empty())
295                 return;
296
297         FileName const abs_file(support::makeAbsPath(filename, fromqstr(bufferFilepath())));
298
299         // try to get it from the file, if possible
300         string bb = readBB_from_PSFile(abs_file);
301         if (bb.empty()) {
302                 // we don't, so ask the Graphics Cache if it has loaded the file
303                 int width = 0;
304                 int height = 0;
305
306                 graphics::Cache & gc = graphics::Cache::get();
307                 if (gc.inCache(abs_file)) {
308                         graphics::Image const * image = gc.item(abs_file)->image();
309
310                         if (image) {
311                                 width  = image->width();
312                                 height = image->height();
313                         }
314                 }
315                 bb = "0 0 " + convert<string>(width) + ' ' + convert<string>(height);
316         }
317
318         xlED->setText(toqstr(token(bb, ' ', 0)));
319         ybED->setText(toqstr(token(bb, ' ', 1)));
320         xrED->setText(toqstr(token(bb, ' ', 2)));
321         ytED->setText(toqstr(token(bb, ' ', 3)));
322
323         bbChanged_ = false;
324 }
325
326
327 void GuiExternal::sizeChanged()
328 {
329         aspectratioCB->setEnabled(activateAspectratio());
330         changed();
331 }
332
333
334 void GuiExternal::templateChanged()
335 {
336         updateTemplate();
337         changed();
338 }
339
340
341 void GuiExternal::widthUnitChanged()
342 {
343         if (usingScale())
344                 widthED->setValidator(new QDoubleValidator(0, 1000, 2, widthED));
345         else
346                 widthED->setValidator(unsignedLengthValidator(widthED));
347
348         heightED->setEnabled(!usingScale());
349         heightUnitCO->setEnabled(!usingScale());
350         changed();
351 }
352
353
354 static void setRotation(QLineEdit & angleED, QComboBox & originCO,
355         external::RotationData const & data)
356 {
357         originCO.setCurrentIndex(int(data.origin()));
358         doubleToWidget(&angleED, data.angle);
359 }
360
361
362 static void getRotation(external::RotationData & data,
363         QLineEdit const & angleED, QComboBox const & originCO)
364 {
365         typedef external::RotationData::OriginType OriginType;
366
367         data.origin(static_cast<OriginType>(originCO.currentIndex()));
368         data.angle = widgetToDoubleStr(&angleED);
369 }
370
371
372 static void setSize(QLineEdit & widthED, LengthCombo & widthUnitCO,
373         QLineEdit & heightED, LengthCombo & heightUnitCO,
374         QCheckBox & aspectratioCB,
375         external::ResizeData const & data)
376 {
377         bool using_scale = data.usingScale();
378         string scale = data.scale;
379         if (data.no_resize()) {
380                 // Everything is zero, so default to this!
381                 using_scale = true;
382                 scale = "100";
383         }
384
385         if (using_scale) {
386                 doubleToWidget(&widthED, scale);
387                 widthUnitCO.setCurrentItem("scale");
388         } else
389                 lengthToWidgets(&widthED, &widthUnitCO,
390                                 data.width.asString(), Length::defaultUnit());
391
392         string const h = data.height.zero() ? string() : data.height.asString();
393         Length::UNIT const default_unit = data.width.zero() ?
394                 Length::defaultUnit() : data.width.unit();
395         lengthToWidgets(&heightED, &heightUnitCO, h, default_unit);
396
397         heightED.setEnabled(!using_scale);
398         heightUnitCO.setEnabled(!using_scale);
399
400         aspectratioCB.setChecked(data.keepAspectRatio);
401
402         bool const disable_aspectRatio = using_scale ||
403                 data.width.zero() || data.height.zero();
404         aspectratioCB.setEnabled(!disable_aspectRatio);
405 }
406
407
408 static void getSize(external::ResizeData & data,
409         QLineEdit const & widthED, QComboBox const & widthUnitCO,
410         QLineEdit const & heightED, LengthCombo const & heightUnitCO,
411         QCheckBox const & aspectratioCB, bool const scaling)
412 {
413         if (scaling) {
414                 // scaling instead of a width
415                 data.scale = widgetToDoubleStr(&widthED);
416                 data.width = Length();
417         } else {
418                 data.width = Length(widgetsToLength(&widthED, &widthUnitCO));
419                 data.scale = string();
420         }
421         data.height = Length(widgetsToLength(&heightED, &heightUnitCO));
422         data.keepAspectRatio = aspectratioCB.isChecked();
423 }
424
425
426 void setCrop(QCheckBox & clipCB,
427         QLineEdit & xlED, QLineEdit & ybED,
428         QLineEdit & xrED, QLineEdit & ytED,
429         external::ClipData const & data)
430 {
431         clipCB.setChecked(data.clip);
432         graphics::BoundingBox const & bbox = data.bbox;
433         xlED.setText(QString::number(bbox.xl));
434         ybED.setText(QString::number(bbox.yb));
435         xrED.setText(QString::number(bbox.xr));
436         ytED.setText(QString::number(bbox.yt));
437 }
438
439
440 static void getCrop(external::ClipData & data,
441         QCheckBox const & clipCB,
442         QLineEdit const & xlED, QLineEdit const & ybED,
443         QLineEdit const & xrED, QLineEdit const & ytED,
444         bool bb_changed)
445 {
446         data.clip = clipCB.isChecked();
447
448         if (!bb_changed)
449                 return;
450
451         data.bbox.xl = xlED.text().toInt();
452         data.bbox.yb = ybED.text().toInt();
453         data.bbox.xr = xrED.text().toInt();
454         data.bbox.yt = ytED.text().toInt();
455 }
456
457
458 void GuiExternal::updateContents()
459 {
460         string const name =
461                 params_.filename.outputFilename(fromqstr(bufferFilepath()));
462         fileED->setText(toqstr(name));
463
464         int index = -1;
465         external::TemplateManager::Templates::const_iterator i1, i2;
466         i1 = external::TemplateManager::get().getTemplates().begin();
467         i2 = external::TemplateManager::get().getTemplates().end();
468         for (int i = 0; i1 != i2; ++i1, ++i) {
469                 if (i1->second.lyxName == params_.templatename()) {
470                         index = i;
471                         break;
472                 }
473         }
474
475         externalCO->setCurrentIndex(index);
476         updateTemplate();
477
478         draftCB->setChecked(params_.draft);
479
480         displayGB->setChecked(params_.display);
481         displayscaleED->setText(QString::number(params_.lyxscale));
482         bool scaled = params_.display && !isBufferReadonly() &&
483                         (params_.preview_mode != PREVIEW_INSTANT);
484         displayscaleED->setEnabled(scaled);
485         scaleLA->setEnabled(scaled);
486         displayGB->setEnabled(lyxrc.display_graphics);
487
488
489         setRotation(*angleED, *originCO, params_.rotationdata);
490
491         setSize(*widthED, *widthUnitCO, *heightED, *heightUnitCO,
492                 *aspectratioCB, params_.resizedata);
493
494         setCrop(*clipCB, *xlED, *ybED, *xrED, *ytED, params_.clipdata);
495         bbChanged_ = !params_.clipdata.bbox.empty();
496
497         isValid();
498 }
499
500
501 void GuiExternal::updateTemplate()
502 {
503         external::Template templ = getTemplate(externalCO->currentIndex());
504         externalTB->setPlainText(qt_(templ.helpText));
505
506         // Ascertain which (if any) transformations the template supports
507         // and disable tabs and Group Boxes hosting unsupported transforms.
508         typedef vector<external::TransformID> TransformIDs;
509         TransformIDs const transformIds = templ.transformIds;
510         TransformIDs::const_iterator tr_begin = transformIds.begin();
511         TransformIDs::const_iterator const tr_end = transformIds.end();
512
513         bool found = std::find(tr_begin, tr_end, external::Rotate) != tr_end;
514         rotationGB->setEnabled(found);
515
516         found = std::find(tr_begin, tr_end, external::Resize) != tr_end;
517         scaleGB->setEnabled(found);
518
519         found = std::find(tr_begin, tr_end, external::Clip) != tr_end;
520         cropGB->setEnabled(found);
521
522         tab->setTabEnabled(tab->indexOf(sizetab),
523                 rotationGB->isEnabled()
524                 || scaleGB->isEnabled()
525                 || cropGB->isEnabled());
526
527         found = std::find(tr_begin, tr_end, external::Extra) != tr_end;
528         optionsGB->setEnabled(found);
529
530         bool scaled = displayGB->isChecked() && displayGB->isEnabled() &&
531                         !isBufferReadonly() && (templ.preview_mode != PREVIEW_INSTANT);
532         displayscaleED->setEnabled(scaled);
533         scaleLA->setEnabled(scaled);
534
535         if (!found)
536                 return;
537
538         // Ascertain whether the template has any formats supporting
539         // the 'Extra' option
540         extra_.clear();
541         extraED->clear();
542         extraFormatCO->clear();
543
544         external::Template::Formats::const_iterator it  = templ.formats.begin();
545         external::Template::Formats::const_iterator end = templ.formats.end();
546         for (; it != end; ++it) {
547                 if (it->second.option_transformers.find(external::Extra) ==
548                     it->second.option_transformers.end())
549                         continue;
550                 string const format = it->first;
551                 string const opt = params_.extradata.get(format);
552                 extraFormatCO->addItem(toqstr(format));
553                 extra_[toqstr(format)] = toqstr(opt);
554         }
555
556         bool const enabled = extraFormatCO->count()  > 0;
557
558         optionsGB->setEnabled(enabled);
559         extraED->setEnabled(enabled && !isBufferReadonly());
560         extraFormatCO->setEnabled(enabled);
561
562         if (enabled) {
563                 extraFormatCO->setCurrentIndex(0);
564                 extraED->setText(extra_[extraFormatCO->currentText()]);
565         }
566 }
567
568
569 void GuiExternal::applyView()
570 {
571         params_.filename.set(fromqstr(fileED->text()), fromqstr(bufferFilepath()));
572         params_.settemplate(getTemplate(externalCO->currentIndex()).lyxName);
573
574         params_.draft = draftCB->isChecked();
575         params_.lyxscale = displayscaleED->text().toInt();
576         params_.display = displayGB->isChecked();
577
578         if (rotationGB->isEnabled())
579                 getRotation(params_.rotationdata, *angleED, *originCO);
580
581         if (scaleGB->isEnabled())
582                 getSize(params_.resizedata, *widthED, *widthUnitCO,
583                         *heightED, *heightUnitCO, *aspectratioCB, usingScale());
584
585         if (cropGB->isEnabled())
586                 getCrop(params_.clipdata, *clipCB, *xlED, *ybED,
587                         *xrED, *ytED, bbChanged_);
588
589         if (optionsGB->isEnabled()) {
590                 MapType::const_iterator it = extra_.begin();
591                 MapType::const_iterator const end = extra_.end();
592                 for (; it != end; ++it)
593                         params_.extradata.set(fromqstr(it.key()), fromqstr(it.value().trimmed()));
594         }
595 }
596
597
598 bool GuiExternal::initialiseParams(string const & data)
599 {
600         InsetExternal::string2params(data, buffer(), params_);
601         return true;
602 }
603
604
605 void GuiExternal::clearParams()
606 {
607         params_ = InsetExternalParams();
608 }
609
610
611 void GuiExternal::dispatchParams()
612 {
613         string const lfun = InsetExternal::params2string(params_, buffer());
614         dispatch(FuncRequest(getLfun(), lfun));
615 }
616
617
618 static QStringList templateFilters(QString const & template_name)
619 {
620         /// Determine the template file extension
621         external::TemplateManager const & etm =
622                 external::TemplateManager::get();
623         external::Template const * const et_ptr =
624                 etm.getTemplateByName(fromqstr(template_name));
625
626         return fileFilters(et_ptr ? toqstr(et_ptr->fileRegExp) : QString());
627 }
628
629
630 QString GuiExternal::browse(QString const & input,
631                                      QString const & template_name) const
632 {
633         QString const title = qt_("Select external file");
634         QString const bufpath = bufferFilepath();
635         QStringList const filter = templateFilters(template_name);
636
637         QString const label1 = qt_("Documents|#o#O");
638         QString const dir1 = toqstr(lyxrc.document_path);
639
640         return browseRelFile(input, bufpath, title, filter, false, label1, dir1);
641 }
642
643
644 Dialog * createGuiExternal(GuiView & lv) { return new GuiExternal(lv); }
645
646
647 } // namespace frontend
648 } // namespace lyx
649
650 #include "moc_GuiExternal.cpp"