]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiGraphics.cpp
Sync with master
[lyx.git] / src / frontends / qt / GuiGraphics.cpp
1 /**
2  * \file GuiGraphics.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  * \author John Levon
8  * \author Edwin Leuven
9  * \author Herbert Voß
10  * \author Richard Kimberly Heck
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "GuiGraphics.h"
18 #include "frontends/alert.h"
19 #include "qt_helpers.h"
20 #include "Validator.h"
21
22 #include "Buffer.h"
23 #include "FuncRequest.h"
24 #include "LengthCombo.h"
25 #include "LyXRC.h"
26
27 #include "graphics/epstools.h"
28 #include "graphics/GraphicsCache.h"
29 #include "graphics/GraphicsCacheItem.h"
30 #include "graphics/GraphicsImage.h"
31
32 #include "insets/InsetGraphics.h"
33
34 #include "support/convert.h"
35 #include "support/debug.h"
36 #include "support/filetools.h"
37 #include "support/gettext.h"
38 #include "support/Length.h"
39 #include "support/lstrings.h"
40 #include "support/os.h"
41 #include "support/Package.h"
42 #include "support/types.h"
43
44 #include <QCheckBox>
45 #include <QLabel>
46 #include <QLineEdit>
47 #include <QPushButton>
48 #include <QValidator>
49
50 #include <cmath>
51 #include <utility>
52
53 using namespace std;
54 using namespace lyx::support;
55
56 namespace {
57
58 // These are the strings that are stored in the LyX file and which
59 // correspond to the LaTeX identifiers shown in the comments at the
60 // end of each line.
61 char const * const rorigin_lyx_strs[] = {
62         // the LaTeX default is leftBaseline
63         "",
64         "leftTop",  "leftBottom", "leftBaseline", // lt lb lB
65         "center", "centerTop", "centerBottom", "centerBaseline", // c ct cb cB
66         "rightTop", "rightBottom", "rightBaseline" }; // rt rb rB
67
68 // These are the strings, corresponding to the above, that the GUI should
69 // use. Note that they can/should be translated.
70 char const * const rorigin_gui_strs[] = {
71         N_("Default"),
72         N_("Top left"), N_("Bottom left"), N_("Baseline left"),
73         N_("Center"), N_("Top center"), N_("Bottom center"), N_("Baseline center"),
74         N_("Top right"), N_("Bottom right"), N_("Baseline right") };
75
76 size_t const rorigin_size = sizeof(rorigin_lyx_strs) / sizeof(char *);
77
78 static string const autostr = N_("automatically");
79
80 } // namespace
81
82
83 namespace lyx {
84 namespace frontend {
85
86 //FIXME setAutoTextCB should really take an argument, as indicated, that
87 //determines what text is to be written for "auto". But making
88 //that work involves more extensive revisions than we now want
89 //to make, since "auto" also appears in paramsToDialog().
90 //The right way to do this, I think, would be to define a class
91 //checkedLengthSet (and a partnering labeledLengthSete) that encapsulated
92 //the checkbox, line edit, and length combo together, and then made e.g.
93 //lengthToWidgets, widgetsToLength, etc, all public methods of that class.
94 //Perhaps even the validator could be exposed through it.
95 /**
96  * sets a checkbox-line edit-length combo group, using "text" if the
97  * checkbox is unchecked and clearing the line edit if it previously
98  * said "text".
99 */
100 static void setAutoTextCB(QCheckBox * checkBox, QLineEdit * lineEdit,
101         LengthCombo * lengthCombo/*, string text = "auto"*/)
102 {
103         if (!checkBox->isChecked())
104                 lengthToWidgets(lineEdit, lengthCombo,
105                                 _(autostr), lengthCombo->currentLengthItem());
106         else if (lineEdit->text() == qt_(autostr))
107                 lengthToWidgets(lineEdit, lengthCombo, string(),
108                                 lengthCombo->currentLengthItem());
109 }
110
111
112 GuiGraphics::GuiGraphics(GuiView & lv)
113         : GuiDialog(lv, "graphics", qt_("Graphics")), bbChanged(false)
114 {
115         setupUi(this);
116
117         //main buttons
118         connect(buttonBox, SIGNAL(clicked(QAbstractButton *)),
119                         this, SLOT(slotButtonBox(QAbstractButton *)));
120
121         //graphics pane
122         connect(filename, SIGNAL(textChanged(const QString &)),
123                 this, SLOT(change_adaptor()));
124         connect(WidthCB, SIGNAL(clicked()),
125                 this, SLOT(change_adaptor()));
126         connect(HeightCB, SIGNAL(clicked()),
127                 this, SLOT(change_adaptor()));
128         connect(Width, SIGNAL(textChanged(const QString &)),
129                 this, SLOT(updateAspectRatioStatus()));
130         connect(Width, SIGNAL(textChanged(const QString &)),
131                 this, SLOT(change_adaptor()));
132         connect(Height, SIGNAL(textChanged(const QString &)),
133                 this, SLOT(updateAspectRatioStatus()));
134         connect(Height, SIGNAL(textChanged(const QString &)),
135                 this, SLOT(change_adaptor()));
136         connect(heightUnit, SIGNAL(selectionChanged(lyx::Length::UNIT)),
137                 this, SLOT(change_adaptor()));
138         connect(widthUnit, SIGNAL(selectionChanged(lyx::Length::UNIT)),
139                 this, SLOT(change_adaptor()));
140         connect(aspectratio, SIGNAL(stateChanged(int)),
141                 this, SLOT(change_adaptor()));
142         connect(angle, SIGNAL(textChanged(const QString &)),
143                 this, SLOT(change_adaptor()));
144         connect(origin, SIGNAL(activated(int)),
145                 this, SLOT(change_adaptor()));
146         connect(scaleCB, SIGNAL(clicked()),
147                 this, SLOT(change_adaptor()));
148         connect(Scale, SIGNAL(textChanged(const QString &)),
149                 this, SLOT(change_adaptor()));
150         connect(rotateOrderCB, SIGNAL(clicked()),
151                 this, SLOT(change_adaptor()));
152
153         filename->setValidator(new PathValidator(true, filename));
154         setFocusProxy(filename);
155
156         QDoubleValidator * scaleValidator =
157                 new DoubleAutoValidator(Scale, qt_(autostr));
158         scaleValidator->setBottom(0);
159         scaleValidator->setDecimals(256); //I guess that will do
160         Scale->setValidator(scaleValidator);
161         Height->setValidator(positiveLengthAutoValidator(Height, qt_(autostr)));
162         Width->setValidator(positiveLengthAutoValidator(Width, qt_(autostr)));
163         angle->setValidator(new QDoubleValidator(-360, 360, 2, angle));
164
165         //clipping pane
166         connect(clip, SIGNAL(stateChanged(int)),
167                 this, SLOT(change_adaptor()));
168         connect(lbY, SIGNAL(textChanged(const QString &)),
169                 this, SLOT(changeBB()));
170         connect(lbYunit, SIGNAL(activated(int)),
171                 this, SLOT(changeBB()));
172         connect(rtY, SIGNAL(textChanged(const QString &)),
173                 this, SLOT(changeBB()));
174         connect(rtYunit, SIGNAL(activated(int)),
175                 this, SLOT(changeBB()));
176         connect(lbX, SIGNAL(textChanged(const QString &)),
177                 this, SLOT(changeBB()));
178         connect(lbXunit, SIGNAL(activated(int)),
179                 this, SLOT(changeBB()));
180         connect(rtX, SIGNAL(textChanged(const QString &)),
181                 this, SLOT(changeBB()));
182         connect(rtXunit, SIGNAL(activated(int)),
183                 this, SLOT(changeBB()));
184         connect(getPB, SIGNAL(clicked()),
185                 this, SLOT(change_adaptor()));
186
187         lbX->setValidator(new QDoubleValidator(lbX));
188         lbY->setValidator(new QDoubleValidator(lbY));
189         rtX->setValidator(new QDoubleValidator(rtX));
190         rtY->setValidator(new QDoubleValidator(rtY));
191
192         //extra options pane
193         connect(latexoptions, SIGNAL(textChanged(const QString &)),
194                 this, SLOT(change_adaptor()));
195         connect(draftCB, SIGNAL(stateChanged(int)),
196                 this, SLOT(change_adaptor()));
197         connect(displayGB, SIGNAL(clicked(bool)), this, SLOT(change_adaptor()));
198         connect(darkModeCB, SIGNAL(clicked(bool)), this, SLOT(change_adaptor()));
199         connect(displayscale, SIGNAL(textChanged(const QString &)),
200                 this, SLOT(change_adaptor()));
201         connect(groupCO, SIGNAL(currentIndexChanged(int)),
202                 this, SLOT(changeGroup(int)));
203
204         displayscale->setValidator(new QIntValidator(1, 1000, displayscale));
205
206         bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
207         bc().setOK(buttonBox->button(QDialogButtonBox::Ok));
208         bc().setApply(buttonBox->button(QDialogButtonBox::Apply));
209         bc().setCancel(buttonBox->button(QDialogButtonBox::Cancel));
210         bc().setRestore(buttonBox->button(QDialogButtonBox::Reset));
211
212         bc().addReadOnly(latexoptions);
213         bc().addReadOnly(filenameL);
214         bc().addReadOnly(filename);
215         bc().addReadOnly(browsePB);
216         bc().addReadOnly(bbFrame);
217         bc().addReadOnly(draftCB);
218         bc().addReadOnly(clip);
219         bc().addReadOnly(displayGB);
220         bc().addReadOnly(darkModeCB);
221         bc().addReadOnly(sizeGB);
222         bc().addReadOnly(rotationGB);
223         bc().addReadOnly(latexoptions);
224         bc().addReadOnly(getPB);
225         bc().addReadOnly(rotateOrderCB);
226
227         // initialize the length validator
228         bc().addCheckedLineEdit(Scale, scaleCB);
229         bc().addCheckedLineEdit(Width, WidthCB);
230         bc().addCheckedLineEdit(Height, HeightCB);
231         bc().addCheckedLineEdit(displayscale, scaleLA);
232         bc().addCheckedLineEdit(angle, angleL);
233         bc().addCheckedLineEdit(lbX, xL);
234         bc().addCheckedLineEdit(lbY, yL);
235         bc().addCheckedLineEdit(rtX, xL_2);
236         bc().addCheckedLineEdit(rtY, yL_2);
237         bc().addCheckedLineEdit(filename, filenameL);
238 }
239
240
241 void GuiGraphics::change_adaptor()
242 {
243         changed();
244 }
245
246
247 void GuiGraphics::changeGroup(int /* index */)
248 {
249         QString const new_group = groupCO->itemData(
250                 groupCO->currentIndex()).toString();
251
252         // check if the old group consisted only of this member
253         if (current_group_ != fromqstr(new_group)
254             && graphics::countGroupMembers(buffer(), current_group_) == 1) {
255                 if (!new_group.isEmpty()) {
256                         if (Alert::prompt(_("Dissolve previous group?"),
257                                 bformat(_("If you assign this graphic to group '%2$s',\n"
258                                           "the previously assigned group '%1$s' will be dissolved,\n"
259                                           "because this graphic was its only member.\n"
260                                           "How do you want to proceed?"),
261                                         from_utf8(current_group_), qstring_to_ucs4(new_group)),
262                                         0, 0,
263                                         bformat(_("Stick with group '%1$s'"),
264                                                 from_utf8(current_group_)),
265                                         bformat(_("Assign to group '%1$s' anyway"),
266                                                 qstring_to_ucs4(new_group))) == 0) {
267                                 groupCO->setCurrentIndex(
268                                         groupCO->findData(toqstr(current_group_), Qt::MatchExactly));
269                                 return;
270                         }
271                 } else {
272                         if (Alert::prompt(_("Dissolve previous group?"),
273                         bformat(_("If you sign off this graphic from group '%1$s',\n"
274                                   "the group will be dissolved,\n"
275                                   "because this graphic was its only member.\n"
276                                   "How do you want to proceed?"),
277                                 from_utf8(current_group_)),
278                                 0, 0,
279                                 bformat(_("Stick with group '%1$s'"),
280                                 from_utf8(current_group_)),
281                                 bformat(_("Sign off from group '%1$s'"),
282                                 from_utf8(current_group_))) == 0) {
283                         groupCO->setCurrentIndex(
284                                 groupCO->findData(toqstr(current_group_), Qt::MatchExactly));
285                         return;
286                         }
287                 }
288         }
289
290         if (new_group.isEmpty()) {
291                 changed();
292                 return;
293         }
294
295         string grp = graphics::getGroupParams(buffer(), fromqstr(new_group));
296         if (grp.empty()) {
297                 // group does not exist yet
298                 changed();
299                 return;
300         }
301
302         // filename might have been changed
303         QString current_filename = filename->text();
304
305         // group exists: load params into the dialog
306         groupCO->blockSignals(true);
307         InsetGraphics::string2params(grp, buffer(), params_);
308         paramsToDialog(params_);
309         groupCO->blockSignals(false);
310
311         // reset filename
312         filename->setText(current_filename);
313
314         changed();
315 }
316
317
318 void GuiGraphics::on_newGroupPB_clicked()
319 {
320         docstring newgroup;
321         if (!Alert::askForText(newgroup, _("Enter unique group name:")))
322                 return;
323         if (newgroup.empty())
324                 return;
325         if (groupCO->findData(toqstr(newgroup), Qt::MatchExactly) != -1) {
326                 Alert::warning(_("Group already defined!"),
327                         bformat(_("A graphics group with the name '%1$s' already exists."),
328                                 newgroup));
329                 return;
330         }
331         groupCO->addItem(toqstr(newgroup), toqstr(newgroup));
332         groupCO->setCurrentIndex(
333                 groupCO->findData(toqstr(newgroup), Qt::MatchExactly));
334 }
335
336
337 void GuiGraphics::changeBB()
338 {
339         bbChanged = isChangedBB();
340         getPB->setEnabled(bbChanged);
341         LYXERR(Debug::GRAPHICS, "[bb_Changed set to " << bbChanged << "]");
342         changed();
343 }
344
345
346 void GuiGraphics::on_browsePB_clicked()
347 {
348         QString const str = browse(filename->text());
349         if (!str.isEmpty()) {
350                 filename->setText(str);
351                 // read in the bb values of the new file
352                 // if there was no explicit custom viewport
353                 if (!bbChanged)
354                         getBB();
355                 changed();
356         }
357 }
358
359
360 void GuiGraphics::on_getPB_clicked()
361 {
362         getBB();
363         bbChanged = false;
364 }
365
366
367 void GuiGraphics::setAutoText()
368 {
369         if (scaleCB->isChecked())
370                 return;
371         if (!Scale->isEnabled() && Scale->text() != "100")
372                 Scale->setText("100");
373
374         setAutoTextCB(WidthCB, Width, widthUnit);
375         setAutoTextCB(HeightCB, Height, heightUnit);
376 }
377
378
379 void GuiGraphics::on_scaleCB_toggled(bool setScale)
380 {
381         Scale->setEnabled(setScale);
382         if (setScale) {
383                 Scale->setText("100");
384                 Scale->setFocus(Qt::OtherFocusReason);
385         }
386
387         WidthCB->setDisabled(setScale);
388         WidthCB->blockSignals(true);
389         WidthCB->setChecked(false);
390         WidthCB->blockSignals(false);
391         Width->setEnabled(false);
392         widthUnit->setEnabled(false);
393
394         HeightCB->setDisabled(setScale);
395         HeightCB->blockSignals(true);
396         HeightCB->setChecked(false);
397         HeightCB->blockSignals(false);
398         Height->setEnabled(false);
399         heightUnit->setEnabled(false);
400
401         rotateOrderCB->setEnabled((WidthCB->isChecked() ||
402                                  HeightCB->isChecked() ||
403                                  scaleCB->isChecked()) &&
404                                  (angle->text() != "0"));
405
406         setAutoText();
407         updateAspectRatioStatus();
408 }
409
410
411 void GuiGraphics::on_WidthCB_toggled(bool setWidth)
412 {
413         Width->setEnabled(setWidth);
414         widthUnit->setEnabled(setWidth);
415         if (setWidth)
416                 Width->setFocus(Qt::OtherFocusReason);
417
418         bool const setHeight = HeightCB->isChecked();
419         scaleCB->setEnabled(!setWidth && !setHeight);
420         //already will be unchecked, so don't need to do that
421         Scale->setEnabled((!setWidth && !setHeight) //=scaleCB->isEnabled()
422                         && scaleCB->isChecked()); //should be false, but let's check
423         rotateOrderCB->setEnabled((setWidth || setHeight ||
424                                  scaleCB->isChecked()) &&
425                                  (angle->text() != "0"));
426
427         setAutoText();
428         updateAspectRatioStatus();
429 }
430
431
432 void GuiGraphics::on_HeightCB_toggled(bool setHeight)
433 {
434         Height->setEnabled(setHeight);
435         heightUnit->setEnabled(setHeight);
436         if (setHeight)
437                 Height->setFocus(Qt::OtherFocusReason);
438
439         bool const setWidth = WidthCB->isChecked();
440         scaleCB->setEnabled(!setWidth && !setHeight);
441         //already unchecked
442         Scale->setEnabled((!setWidth && !setHeight) //=scaleCB->isEnabled()
443                 && scaleCB->isChecked()); //should be false
444         rotateOrderCB->setEnabled((setWidth || setHeight ||
445                                  scaleCB->isChecked()) &&
446                                  (angle->text() != "0"));
447
448         setAutoText();
449         updateAspectRatioStatus();
450 }
451
452
453 void GuiGraphics::updateAspectRatioStatus()
454 {
455         // keepaspectratio only makes sense if both a width _and_ a
456         // height are given, since its function is (see graphics manual):
457         // "If set to true then specifying both 'width' and 'height'
458         // (or 'totalheight') does not distort the figure but scales
459         // such that neither of the specified dimensions is _exceeded_."
460         aspectratio->setEnabled(
461                 WidthCB->isChecked() && !Width->text().isEmpty()
462                 && Width->text() != qt_(autostr)
463                 && HeightCB->isChecked() && !Height->text().isEmpty()
464                 && Height->text() != qt_(autostr)
465                 );
466         if (!aspectratio->isEnabled())
467                 aspectratio->setChecked(false);
468 }
469
470
471 void GuiGraphics::on_aspectratio_toggled(bool aspect_ratio)
472 {
473         if (aspect_ratio) {
474                 WidthCB->setText(qt_("Set max. &width:"));
475                 HeightCB->setText(qt_("Set max. &height:"));
476                 Width->setToolTip(qt_("Maximal width of image in output"));
477                 Height->setToolTip(qt_("Maximal height of image in output"));
478         } else {
479                 WidthCB->setText(qt_("Set &width:"));
480                 HeightCB->setText(qt_("Set &height:"));
481                 Width->setToolTip(qt_("Width of image in output"));
482                 Height->setToolTip(qt_("Height of image in output"));
483         }
484 }
485
486
487 void GuiGraphics::on_angle_textChanged(const QString & file_name)
488 {
489         rotateOrderCB->setEnabled((WidthCB->isChecked() ||
490                                  HeightCB->isChecked() ||
491                                  scaleCB->isChecked()) &&
492                                  (file_name != "0"));
493 }
494
495
496 void GuiGraphics::paramsToDialog(InsetGraphicsParams const & params)
497 {
498         static char const * const bb_units[] = { "bp", "cm", "mm", "in" };
499         static char const * const bb_units_gui[] = { N_("bp"), N_("cm"), N_("mm"), N_("in[[unit of measure]]") };
500         size_t const bb_size = sizeof(bb_units) / sizeof(bb_units[0]);
501
502         lbXunit->clear();
503         lbYunit->clear();
504         rtXunit->clear();
505         rtYunit->clear();
506
507         for (size_t i = 0; i < bb_size; i++) {
508                 lbXunit->addItem(qt_(bb_units_gui[i]),
509                         toqstr(bb_units[i]));
510                 lbYunit->addItem(qt_(bb_units_gui[i]),
511                         toqstr(bb_units[i]));
512                 rtXunit->addItem(qt_(bb_units_gui[i]),
513                         toqstr(bb_units[i]));
514                 rtYunit->addItem(qt_(bb_units_gui[i]),
515                         toqstr(bb_units[i]));
516         }
517
518         // set the right default unit
519         Length::UNIT const defaultUnit = Length::defaultUnit();
520
521         //lyxerr << bufferFilePath();
522         string const name =
523                 params.filename.outputFileName(fromqstr(bufferFilePath()));
524         filename->setText(toqstr(name));
525
526         // set the bounding box values
527         if (params.bbox.empty()) {
528                 string const bb = readBoundingBox(params.filename.absFileName());
529                 // the values from the file always have the bigpoint-unit bp
530                 doubleToWidget(lbX, token(bb, ' ', 0));
531                 doubleToWidget(lbY, token(bb, ' ', 1));
532                 doubleToWidget(rtX, token(bb, ' ', 2));
533                 doubleToWidget(rtY, token(bb, ' ', 3));
534                 lbXunit->setCurrentIndex(0);
535                 lbYunit->setCurrentIndex(0);
536                 rtXunit->setCurrentIndex(0);
537                 rtYunit->setCurrentIndex(0);
538                 bbChanged = false;
539         } else {
540                 // get the values from the inset
541                 doubleToWidget(lbX, params.bbox.xl.value());
542                 string unit = unit_name[params.bbox.xl.unit()];
543                 lbXunit->setCurrentIndex(lbXunit->findData(toqstr(unit)));
544                 doubleToWidget(lbY, params.bbox.yb.value());
545                 unit = unit_name[params.bbox.yb.unit()];
546                 lbYunit->setCurrentIndex(lbYunit->findData(toqstr(unit)));
547                 doubleToWidget(rtX, params.bbox.xr.value());
548                 unit = unit_name[params.bbox.xr.unit()];
549                 rtXunit->setCurrentIndex(rtXunit->findData(toqstr(unit)));
550                 doubleToWidget(rtY, params.bbox.yt.value());
551                 unit = unit_name[params.bbox.yt.unit()];
552                 rtYunit->setCurrentIndex(rtYunit->findData(toqstr(unit)));
553                 bbChanged = true;
554         }
555
556         // Update the draft and clip mode
557         draftCB->setChecked(params.draft);
558         clip->setChecked(params.clip);
559         darkModeCB->setChecked(params.darkModeSensitive);
560         displayGB->setChecked(params.display);
561         displayscale->setText(toqstr(convert<string>(params.lyxscale)));
562
563         // the output section (width/height)
564
565         doubleToWidget(Scale, params.scale);
566         //igp.scale defaults to 100, so we treat it as empty
567         bool const scaleChecked = !params.scale.empty() && params.scale != "100";
568         scaleCB->blockSignals(true);
569         scaleCB->setChecked(scaleChecked);
570         scaleCB->blockSignals(false);
571         Scale->setEnabled(scaleChecked);
572         displayGB->setEnabled(lyxrc.display_graphics);
573
574         set<string> grp;
575         graphics::getGraphicsGroups(buffer(), grp);
576         set<string>::const_iterator it = grp.begin();
577         set<string>::const_iterator end = grp.end();
578         groupCO->blockSignals(true);
579         groupCO->clear();
580         for (; it != end; ++it)
581                 groupCO->addItem(toqstr(*it), toqstr(*it));
582         groupCO->insertItem(0, qt_("None"), QString());
583         if (params.groupId.empty())
584                 groupCO->setCurrentIndex(0);
585         else
586                 groupCO->setCurrentIndex(
587                         groupCO->findData(toqstr(params.groupId), Qt::MatchExactly));
588         groupCO->blockSignals(false);
589
590         if (params.width.value() == 0)
591                 lengthToWidgets(Width, widthUnit, _(autostr), defaultUnit);
592         else
593                 lengthToWidgets(Width, widthUnit, params.width, defaultUnit);
594
595         bool const widthChecked = !Width->text().isEmpty() &&
596                 Width->text() != qt_(autostr);
597         WidthCB->blockSignals(true);
598         WidthCB->setChecked(widthChecked);
599         WidthCB->blockSignals(false);
600         Width->setEnabled(widthChecked);
601         widthUnit->setEnabled(widthChecked);
602
603         if (params.height.value() == 0)
604                 lengthToWidgets(Height, heightUnit, _(autostr), defaultUnit);
605         else
606                 lengthToWidgets(Height, heightUnit, params.height, defaultUnit);
607
608         bool const heightChecked = !Height->text().isEmpty()
609                 && Height->text() != qt_(autostr);
610         HeightCB->blockSignals(true);
611         HeightCB->setChecked(heightChecked);
612         HeightCB->blockSignals(false);
613         Height->setEnabled(heightChecked);
614         heightUnit->setEnabled(heightChecked);
615
616         scaleCB->setEnabled(!widthChecked && !heightChecked);
617         WidthCB->setEnabled(!scaleChecked);
618         HeightCB->setEnabled(!scaleChecked);
619
620         setAutoText();
621         updateAspectRatioStatus();
622
623         doubleToWidget(angle, params.rotateAngle);
624         rotateOrderCB->setChecked(params.scaleBeforeRotation);
625
626         rotateOrderCB->setEnabled( (widthChecked || heightChecked || scaleChecked)
627                 && params.rotateAngle != "0");
628
629         origin->clear();
630
631         for (size_t i = 0; i < rorigin_size; i++) {
632                 origin->addItem(qt_(rorigin_gui_strs[i]),
633                         toqstr(rorigin_lyx_strs[i]));
634         }
635
636         if (!params.rotateOrigin.empty())
637                 origin->setCurrentIndex(origin->findData(toqstr(params.rotateOrigin)));
638         else
639                 origin->setCurrentIndex(0);
640
641         // latex section
642         latexoptions->setText(toqstr(params.special));
643         // cf bug #3852
644         filename->setFocus();
645 }
646
647
648 void GuiGraphics::applyView()
649 {
650         InsetGraphicsParams & igp = params_;
651
652         igp.filename.set(fromqstr(filename->text()), fromqstr(bufferFilePath()));
653
654         // the bb section
655         igp.bbox = graphics::BoundingBox();
656         if (bbChanged) {
657                 string lbXs = widgetToDoubleStr(lbX);
658                 string lbYs = widgetToDoubleStr(lbY);
659                 string rtXs = widgetToDoubleStr(rtX);
660                 string rtYs = widgetToDoubleStr(rtY);
661                 int bb_sum =
662                         convert<int>(lbXs) + convert<int>(lbYs) +
663                         convert<int>(rtXs) + convert<int>(rtXs);
664                 if (bb_sum) {
665                         if (lbXs.empty())
666                                 lbXs = "0";
667                         igp.bbox.xl = Length(lbXs + fromqstr(lbXunit->currentText()));
668                         if (lbYs.empty())
669                                 lbYs = "0";
670                         igp.bbox.yb = Length(lbYs + fromqstr(lbYunit->currentText()));
671                         if (rtXs.empty())
672                                 rtXs = "0";
673                         igp.bbox.xr = Length(rtXs + fromqstr(rtXunit->currentText()));
674                         if (rtYs.empty())
675                                 rtYs = "0";
676                         igp.bbox.yt = Length(rtYs + fromqstr(rtYunit->currentText()));
677                 }
678         }
679
680         igp.draft = draftCB->isChecked();
681         igp.clip = clip->isChecked();
682         igp.display = displayGB->isChecked();
683         igp.darkModeSensitive = darkModeCB->isChecked();
684
685         //the graphics section
686         if (scaleCB->isChecked() && !Scale->text().isEmpty()) {
687                 igp.scale = widgetToDoubleStr(Scale);
688                 igp.width = Length("0pt");
689                 igp.height = Length("0pt");
690                 igp.keepAspectRatio = false;
691         } else {
692                 igp.scale = string();
693                 igp.width = WidthCB->isChecked() ?
694                         //Note that this works even if Width is "auto", since in
695                         //that case we get "0pt".
696                         Length(widgetsToLength(Width, widthUnit)):
697                         Length("0pt");
698                 igp.height = HeightCB->isChecked() ?
699                         Length(widgetsToLength(Height, heightUnit)) :
700                         Length("0pt");
701                 igp.keepAspectRatio = aspectratio->isChecked();
702         }
703
704         igp.lyxscale = displayscale->text().toInt();
705         igp.rotateAngle = widgetToDoubleStr(angle);
706
707         double rotAngle = widgetToDouble(angle);
708         if (abs(rotAngle) > 360.0) {
709                 rotAngle -= 360.0 * floor(rotAngle / 360.0);
710                 igp.rotateAngle = convert<string>(rotAngle);
711         }
712
713         // save the latex name for the origin. If it is the default
714         // then origin_ltx returns ""
715         igp.rotateOrigin =
716                 fromqstr(origin->itemData(origin->currentIndex()).toString());
717         igp.scaleBeforeRotation = rotateOrderCB->isChecked();
718
719         // more latex options
720         igp.special = fromqstr(latexoptions->text());
721
722         igp.groupId = fromqstr(groupCO->itemData(
723                 groupCO->currentIndex()).toString());
724         current_group_ = igp.groupId;
725 }
726
727
728 void GuiGraphics::getBB()
729 {
730         string const fn = fromqstr(filename->text());
731         if (fn.empty())
732                 return;
733         string const bb = readBoundingBox(fn);
734         bbChanged = false;
735         if (bb.empty())
736                 return;
737         doubleToWidget(lbX, token(bb, ' ', 0));
738         doubleToWidget(lbY, token(bb, ' ', 1));
739         doubleToWidget(rtX, token(bb, ' ', 2));
740         doubleToWidget(rtY, token(bb, ' ', 3));
741         // the default units for the bb values when reading
742         // it from the file
743         lbXunit->setCurrentIndex(0);
744         lbYunit->setCurrentIndex(0);
745         rtXunit->setCurrentIndex(0);
746         rtYunit->setCurrentIndex(0);
747 }
748
749
750 bool GuiGraphics::isChangedBB()
751 {
752         string const fn = fromqstr(filename->text());
753         if (fn.empty())
754                 return false;
755
756         string const bb = readBoundingBox(fn);
757         if (bb.empty())
758                 return false;
759
760         // Compare orig bb values with the set ones
761         if (Length(token(bb, ' ', 0) + "bp") !=
762                 Length(widgetToDoubleStr(lbX) + fromqstr(lbXunit->currentText())))
763                 return true;
764
765         if (Length(token(bb, ' ', 1) + "bp") !=
766                 Length(widgetToDoubleStr(lbY) + fromqstr(lbYunit->currentText())))
767                 return true;
768
769         if (Length(token(bb, ' ', 2) + "bp") !=
770                 Length(widgetToDoubleStr(rtX) + fromqstr(rtXunit->currentText())))
771                 return true;
772
773         if (Length(token(bb, ' ', 3) + "bp") !=
774                 Length(widgetToDoubleStr(rtY) + fromqstr(rtYunit->currentText())))
775                 return true;
776
777         return false;
778 }
779
780
781 bool GuiGraphics::isValid()
782 {
783         return !filename->text().isEmpty();
784 }
785
786
787 bool GuiGraphics::initialiseParams(string const & sdata)
788 {
789         InsetGraphics::string2params(sdata, buffer(), params_);
790         paramsToDialog(params_);
791         current_group_ = params_.groupId;
792         return true;
793 }
794
795
796 void GuiGraphics::clearParams()
797 {
798         params_ = InsetGraphicsParams();
799 }
800
801
802 void GuiGraphics::dispatchParams()
803 {
804         InsetGraphicsParams tmp_params(params_);
805         string const lfun = InsetGraphics::params2string(tmp_params, buffer());
806         dispatch(FuncRequest(getLfun(), lfun));
807         connectToNewInset();
808 }
809
810
811 QString GuiGraphics::browse(QString const & in_name) const
812 {
813         QString const title = qt_("Select graphics file");
814
815         // Does user clipart directory exist?
816         string clipdir = addName(package().user_support().absFileName(), "clipart");
817         FileName fclip(clipdir);
818
819         // bail out to system clipart directory
820         if (!fclip.isDirectory())
821                 clipdir = addName(package().system_support().absFileName(), "clipart");
822
823         return browseRelToParent(in_name, bufferFilePath(),
824                 title, fileFilters(QString()), false,
825                 qt_("&Clipart"), toqstr(clipdir),
826                 qt_("D&ocuments"), toqstr(lyxrc.document_path));
827 }
828
829
830 string GuiGraphics::readBoundingBox(string const & file)
831 {
832         FileName const abs_file = support::makeAbsPath(file, fromqstr(bufferFilePath()));
833
834         // With (E)PS files, try to get it from the file, if possible.
835         // Zipped files are unzipped in the readBB_from_PSFile-Function
836         string const bb = graphics::readBB_from_PSFile(abs_file);
837         if (!bb.empty())
838                 return bb;
839
840         // With other formats, we try to read the file dimensions
841         int width = 0;
842         int height = 0;
843
844         // First ask the Graphics Cache if it has loaded the file
845         graphics::Cache & gc = graphics::Cache::get();
846         if (gc.inCache(abs_file)) {
847                 graphics::Image const * image = gc.item(abs_file)->image();
848
849                 if (image) {
850                         width  = image->width();
851                         height = image->height();
852                 }
853         } else {
854                 // If not, construct a QImage and get the values from that
855                 QImage image(toqstr(abs_file.absoluteFilePath()));
856                 if (!image.isNull()) {
857                         width  = image.width();
858                         height = image.height();
859                 }
860         }
861
862         return ("0 0 " + convert<string>(width) + ' ' + convert<string>(height));
863 }
864
865
866 bool GuiGraphics::isFileNameValid(string const & fname) const
867 {
868         // It may be that the filename is relative.
869         return support::makeAbsPath(fname, fromqstr(bufferFilePath())).isReadableFile();
870 }
871
872
873 } // namespace frontend
874 } // namespace lyx
875
876 #include "moc_GuiGraphics.cpp"