]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiGraphics.cpp
Make code a bit easier to read
[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         // Add validated widgets to those that will be
228         // visually marked if invalid
229         bc().addCheckedLineEdit(Scale, scaleCB);
230         bc().addCheckedLineEdit(Width, WidthCB);
231         bc().addCheckedLineEdit(Height, HeightCB);
232         bc().addCheckedLineEdit(angle, angleL);
233         bc().addCheckedLineEdit(filename, filenameL);
234         bc().addCheckedLineEdit(displayscale, scaleLA);
235         bc().addCheckedLineEdit(lbX, xL);
236         bc().addCheckedLineEdit(lbY, yL);
237         bc().addCheckedLineEdit(rtX, xL_2);
238         bc().addCheckedLineEdit(rtY, yL_2);
239
240         // We also mark the tabs the widgets are in
241         int tabindex = tabWidget->indexOf(Graphics);
242         bc().addCheckedLineEdit(Scale, tabWidget, tabindex);
243         bc().addCheckedLineEdit(Width, tabWidget, tabindex);
244         bc().addCheckedLineEdit(Height, tabWidget, tabindex);
245         bc().addCheckedLineEdit(angle, tabWidget, tabindex);
246         bc().addCheckedLineEdit(filename, tabWidget, tabindex);
247         bc().addCheckedLineEdit(displayscale, tabWidget, tabWidget->indexOf(ExtraOptions));
248         tabindex = tabWidget->indexOf(Clipping);
249         bc().addCheckedLineEdit(lbX, tabWidget, tabindex);
250         bc().addCheckedLineEdit(lbY, tabWidget, tabindex);
251         bc().addCheckedLineEdit(rtX, tabWidget, tabindex);
252         bc().addCheckedLineEdit(rtY, tabWidget, tabindex);
253 }
254
255
256 void GuiGraphics::change_adaptor()
257 {
258         changed();
259 }
260
261
262 void GuiGraphics::changeGroup(int /* index */)
263 {
264         QString const new_group = groupCO->itemData(
265                 groupCO->currentIndex()).toString();
266
267         // check if the old group consisted only of this member
268         if (current_group_ != fromqstr(new_group)
269             && graphics::countGroupMembers(buffer(), current_group_) == 1) {
270                 if (!new_group.isEmpty()) {
271                         if (Alert::prompt(_("Dissolve previous group?"),
272                                 bformat(_("If you assign this graphic to group '%2$s',\n"
273                                           "the previously assigned group '%1$s' will be dissolved,\n"
274                                           "because this graphic was its only member.\n"
275                                           "How do you want to proceed?"),
276                                         from_utf8(current_group_), qstring_to_ucs4(new_group)),
277                                         0, 0,
278                                         bformat(_("Stick with group '%1$s'"),
279                                                 from_utf8(current_group_)),
280                                         bformat(_("Assign to group '%1$s' anyway"),
281                                                 qstring_to_ucs4(new_group))) == 0) {
282                                 groupCO->setCurrentIndex(
283                                         groupCO->findData(toqstr(current_group_), Qt::MatchExactly));
284                                 return;
285                         }
286                 } else {
287                         if (Alert::prompt(_("Dissolve previous group?"),
288                         bformat(_("If you sign off this graphic from group '%1$s',\n"
289                                   "the group will be dissolved,\n"
290                                   "because this graphic was its only member.\n"
291                                   "How do you want to proceed?"),
292                                 from_utf8(current_group_)),
293                                 0, 0,
294                                 bformat(_("Stick with group '%1$s'"),
295                                 from_utf8(current_group_)),
296                                 bformat(_("Sign off from group '%1$s'"),
297                                 from_utf8(current_group_))) == 0) {
298                         groupCO->setCurrentIndex(
299                                 groupCO->findData(toqstr(current_group_), Qt::MatchExactly));
300                         return;
301                         }
302                 }
303         }
304
305         if (new_group.isEmpty()) {
306                 changed();
307                 return;
308         }
309
310         string grp = graphics::getGroupParams(buffer(), fromqstr(new_group));
311         if (grp.empty()) {
312                 // group does not exist yet
313                 changed();
314                 return;
315         }
316
317         // filename might have been changed
318         QString current_filename = filename->text();
319
320         // group exists: load params into the dialog
321         groupCO->blockSignals(true);
322         InsetGraphics::string2params(grp, buffer(), params_);
323         paramsToDialog(params_);
324         groupCO->blockSignals(false);
325
326         // reset filename
327         filename->setText(current_filename);
328
329         changed();
330 }
331
332
333 void GuiGraphics::on_newGroupPB_clicked()
334 {
335         docstring newgroup;
336         if (!Alert::askForText(newgroup, _("Enter unique group name:")))
337                 return;
338         if (newgroup.empty())
339                 return;
340         if (groupCO->findData(toqstr(newgroup), Qt::MatchExactly) != -1) {
341                 Alert::warning(_("Group already defined!"),
342                         bformat(_("A graphics group with the name '%1$s' already exists."),
343                                 newgroup));
344                 return;
345         }
346         groupCO->addItem(toqstr(newgroup), toqstr(newgroup));
347         groupCO->setCurrentIndex(
348                 groupCO->findData(toqstr(newgroup), Qt::MatchExactly));
349 }
350
351
352 void GuiGraphics::changeBB()
353 {
354         bbChanged = isChangedBB();
355         getPB->setEnabled(bbChanged);
356         LYXERR(Debug::GRAPHICS, "[bb_Changed set to " << bbChanged << "]");
357         changed();
358 }
359
360
361 void GuiGraphics::on_browsePB_clicked()
362 {
363         QString const str = browse(filename->text());
364         if (!str.isEmpty()) {
365                 filename->setText(str);
366                 // read in the bb values of the new file
367                 // if there was no explicit custom viewport
368                 if (!bbChanged)
369                         getBB();
370                 changed();
371         }
372 }
373
374
375 void GuiGraphics::on_getPB_clicked()
376 {
377         getBB();
378         bbChanged = false;
379 }
380
381
382 void GuiGraphics::setAutoText()
383 {
384         if (scaleCB->isChecked())
385                 return;
386         if (!Scale->isEnabled() && Scale->text() != "100")
387                 Scale->setText("100");
388
389         setAutoTextCB(WidthCB, Width, widthUnit);
390         setAutoTextCB(HeightCB, Height, heightUnit);
391 }
392
393
394 void GuiGraphics::on_scaleCB_toggled(bool setScale)
395 {
396         Scale->setEnabled(setScale);
397         if (setScale) {
398                 Scale->setText("100");
399                 Scale->setFocus(Qt::OtherFocusReason);
400         }
401
402         WidthCB->setDisabled(setScale);
403         WidthCB->blockSignals(true);
404         WidthCB->setChecked(false);
405         WidthCB->blockSignals(false);
406         Width->setEnabled(false);
407         widthUnit->setEnabled(false);
408
409         HeightCB->setDisabled(setScale);
410         HeightCB->blockSignals(true);
411         HeightCB->setChecked(false);
412         HeightCB->blockSignals(false);
413         Height->setEnabled(false);
414         heightUnit->setEnabled(false);
415
416         rotateOrderCB->setEnabled((WidthCB->isChecked() ||
417                                  HeightCB->isChecked() ||
418                                  scaleCB->isChecked()) &&
419                                  (angle->text() != "0"));
420
421         setAutoText();
422         updateAspectRatioStatus();
423 }
424
425
426 void GuiGraphics::on_WidthCB_toggled(bool setWidth)
427 {
428         Width->setEnabled(setWidth);
429         widthUnit->setEnabled(setWidth);
430         if (setWidth)
431                 Width->setFocus(Qt::OtherFocusReason);
432
433         bool const setHeight = HeightCB->isChecked();
434         scaleCB->setEnabled(!setWidth && !setHeight);
435         //already will be unchecked, so don't need to do that
436         Scale->setEnabled((!setWidth && !setHeight) //=scaleCB->isEnabled()
437                         && scaleCB->isChecked()); //should be false, but let's check
438         rotateOrderCB->setEnabled((setWidth || setHeight ||
439                                  scaleCB->isChecked()) &&
440                                  (angle->text() != "0"));
441
442         setAutoText();
443         updateAspectRatioStatus();
444 }
445
446
447 void GuiGraphics::on_HeightCB_toggled(bool setHeight)
448 {
449         Height->setEnabled(setHeight);
450         heightUnit->setEnabled(setHeight);
451         if (setHeight)
452                 Height->setFocus(Qt::OtherFocusReason);
453
454         bool const setWidth = WidthCB->isChecked();
455         scaleCB->setEnabled(!setWidth && !setHeight);
456         //already unchecked
457         Scale->setEnabled((!setWidth && !setHeight) //=scaleCB->isEnabled()
458                 && scaleCB->isChecked()); //should be false
459         rotateOrderCB->setEnabled((setWidth || setHeight ||
460                                  scaleCB->isChecked()) &&
461                                  (angle->text() != "0"));
462
463         setAutoText();
464         updateAspectRatioStatus();
465 }
466
467
468 void GuiGraphics::updateAspectRatioStatus()
469 {
470         // keepaspectratio only makes sense if both a width _and_ a
471         // height are given, since its function is (see graphics manual):
472         // "If set to true then specifying both 'width' and 'height'
473         // (or 'totalheight') does not distort the figure but scales
474         // such that neither of the specified dimensions is _exceeded_."
475         aspectratio->setEnabled(
476                 WidthCB->isChecked() && !Width->text().isEmpty()
477                 && Width->text() != qt_(autostr)
478                 && HeightCB->isChecked() && !Height->text().isEmpty()
479                 && Height->text() != qt_(autostr)
480                 );
481         if (!aspectratio->isEnabled())
482                 aspectratio->setChecked(false);
483 }
484
485
486 void GuiGraphics::on_aspectratio_toggled(bool aspect_ratio)
487 {
488         if (aspect_ratio) {
489                 WidthCB->setText(qt_("Set max. &width:"));
490                 HeightCB->setText(qt_("Set max. &height:"));
491                 Width->setToolTip(qt_("Maximal width of image in output"));
492                 Height->setToolTip(qt_("Maximal height of image in output"));
493         } else {
494                 WidthCB->setText(qt_("Set &width:"));
495                 HeightCB->setText(qt_("Set &height:"));
496                 Width->setToolTip(qt_("Width of image in output"));
497                 Height->setToolTip(qt_("Height of image in output"));
498         }
499 }
500
501
502 void GuiGraphics::on_angle_textChanged(const QString & file_name)
503 {
504         rotateOrderCB->setEnabled((WidthCB->isChecked() ||
505                                  HeightCB->isChecked() ||
506                                  scaleCB->isChecked()) &&
507                                  (file_name != "0"));
508 }
509
510
511 void GuiGraphics::paramsToDialog(InsetGraphicsParams const & params)
512 {
513         static char const * const bb_units[] = { "bp", "cm", "mm", "in" };
514         static char const * const bb_units_gui[] = { N_("bp"), N_("cm"), N_("mm"), N_("in[[unit of measure]]") };
515         size_t const bb_size = sizeof(bb_units) / sizeof(bb_units[0]);
516
517         lbXunit->clear();
518         lbYunit->clear();
519         rtXunit->clear();
520         rtYunit->clear();
521
522         for (size_t i = 0; i < bb_size; i++) {
523                 lbXunit->addItem(qt_(bb_units_gui[i]),
524                         toqstr(bb_units[i]));
525                 lbYunit->addItem(qt_(bb_units_gui[i]),
526                         toqstr(bb_units[i]));
527                 rtXunit->addItem(qt_(bb_units_gui[i]),
528                         toqstr(bb_units[i]));
529                 rtYunit->addItem(qt_(bb_units_gui[i]),
530                         toqstr(bb_units[i]));
531         }
532
533         // set the right default unit
534         Length::UNIT const defaultUnit = Length::defaultUnit();
535
536         //lyxerr << bufferFilePath();
537         string const name =
538                 params.filename.outputFileName(fromqstr(bufferFilePath()));
539         filename->setText(toqstr(name));
540
541         // set the bounding box values
542         if (params.bbox.empty()) {
543                 string const bb = readBoundingBox(params.filename.absFileName());
544                 // the values from the file always have the bigpoint-unit bp
545                 doubleToWidget(lbX, token(bb, ' ', 0));
546                 doubleToWidget(lbY, token(bb, ' ', 1));
547                 doubleToWidget(rtX, token(bb, ' ', 2));
548                 doubleToWidget(rtY, token(bb, ' ', 3));
549                 lbXunit->setCurrentIndex(0);
550                 lbYunit->setCurrentIndex(0);
551                 rtXunit->setCurrentIndex(0);
552                 rtYunit->setCurrentIndex(0);
553                 bbChanged = false;
554         } else {
555                 // get the values from the inset
556                 doubleToWidget(lbX, params.bbox.xl.value());
557                 string unit = unit_name[params.bbox.xl.unit()];
558                 lbXunit->setCurrentIndex(lbXunit->findData(toqstr(unit)));
559                 doubleToWidget(lbY, params.bbox.yb.value());
560                 unit = unit_name[params.bbox.yb.unit()];
561                 lbYunit->setCurrentIndex(lbYunit->findData(toqstr(unit)));
562                 doubleToWidget(rtX, params.bbox.xr.value());
563                 unit = unit_name[params.bbox.xr.unit()];
564                 rtXunit->setCurrentIndex(rtXunit->findData(toqstr(unit)));
565                 doubleToWidget(rtY, params.bbox.yt.value());
566                 unit = unit_name[params.bbox.yt.unit()];
567                 rtYunit->setCurrentIndex(rtYunit->findData(toqstr(unit)));
568                 bbChanged = true;
569         }
570
571         // Update the draft and clip mode
572         draftCB->setChecked(params.draft);
573         clip->setChecked(params.clip);
574         darkModeCB->setChecked(params.darkModeSensitive);
575         displayGB->setChecked(params.display);
576         displayscale->setText(toqstr(convert<string>(params.lyxscale)));
577
578         // the output section (width/height)
579
580         doubleToWidget(Scale, params.scale);
581         //igp.scale defaults to 100, so we treat it as empty
582         bool const scaleChecked = !params.scale.empty() && params.scale != "100";
583         scaleCB->blockSignals(true);
584         scaleCB->setChecked(scaleChecked);
585         scaleCB->blockSignals(false);
586         Scale->setEnabled(scaleChecked);
587         displayGB->setEnabled(lyxrc.display_graphics);
588
589         set<string> grp;
590         graphics::getGraphicsGroups(buffer(), grp);
591         set<string>::const_iterator it = grp.begin();
592         set<string>::const_iterator end = grp.end();
593         groupCO->blockSignals(true);
594         groupCO->clear();
595         for (; it != end; ++it)
596                 groupCO->addItem(toqstr(*it), toqstr(*it));
597         groupCO->insertItem(0, qt_("None"), QString());
598         if (params.groupId.empty())
599                 groupCO->setCurrentIndex(0);
600         else
601                 groupCO->setCurrentIndex(
602                         groupCO->findData(toqstr(params.groupId), Qt::MatchExactly));
603         groupCO->blockSignals(false);
604
605         if (params.width.value() == 0)
606                 lengthToWidgets(Width, widthUnit, _(autostr), defaultUnit);
607         else
608                 lengthToWidgets(Width, widthUnit, params.width, defaultUnit);
609
610         bool const widthChecked = !Width->text().isEmpty() &&
611                 Width->text() != qt_(autostr);
612         WidthCB->blockSignals(true);
613         WidthCB->setChecked(widthChecked);
614         WidthCB->blockSignals(false);
615         Width->setEnabled(widthChecked);
616         widthUnit->setEnabled(widthChecked);
617
618         if (params.height.value() == 0)
619                 lengthToWidgets(Height, heightUnit, _(autostr), defaultUnit);
620         else
621                 lengthToWidgets(Height, heightUnit, params.height, defaultUnit);
622
623         bool const heightChecked = !Height->text().isEmpty()
624                 && Height->text() != qt_(autostr);
625         HeightCB->blockSignals(true);
626         HeightCB->setChecked(heightChecked);
627         HeightCB->blockSignals(false);
628         Height->setEnabled(heightChecked);
629         heightUnit->setEnabled(heightChecked);
630
631         scaleCB->setEnabled(!widthChecked && !heightChecked);
632         WidthCB->setEnabled(!scaleChecked);
633         HeightCB->setEnabled(!scaleChecked);
634
635         setAutoText();
636         updateAspectRatioStatus();
637
638         doubleToWidget(angle, params.rotateAngle);
639         rotateOrderCB->setChecked(params.scaleBeforeRotation);
640
641         rotateOrderCB->setEnabled( (widthChecked || heightChecked || scaleChecked)
642                 && params.rotateAngle != "0");
643
644         origin->clear();
645
646         for (size_t i = 0; i < rorigin_size; i++) {
647                 origin->addItem(qt_(rorigin_gui_strs[i]),
648                         toqstr(rorigin_lyx_strs[i]));
649         }
650
651         if (!params.rotateOrigin.empty())
652                 origin->setCurrentIndex(origin->findData(toqstr(params.rotateOrigin)));
653         else
654                 origin->setCurrentIndex(0);
655
656         // latex section
657         latexoptions->setText(toqstr(params.special));
658         // cf bug #3852
659         filename->setFocus();
660 }
661
662
663 void GuiGraphics::applyView()
664 {
665         InsetGraphicsParams & igp = params_;
666
667         igp.filename.set(fromqstr(filename->text()), fromqstr(bufferFilePath()));
668
669         // the bb section
670         igp.bbox = graphics::BoundingBox();
671         if (bbChanged) {
672                 string lbXs = widgetToDoubleStr(lbX);
673                 string lbYs = widgetToDoubleStr(lbY);
674                 string rtXs = widgetToDoubleStr(rtX);
675                 string rtYs = widgetToDoubleStr(rtY);
676                 int bb_sum =
677                         convert<int>(lbXs) + convert<int>(lbYs) +
678                         convert<int>(rtXs) + convert<int>(rtXs);
679                 if (bb_sum) {
680                         if (lbXs.empty())
681                                 lbXs = "0";
682                         igp.bbox.xl = Length(lbXs + fromqstr(lbXunit->currentText()));
683                         if (lbYs.empty())
684                                 lbYs = "0";
685                         igp.bbox.yb = Length(lbYs + fromqstr(lbYunit->currentText()));
686                         if (rtXs.empty())
687                                 rtXs = "0";
688                         igp.bbox.xr = Length(rtXs + fromqstr(rtXunit->currentText()));
689                         if (rtYs.empty())
690                                 rtYs = "0";
691                         igp.bbox.yt = Length(rtYs + fromqstr(rtYunit->currentText()));
692                 }
693         }
694
695         igp.draft = draftCB->isChecked();
696         igp.clip = clip->isChecked();
697         igp.display = displayGB->isChecked();
698         igp.darkModeSensitive = darkModeCB->isChecked();
699
700         //the graphics section
701         if (scaleCB->isChecked() && !Scale->text().isEmpty()) {
702                 igp.scale = widgetToDoubleStr(Scale);
703                 igp.width = Length("0pt");
704                 igp.height = Length("0pt");
705                 igp.keepAspectRatio = false;
706         } else {
707                 igp.scale = string();
708                 igp.width = WidthCB->isChecked() ?
709                         //Note that this works even if Width is "auto", since in
710                         //that case we get "0pt".
711                         Length(widgetsToLength(Width, widthUnit)):
712                         Length("0pt");
713                 igp.height = HeightCB->isChecked() ?
714                         Length(widgetsToLength(Height, heightUnit)) :
715                         Length("0pt");
716                 igp.keepAspectRatio = aspectratio->isChecked();
717         }
718
719         igp.lyxscale = displayscale->text().toInt();
720         igp.rotateAngle = widgetToDoubleStr(angle);
721
722         double rotAngle = widgetToDouble(angle);
723         if (abs(rotAngle) > 360.0) {
724                 rotAngle -= 360.0 * floor(rotAngle / 360.0);
725                 igp.rotateAngle = convert<string>(rotAngle);
726         }
727
728         // save the latex name for the origin. If it is the default
729         // then origin_ltx returns ""
730         igp.rotateOrigin =
731                 fromqstr(origin->itemData(origin->currentIndex()).toString());
732         igp.scaleBeforeRotation = rotateOrderCB->isChecked();
733
734         // more latex options
735         igp.special = fromqstr(latexoptions->text());
736
737         igp.groupId = fromqstr(groupCO->itemData(
738                 groupCO->currentIndex()).toString());
739         current_group_ = igp.groupId;
740 }
741
742
743 void GuiGraphics::getBB()
744 {
745         string const fn = fromqstr(filename->text());
746         if (fn.empty())
747                 return;
748         string const bb = readBoundingBox(fn);
749         bbChanged = false;
750         if (bb.empty())
751                 return;
752         doubleToWidget(lbX, token(bb, ' ', 0));
753         doubleToWidget(lbY, token(bb, ' ', 1));
754         doubleToWidget(rtX, token(bb, ' ', 2));
755         doubleToWidget(rtY, token(bb, ' ', 3));
756         // the default units for the bb values when reading
757         // it from the file
758         lbXunit->setCurrentIndex(0);
759         lbYunit->setCurrentIndex(0);
760         rtXunit->setCurrentIndex(0);
761         rtYunit->setCurrentIndex(0);
762 }
763
764
765 bool GuiGraphics::isChangedBB()
766 {
767         string const fn = fromqstr(filename->text());
768         if (fn.empty())
769                 return false;
770
771         string const bb = readBoundingBox(fn);
772         if (bb.empty())
773                 return false;
774
775         // Compare orig bb values with the set ones
776         if (Length(token(bb, ' ', 0) + "bp") !=
777                 Length(widgetToDoubleStr(lbX) + fromqstr(lbXunit->currentText())))
778                 return true;
779
780         if (Length(token(bb, ' ', 1) + "bp") !=
781                 Length(widgetToDoubleStr(lbY) + fromqstr(lbYunit->currentText())))
782                 return true;
783
784         if (Length(token(bb, ' ', 2) + "bp") !=
785                 Length(widgetToDoubleStr(rtX) + fromqstr(rtXunit->currentText())))
786                 return true;
787
788         if (Length(token(bb, ' ', 3) + "bp") !=
789                 Length(widgetToDoubleStr(rtY) + fromqstr(rtYunit->currentText())))
790                 return true;
791
792         return false;
793 }
794
795
796 bool GuiGraphics::isValid()
797 {
798         return !filename->text().isEmpty();
799 }
800
801
802 bool GuiGraphics::initialiseParams(string const & sdata)
803 {
804         InsetGraphics::string2params(sdata, buffer(), params_);
805         paramsToDialog(params_);
806         current_group_ = params_.groupId;
807         return true;
808 }
809
810
811 void GuiGraphics::clearParams()
812 {
813         params_ = InsetGraphicsParams();
814 }
815
816
817 void GuiGraphics::dispatchParams()
818 {
819         InsetGraphicsParams tmp_params(params_);
820         string const lfun = InsetGraphics::params2string(tmp_params, buffer());
821         dispatch(FuncRequest(getLfun(), lfun));
822         connectToNewInset();
823 }
824
825
826 QString GuiGraphics::browse(QString const & in_name)
827 {
828         QString const title = qt_("Select graphics file");
829
830         // Does user clipart directory exist?
831         string clipdir = addName(package().user_support().absFileName(), "clipart");
832         FileName fclip(clipdir);
833
834         // bail out to system clipart directory
835         if (!fclip.isDirectory())
836                 clipdir = addName(package().system_support().absFileName(), "clipart");
837
838         return browseRelToParent(in_name, bufferFilePath(),
839                 title, fileFilters(QString()), false,
840                 qt_("&Clipart"), toqstr(clipdir),
841                 qt_("D&ocuments"), toqstr(lyxrc.document_path));
842 }
843
844
845 string GuiGraphics::readBoundingBox(string const & file)
846 {
847         FileName const abs_file = support::makeAbsPath(file, fromqstr(bufferFilePath()));
848
849         // With (E)PS files, try to get it from the file, if possible.
850         // Zipped files are unzipped in the readBB_from_PSFile-Function
851         string const bb = graphics::readBB_from_PSFile(abs_file);
852         if (!bb.empty())
853                 return bb;
854
855         // With other formats, we try to read the file dimensions
856         int width = 0;
857         int height = 0;
858
859         // First ask the Graphics Cache if it has loaded the file
860         graphics::Cache & gc = graphics::Cache::get();
861         if (gc.inCache(abs_file)) {
862                 graphics::Image const * image = gc.item(abs_file)->image();
863
864                 if (image) {
865                         width  = image->width();
866                         height = image->height();
867                 }
868         } else {
869                 // If not, construct a QImage and get the values from that
870                 QImage image(toqstr(abs_file.absoluteFilePath()));
871                 if (!image.isNull()) {
872                         width  = image.width();
873                         height = image.height();
874                 }
875         }
876
877         return ("0 0 " + convert<string>(width) + ' ' + convert<string>(height));
878 }
879
880
881 bool GuiGraphics::isFileNameValid(string const & fname) const
882 {
883         // It may be that the filename is relative.
884         return support::makeAbsPath(fname, fromqstr(bufferFilePath())).isReadableFile();
885 }
886
887
888 } // namespace frontend
889 } // namespace lyx
890
891 #include "moc_GuiGraphics.cpp"