Coverage Report

Created: 2026-10-14 09:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libreoffice/sc/source/ui/miscdlgs/optsolver.cxx
Line
Count
Source
1
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
/*
3
 * This file is part of the LibreOffice project.
4
 *
5
 * This Source Code Form is subject to the terms of the Mozilla Public
6
 * License, v. 2.0. If a copy of the MPL was not distributed with this
7
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8
 *
9
 * This file incorporates work covered by the following license notice:
10
 *
11
 *   Licensed to the Apache Software Foundation (ASF) under one or more
12
 *   contributor license agreements. See the NOTICE file distributed
13
 *   with this work for additional information regarding copyright
14
 *   ownership. The ASF licenses this file to you under the Apache
15
 *   License, Version 2.0 (the "License"); you may not use this file
16
 *   except in compliance with the License. You may obtain a copy of
17
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
18
 */
19
20
#include <rangelst.hxx>
21
#include <sfx2/bindings.hxx>
22
#include <svl/numformat.hxx>
23
#include <utility>
24
#include <vcl/commandinfoprovider.hxx>
25
#include <vcl/weld/Dialog.hxx>
26
#include <vcl/weld/MessageDialog.hxx>
27
#include <vcl/svapp.hxx>
28
29
#include <reffact.hxx>
30
#include <docsh.hxx>
31
#include <docfunc.hxx>
32
#include <rangeutl.hxx>
33
#include <convuno.hxx>
34
#include <unonames.hxx>
35
#include <solveroptions.hxx>
36
#include <solverutil.hxx>
37
#include <globstr.hrc>
38
#include <scresid.hxx>
39
#include <comphelper/sequence.hxx>
40
#include <optsolver.hxx>
41
#include <table.hxx>
42
#include <TableFillingAndNavigationTools.hxx>
43
#include <tabvwsh.hxx>
44
45
#include <com/sun/star/beans/XPropertySetInfo.hpp>
46
#include <com/sun/star/sheet/SolverConstraint.hpp>
47
#include <com/sun/star/sheet/SolverConstraintOperator.hpp>
48
#include <com/sun/star/sheet/XSolverDescription.hpp>
49
#include <com/sun/star/sheet/XSolver.hpp>
50
#include <com/sun/star/sheet/SensitivityReport.hpp>
51
52
using namespace com::sun::star;
53
54
ScSolverProgressDialog::ScSolverProgressDialog(weld::Window* pParent)
55
0
    : GenericDialogController(pParent, u"modules/scalc/ui/solverprogressdialog.ui"_ustr,
56
0
                              u"SolverProgressDialog"_ustr)
57
0
    , m_xFtTime(m_xBuilder->weld_label(u"progress"_ustr))
58
0
{
59
0
}
60
61
ScSolverProgressDialog::~ScSolverProgressDialog()
62
0
{
63
0
}
64
65
void ScSolverProgressDialog::HideTimeLimit()
66
0
{
67
0
    m_xFtTime->hide();
68
0
}
69
70
void ScSolverProgressDialog::SetTimeLimit( sal_Int32 nSeconds )
71
0
{
72
0
    OUString aOld = m_xFtTime->get_label();
73
0
    OUString aNew = aOld.replaceFirst("#", OUString::number(nSeconds));
74
0
    m_xFtTime->set_label(aNew);
75
0
}
76
77
ScSolverNoSolutionDialog::ScSolverNoSolutionDialog(weld::Window* pParent, const OUString& rErrorText)
78
0
    : GenericDialogController(pParent, u"modules/scalc/ui/nosolutiondialog.ui"_ustr, u"NoSolutionDialog"_ustr)
79
0
    , m_xFtErrorText(m_xBuilder->weld_label(u"error"_ustr))
80
0
{
81
0
    m_xFtErrorText->set_label(rErrorText);
82
0
}
83
84
ScSolverNoSolutionDialog::~ScSolverNoSolutionDialog()
85
0
{
86
0
}
87
88
ScSolverSuccessDialog::ScSolverSuccessDialog(weld::Window* pParent, std::u16string_view rSolution)
89
0
    : GenericDialogController(pParent, u"modules/scalc/ui/solversuccessdialog.ui"_ustr, u"SolverSuccessDialog"_ustr)
90
0
    , m_xFtResult(m_xBuilder->weld_label(u"result"_ustr))
91
0
    , m_xBtnOk(m_xBuilder->weld_button(u"ok"_ustr))
92
0
    , m_xBtnCancel(m_xBuilder->weld_button(u"cancel"_ustr))
93
0
{
94
0
    m_xBtnOk->connect_clicked(LINK(this, ScSolverSuccessDialog, ClickHdl));
95
0
    m_xBtnCancel->connect_clicked(LINK(this, ScSolverSuccessDialog, ClickHdl));
96
0
    OUString aMessage = m_xFtResult->get_label() + " " + rSolution;
97
0
    m_xFtResult->set_label(aMessage);
98
0
}
99
100
ScSolverSuccessDialog::~ScSolverSuccessDialog()
101
0
{
102
0
}
103
104
IMPL_LINK(ScSolverSuccessDialog, ClickHdl, weld::Button&, rBtn, void)
105
0
{
106
0
    if (&rBtn == m_xBtnOk.get())
107
0
        m_xDialog->response(RET_OK);
108
0
    else
109
0
        m_xDialog->response(RET_CANCEL);
110
0
}
111
112
ScCursorRefEdit::ScCursorRefEdit(std::unique_ptr<weld::Entry> xControl)
113
0
    : formula::RefEdit(std::move(xControl))
114
0
{
115
0
    mxEntry->connect_key_press(Link<const KeyEvent&, bool>()); //acknowledge we first remove the old one
116
0
    mxEntry->connect_key_press(LINK(this, ScCursorRefEdit, KeyInputHdl));
117
0
}
118
119
void ScCursorRefEdit::SetCursorLinks( const Link<ScCursorRefEdit&,void>& rUp, const Link<ScCursorRefEdit&,void>& rDown )
120
0
{
121
0
    maCursorUpLink = rUp;
122
0
    maCursorDownLink = rDown;
123
0
}
124
125
IMPL_LINK(ScCursorRefEdit, KeyInputHdl, const KeyEvent&, rKEvt, bool)
126
0
{
127
0
    vcl::KeyCode aCode = rKEvt.GetKeyCode();
128
0
    bool bUp = (aCode.GetCode() == KEY_UP);
129
0
    bool bDown = (aCode.GetCode() == KEY_DOWN);
130
0
    if ( !aCode.IsShift() && !aCode.IsMod1() && !aCode.IsMod2() && ( bUp || bDown ) )
131
0
    {
132
0
        if ( bUp )
133
0
            maCursorUpLink.Call( *this );
134
0
        else
135
0
            maCursorDownLink.Call( *this );
136
0
        return true;
137
0
    }
138
0
    return formula::RefEdit::KeyInput(rKEvt);
139
0
}
140
141
ScOptSolverDlg::ScOptSolverDlg(SfxBindings* pB, SfxChildWindow* pCW, weld::Window* pParent,
142
                               ScDocShell* pDocSh, const ScAddress& aCursorPos)
143
0
    : ScAnyRefDlgController(pB, pCW, pParent, u"modules/scalc/ui/solverdlg.ui"_ustr, u"SolverDialog"_ustr)
144
0
    , maInputError(ScResId(STR_INVALIDINPUT))
145
0
    , maConditionError(ScResId(STR_INVALIDCONDITION))
146
147
0
    , mpDocShell(pDocSh)
148
0
    , mrDoc(pDocSh->GetDocument())
149
0
    , mnCurTab(aCursorPos.Tab())
150
0
    , mbDlgLostFocus(false)
151
0
    , nScrollPos(0)
152
0
    , mpEdActive(nullptr)
153
0
    , m_xFtObjectiveCell(m_xBuilder->weld_label(u"targetlabel"_ustr))
154
0
    , m_xEdObjectiveCell(new formula::RefEdit(m_xBuilder->weld_entry(u"targetedit"_ustr)))
155
0
    , m_xRBObjectiveCell(new formula::RefButton(m_xBuilder->weld_button(u"targetbutton"_ustr)))
156
0
    , m_xRbMax(m_xBuilder->weld_radio_button(u"max"_ustr))
157
0
    , m_xRbMin(m_xBuilder->weld_radio_button(u"min"_ustr))
158
0
    , m_xRbValue(m_xBuilder->weld_radio_button(u"value"_ustr))
159
0
    , m_xEdTargetValue(new formula::RefEdit(m_xBuilder->weld_entry(u"valueedit"_ustr)))
160
0
    , m_xRBTargetValue(new formula::RefButton(m_xBuilder->weld_button(u"valuebutton"_ustr)))
161
0
    , m_xFtVariableCells(m_xBuilder->weld_label(u"changelabel"_ustr))
162
0
    , m_xEdVariableCells(new formula::RefEdit(m_xBuilder->weld_entry(u"changeedit"_ustr)))
163
0
    , m_xRBVariableCells(new formula::RefButton(m_xBuilder->weld_button(u"changebutton"_ustr)))
164
0
    , m_xFtCellRef(m_xBuilder->weld_label(u"cellreflabel"_ustr))
165
0
    , m_xEdLeft1(new ScCursorRefEdit(m_xBuilder->weld_entry(u"ref1edit"_ustr)))
166
0
    , m_xRBLeft1(new formula::RefButton(m_xBuilder->weld_button(u"ref1button"_ustr)))
167
0
    , m_xLbOp1(m_xBuilder->weld_combo_box(u"op1list"_ustr))
168
0
    , m_xFtConstraint(m_xBuilder->weld_label(u"constraintlabel"_ustr))
169
0
    , m_xEdRight1(new ScCursorRefEdit(m_xBuilder->weld_entry(u"val1edit"_ustr)))
170
0
    , m_xRBRight1(new formula::RefButton(m_xBuilder->weld_button(u"val1button"_ustr)))
171
0
    , m_xBtnDel1(m_xBuilder->weld_button(u"del1"_ustr))
172
0
    , m_xEdLeft2(new ScCursorRefEdit(m_xBuilder->weld_entry(u"ref2edit"_ustr)))
173
0
    , m_xRBLeft2(new formula::RefButton(m_xBuilder->weld_button(u"ref2button"_ustr)))
174
0
    , m_xLbOp2(m_xBuilder->weld_combo_box(u"op2list"_ustr))
175
0
    , m_xEdRight2(new ScCursorRefEdit(m_xBuilder->weld_entry(u"val2edit"_ustr)))
176
0
    , m_xRBRight2(new formula::RefButton(m_xBuilder->weld_button(u"val2button"_ustr)))
177
0
    , m_xBtnDel2(m_xBuilder->weld_button(u"del2"_ustr))
178
0
    , m_xEdLeft3(new ScCursorRefEdit(m_xBuilder->weld_entry(u"ref3edit"_ustr)))
179
0
    , m_xRBLeft3(new formula::RefButton(m_xBuilder->weld_button(u"ref3button"_ustr)))
180
0
    , m_xLbOp3(m_xBuilder->weld_combo_box(u"op3list"_ustr))
181
0
    , m_xEdRight3(new ScCursorRefEdit(m_xBuilder->weld_entry(u"val3edit"_ustr)))
182
0
    , m_xRBRight3(new formula::RefButton(m_xBuilder->weld_button(u"val3button"_ustr)))
183
0
    , m_xBtnDel3(m_xBuilder->weld_button(u"del3"_ustr))
184
0
    , m_xEdLeft4(new ScCursorRefEdit(m_xBuilder->weld_entry(u"ref4edit"_ustr)))
185
0
    , m_xRBLeft4(new formula::RefButton(m_xBuilder->weld_button(u"ref4button"_ustr)))
186
0
    , m_xLbOp4(m_xBuilder->weld_combo_box(u"op4list"_ustr))
187
0
    , m_xEdRight4(new ScCursorRefEdit(m_xBuilder->weld_entry(u"val4edit"_ustr)))
188
0
    , m_xRBRight4(new formula::RefButton(m_xBuilder->weld_button(u"val4button"_ustr)))
189
0
    , m_xBtnDel4(m_xBuilder->weld_button(u"del4"_ustr))
190
0
    , m_xScrollBar(m_xBuilder->weld_scrolled_window(u"scrollbar"_ustr, true))
191
0
    , m_xBtnOpt(m_xBuilder->weld_button(u"options"_ustr))
192
0
    , m_xBtnClose(m_xBuilder->weld_button(u"close"_ustr))
193
0
    , m_xBtnSolve(m_xBuilder->weld_button(u"ok"_ustr))
194
0
    , m_xBtnResetAll(m_xBuilder->weld_button(u"resetall"_ustr))
195
0
    , m_xResultFT(m_xBuilder->weld_label(u"result"_ustr))
196
0
    , m_xContents(m_xBuilder->weld_widget(u"grid"_ustr))
197
0
    , m_pSolverSettings(mrDoc.FetchTable(mnCurTab)->GetSolverSettings())
198
0
{
199
0
    m_xEdObjectiveCell->SetReferences(this, m_xFtObjectiveCell.get());
200
0
    m_xRBObjectiveCell->SetReferences(this, m_xEdObjectiveCell.get());
201
0
    m_xEdTargetValue->SetReferences(this, m_xResultFT.get());
202
0
    m_xRBTargetValue->SetReferences(this, m_xEdTargetValue.get());
203
0
    m_xEdVariableCells->SetReferences(this, m_xFtVariableCells.get());
204
0
    m_xRBVariableCells->SetReferences(this, m_xEdVariableCells.get());
205
0
    m_xEdLeft1->SetReferences(this, m_xFtCellRef.get());
206
0
    m_xRBLeft1->SetReferences(this, m_xEdLeft1.get());
207
0
    m_xEdRight1->SetReferences(this, m_xFtConstraint.get());
208
0
    m_xRBRight1->SetReferences(this, m_xEdRight1.get());
209
0
    m_xEdLeft2->SetReferences(this, m_xFtCellRef.get());
210
0
    m_xRBLeft2->SetReferences(this, m_xEdLeft2.get());
211
0
    m_xEdRight2->SetReferences(this, m_xFtConstraint.get());
212
0
    m_xRBRight2->SetReferences(this, m_xEdRight2.get());
213
0
    m_xEdLeft3->SetReferences(this, m_xFtCellRef.get());
214
0
    m_xRBLeft3->SetReferences(this, m_xEdLeft3.get());
215
0
    m_xEdRight3->SetReferences(this, m_xFtConstraint.get());
216
0
    m_xRBRight3->SetReferences(this, m_xEdRight3.get());
217
0
    m_xEdLeft4->SetReferences(this, m_xFtCellRef.get());
218
0
    m_xRBLeft4->SetReferences(this, m_xEdLeft4.get());
219
0
    m_xEdRight4->SetReferences(this, m_xFtConstraint.get());
220
0
    m_xRBRight4->SetReferences(this, m_xEdRight4.get());
221
222
0
    mpLeftEdit[0]    = m_xEdLeft1.get();
223
0
    mpLeftButton[0]  = m_xRBLeft1.get();
224
0
    mpRightEdit[0]   = m_xEdRight1.get();
225
0
    mpRightButton[0] = m_xRBRight1.get();
226
0
    mpOperator[0]    = m_xLbOp1.get();
227
0
    mpDelButton[0]   = m_xBtnDel1.get();
228
229
0
    mpLeftEdit[1]    = m_xEdLeft2.get();
230
0
    mpLeftButton[1]  = m_xRBLeft2.get();
231
0
    mpRightEdit[1]   = m_xEdRight2.get();
232
0
    mpRightButton[1] = m_xRBRight2.get();
233
0
    mpOperator[1]    = m_xLbOp2.get();
234
0
    mpDelButton[1]   = m_xBtnDel2.get();
235
236
0
    mpLeftEdit[2]    = m_xEdLeft3.get();
237
0
    mpLeftButton[2]  = m_xRBLeft3.get();
238
0
    mpRightEdit[2]   = m_xEdRight3.get();
239
0
    mpRightButton[2] = m_xRBRight3.get();
240
0
    mpOperator[2]    = m_xLbOp3.get();
241
0
    mpDelButton[2]   = m_xBtnDel3.get();
242
243
0
    mpLeftEdit[3]    = m_xEdLeft4.get();
244
0
    mpLeftButton[3]  = m_xRBLeft4.get();
245
0
    mpRightEdit[3]   = m_xEdRight4.get();
246
0
    mpRightButton[3] = m_xRBRight4.get();
247
0
    mpOperator[3]    = m_xLbOp4.get();
248
0
    mpDelButton[3]   = m_xBtnDel4.get();
249
250
0
    Init( aCursorPos );
251
0
}
252
253
ScOptSolverDlg::~ScOptSolverDlg()
254
0
{
255
0
}
256
257
void ScOptSolverDlg::Init(const ScAddress& rCursorPos)
258
0
{
259
0
    uno::Reference<frame::XFrame> xFrame = GetBindings().GetActiveFrame();
260
0
    auto xDelNm = vcl::CommandInfoProvider::GetXGraphicForCommand(u".uno:DeleteRows"_ustr, xFrame);
261
0
    for (weld::Button* pButton : mpDelButton)
262
0
        pButton->set_image(xDelNm);
263
264
0
    m_xBtnOpt->connect_clicked( LINK( this, ScOptSolverDlg, BtnHdl ) );
265
0
    m_xBtnClose->connect_clicked( LINK( this, ScOptSolverDlg, BtnHdl ) );
266
0
    m_xBtnSolve->connect_clicked( LINK( this, ScOptSolverDlg, BtnHdl ) );
267
0
    m_xBtnResetAll->connect_clicked( LINK( this, ScOptSolverDlg, BtnHdl ) );
268
269
0
    Link<formula::RefEdit&,void> aEditLink = LINK( this, ScOptSolverDlg, GetEditFocusHdl );
270
0
    Link<formula::RefButton&,void> aButtonLink = LINK( this, ScOptSolverDlg, GetButtonFocusHdl );
271
0
    m_xEdObjectiveCell->SetGetFocusHdl( aEditLink );
272
0
    m_xRBObjectiveCell->SetGetFocusHdl( aButtonLink );
273
0
    m_xEdTargetValue->SetGetFocusHdl( aEditLink );
274
0
    m_xRBTargetValue->SetGetFocusHdl( aButtonLink );
275
0
    m_xEdVariableCells->SetGetFocusHdl( aEditLink );
276
0
    m_xRBVariableCells->SetGetFocusHdl( aButtonLink );
277
0
    Link<weld::Widget&,void> aLink = LINK(this, ScOptSolverDlg, GetFocusHdl);
278
0
    m_xRbValue->connect_focus_in(aLink);
279
0
    for ( sal_uInt16 nRow = 0; nRow < EDIT_ROW_COUNT; ++nRow )
280
0
    {
281
0
        mpLeftEdit[nRow]->SetGetFocusHdl( aEditLink );
282
0
        mpLeftButton[nRow]->SetGetFocusHdl( aButtonLink );
283
0
        mpRightEdit[nRow]->SetGetFocusHdl( aEditLink );
284
0
        mpRightButton[nRow]->SetGetFocusHdl( aButtonLink );
285
0
        mpOperator[nRow]->connect_focus_in(aLink);
286
0
    }
287
288
0
    aEditLink = LINK( this, ScOptSolverDlg, LoseEditFocusHdl );
289
0
    aButtonLink = LINK( this, ScOptSolverDlg, LoseButtonFocusHdl );
290
0
    m_xEdObjectiveCell->SetLoseFocusHdl( aEditLink );
291
0
    m_xRBObjectiveCell->SetLoseFocusHdl( aButtonLink );
292
0
    m_xEdTargetValue->SetLoseFocusHdl( aEditLink );
293
0
    m_xRBTargetValue-> SetLoseFocusHdl( aButtonLink );
294
0
    m_xEdVariableCells->SetLoseFocusHdl( aEditLink );
295
0
    m_xRBVariableCells->SetLoseFocusHdl( aButtonLink );
296
0
    for ( sal_uInt16 nRow = 0; nRow < EDIT_ROW_COUNT; ++nRow )
297
0
    {
298
0
        mpLeftEdit[nRow]->SetLoseFocusHdl( aEditLink );
299
0
        mpLeftButton[nRow]->SetLoseFocusHdl( aButtonLink );
300
0
        mpRightEdit[nRow]->SetLoseFocusHdl( aEditLink );
301
0
        mpRightButton[nRow]->SetLoseFocusHdl( aButtonLink );
302
0
    }
303
304
0
    Link<ScCursorRefEdit&,void> aCursorUp = LINK( this, ScOptSolverDlg, CursorUpHdl );
305
0
    Link<ScCursorRefEdit&,void> aCursorDown = LINK( this, ScOptSolverDlg, CursorDownHdl );
306
0
    Link<formula::RefEdit&,void> aCondModify = LINK( this, ScOptSolverDlg, CondModifyHdl );
307
0
    for ( sal_uInt16 nRow = 0; nRow < EDIT_ROW_COUNT; ++nRow )
308
0
    {
309
0
        mpLeftEdit[nRow]->SetCursorLinks( aCursorUp, aCursorDown );
310
0
        mpRightEdit[nRow]->SetCursorLinks( aCursorUp, aCursorDown );
311
0
        mpLeftEdit[nRow]->SetModifyHdl( aCondModify );
312
0
        mpRightEdit[nRow]->SetModifyHdl( aCondModify );
313
0
        mpDelButton[nRow]->connect_clicked( LINK( this, ScOptSolverDlg, DelBtnHdl ) );
314
0
        mpOperator[nRow]->connect_changed( LINK( this, ScOptSolverDlg, SelectHdl ) );
315
0
    }
316
0
    m_xEdTargetValue->SetModifyHdl( LINK( this, ScOptSolverDlg, TargetModifyHdl ) );
317
318
0
    Size aSize(m_xContents->get_preferred_size());
319
0
    m_xContents->set_size_request(aSize.Width(), aSize.Height());
320
0
    m_xScrollBar->connect_vadjustment_value_changed( LINK( this, ScOptSolverDlg, ScrollHdl ) );
321
322
0
    m_xScrollBar->vadjustment_set_page_increment( EDIT_ROW_COUNT );
323
0
    m_xScrollBar->vadjustment_set_page_size( EDIT_ROW_COUNT );
324
    // Range is set in ShowConditions
325
326
    // get available solver implementations
327
    //! sort by descriptions?
328
0
    ScSolverUtil::GetImplementations( maImplNames, maDescriptions );
329
330
    // Load existing settings stored in the tab
331
0
    LoadSolverSettings();
332
0
    ShowConditions();
333
334
    // If no objective cell has been loaded, then use the selected cell
335
0
    if (m_xEdObjectiveCell->GetText().isEmpty())
336
0
    {
337
0
        OUString aCursorStr;
338
0
        if (!mrDoc.GetRangeAtBlock(ScRange(rCursorPos), aCursorStr))
339
0
            aCursorStr = rCursorPos.Format(ScRefFlags::ADDR_ABS, nullptr, mrDoc.GetAddressConvention());
340
0
        m_xEdObjectiveCell->SetRefString(aCursorStr);
341
0
    }
342
343
0
    m_xEdObjectiveCell->GrabFocus();
344
0
    mpEdActive = m_xEdObjectiveCell.get();
345
0
}
346
347
void ScOptSolverDlg::ReadConditions()
348
0
{
349
0
    for ( sal_uInt16 nRow = 0; nRow < EDIT_ROW_COUNT; ++nRow )
350
0
    {
351
0
        sc::ModelConstraint aRowEntry;
352
0
        aRowEntry.aLeftStr = mpLeftEdit[nRow]->GetText();
353
0
        aRowEntry.aRightStr = mpRightEdit[nRow]->GetText();
354
0
        aRowEntry.nOperator = OperatorIndexToConstraintOperator(mpOperator[nRow]->get_active());
355
356
0
        tools::Long nVecPos = nScrollPos + nRow;
357
0
        if ( nVecPos >= static_cast<tools::Long>(m_aConditions.size()) && !aRowEntry.IsDefault() )
358
0
            m_aConditions.resize( nVecPos + 1 );
359
360
0
        if ( nVecPos < static_cast<tools::Long>(m_aConditions.size()) )
361
0
            m_aConditions[nVecPos] = std::move(aRowEntry);
362
363
        // remove default entries at the end
364
0
        size_t nSize = m_aConditions.size();
365
0
        while ( nSize > 0 && m_aConditions[ nSize-1 ].IsDefault() )
366
0
            --nSize;
367
0
        m_aConditions.resize( nSize );
368
0
    }
369
0
}
370
371
void ScOptSolverDlg::ShowConditions()
372
0
{
373
0
    for ( sal_uInt16 nRow = 0; nRow < EDIT_ROW_COUNT; ++nRow )
374
0
    {
375
0
        sc::ModelConstraint aRowEntry;
376
377
0
        tools::Long nVecPos = nScrollPos + nRow;
378
0
        if ( nVecPos < static_cast<tools::Long>(m_aConditions.size()) )
379
0
            aRowEntry = m_aConditions[nVecPos];
380
381
0
        mpLeftEdit[nRow]->SetRefString( aRowEntry.aLeftStr );
382
0
        mpRightEdit[nRow]->SetRefString( aRowEntry.aRightStr );
383
0
        mpOperator[nRow]->set_active( aRowEntry.nOperator - 1);
384
0
    }
385
386
    // allow to scroll one page behind the visible or stored rows
387
0
    tools::Long nVisible = nScrollPos + EDIT_ROW_COUNT;
388
0
    tools::Long nMax = std::max( nVisible, static_cast<tools::Long>(m_aConditions.size()) );
389
0
    m_xScrollBar->vadjustment_configure(nScrollPos, nMax + EDIT_ROW_COUNT, 1, EDIT_ROW_COUNT - 1,
390
0
                                        EDIT_ROW_COUNT);
391
392
0
    EnableButtons();
393
0
}
394
395
void ScOptSolverDlg::EnableButtons()
396
0
{
397
0
    for ( sal_uInt16 nRow = 0; nRow < EDIT_ROW_COUNT; ++nRow )
398
0
    {
399
0
        tools::Long nVecPos = nScrollPos + nRow;
400
0
        mpDelButton[nRow]->set_sensitive(nVecPos < static_cast<tools::Long>(m_aConditions.size()));
401
0
    }
402
0
}
403
404
void ScOptSolverDlg::Close()
405
0
{
406
0
    if (m_xOptDlg)
407
0
        m_xOptDlg->response(RET_CANCEL);
408
0
    assert(!m_xOptDlg);
409
0
    DoClose( ScOptSolverDlgWrapper::GetChildWindowId() );
410
0
}
411
412
void ScOptSolverDlg::SetActive()
413
0
{
414
0
    if ( mbDlgLostFocus )
415
0
    {
416
0
        mbDlgLostFocus = false;
417
0
        if( mpEdActive )
418
0
            mpEdActive->GrabFocus();
419
0
    }
420
0
    else
421
0
    {
422
0
        m_xDialog->grab_focus();
423
0
    }
424
0
    RefInputDone();
425
0
}
426
427
void ScOptSolverDlg::SetReference( const ScRange& rRef, ScDocument& rDocP )
428
0
{
429
0
    if( !mpEdActive )
430
0
        return;
431
432
0
    if ( rRef.aStart != rRef.aEnd )
433
0
        RefInputStart(mpEdActive);
434
435
    // "target"/"value": single cell
436
0
    bool bSingle = ( mpEdActive == m_xEdObjectiveCell.get() || mpEdActive == m_xEdTargetValue.get() );
437
438
0
    OUString aStr;
439
0
    ScAddress aAdr = rRef.aStart;
440
0
    ScRange aNewRef( rRef );
441
0
    if ( bSingle )
442
0
        aNewRef.aEnd = aAdr;
443
444
0
    OUString aName;
445
0
    if ( rDocP.GetRangeAtBlock( aNewRef, aName ) )            // named range: show name
446
0
        aStr = aName;
447
0
    else                                                        // format cell/range reference
448
0
    {
449
0
        ScRefFlags nFmt = ( aAdr.Tab() == mnCurTab ) ? ScRefFlags::ADDR_ABS : ScRefFlags::ADDR_ABS_3D;
450
0
        if ( bSingle )
451
0
            aStr = aAdr.Format(nFmt, &rDocP, rDocP.GetAddressConvention());
452
0
        else
453
0
            aStr = rRef.Format(rDocP, nFmt | ScRefFlags::RANGE_ABS, rDocP.GetAddressConvention());
454
0
    }
455
456
    // variable cells can be several ranges, so only the selection is replaced
457
0
    if ( mpEdActive == m_xEdVariableCells.get() )
458
0
    {
459
0
        OUString aVal = mpEdActive->GetText();
460
0
        Selection aSel = mpEdActive->GetSelection();
461
0
        aSel.Normalize();
462
0
        aVal = aVal.replaceAt( aSel.Min(), aSel.Len(), aStr );
463
0
        Selection aNewSel( aSel.Min(), aSel.Min()+aStr.getLength() );
464
0
        mpEdActive->SetRefString( aVal );
465
0
        mpEdActive->SetSelection( aNewSel );
466
0
    }
467
0
    else
468
0
        mpEdActive->SetRefString( aStr );
469
470
0
    ReadConditions();
471
0
    EnableButtons();
472
473
    // select "Value of" if a ref is input into "target" edit
474
0
    if ( mpEdActive == m_xEdTargetValue.get() )
475
0
        m_xRbValue->set_active(true);
476
0
}
477
478
bool ScOptSolverDlg::IsRefInputMode() const
479
0
{
480
0
    return mpEdActive != nullptr;
481
0
}
482
483
// Loads solver settings into the dialog
484
void ScOptSolverDlg::LoadSolverSettings()
485
0
{
486
0
    m_xEdObjectiveCell->SetRefString(m_pSolverSettings->GetParameter(sc::SP_OBJ_CELL));
487
0
    m_xEdTargetValue->SetRefString(m_pSolverSettings->GetParameter(sc::SP_OBJ_VAL));
488
0
    m_xEdVariableCells->SetRefString(m_pSolverSettings->GetParameter(sc::SP_VAR_CELLS));
489
490
    // Objective type
491
0
    sc::ObjectiveType eType = m_pSolverSettings->GetObjectiveType();
492
0
    switch (eType)
493
0
    {
494
0
        case sc::OT_MAXIMIZE : m_xRbMax->set_active(true); break;
495
0
        case sc::OT_MINIMIZE : m_xRbMin->set_active(true); break;
496
0
        case sc::OT_VALUE    : m_xRbValue->set_active(true); break;
497
0
    }
498
499
    // Model constraints
500
0
    m_aConditions = m_pSolverSettings->GetConstraints();
501
502
    // Loads solver engine name
503
    // If the solver engine in the current settings are not supported, use the first available
504
0
    maEngine = m_pSolverSettings->GetParameter(sc::SP_LO_ENGINE);
505
0
    if (!IsEngineAvailable(maEngine))
506
0
    {
507
0
        maEngine = maImplNames[0];
508
0
        m_pSolverSettings->SetParameter(sc::SP_LO_ENGINE, maEngine);
509
0
    }
510
511
    // Query current engine options
512
0
    maProperties = ScSolverUtil::GetDefaults(maEngine);
513
0
    m_pSolverSettings->GetEngineOptions(maProperties);
514
0
}
515
516
// Set solver settings and save them to the file
517
// But first, checks if the settings have changed
518
void ScOptSolverDlg::SaveSolverSettings()
519
0
{
520
    // tdf#160104 If file does not have a solver model and the Solver dialog is set to its
521
    // default initial values (maximize is selected; no variable cells; no target value
522
    // and no constraints defined) then nothing needs to be saved
523
0
    if (!m_pSolverSettings->TabHasSolverModel() && m_xRbMax->get_active()
524
0
        && m_xEdTargetValue->GetText().isEmpty() && m_xEdVariableCells->GetText().isEmpty()
525
0
        && m_aConditions.size() == 0)
526
0
        return;
527
528
    // The current tab has a model; now we need to determined if it has been modified
529
0
    bool bModified = false;
530
531
    // Check objective cell, objective value and variable cells
532
0
    if (m_pSolverSettings->GetParameter(sc::SP_OBJ_CELL) != m_xEdObjectiveCell->GetText()
533
0
        || m_pSolverSettings->GetParameter(sc::SP_OBJ_VAL) != m_xEdTargetValue->GetText()
534
0
        || m_pSolverSettings->GetParameter(sc::SP_VAR_CELLS) != m_xEdVariableCells->GetText())
535
0
        bModified = true;
536
537
    // Check selected objective type and save it if changed
538
0
    sc::ObjectiveType aType = sc::OT_MAXIMIZE;
539
0
    if (m_xRbMin->get_active())
540
0
        aType = sc::OT_MINIMIZE;
541
0
    else if (m_xRbValue->get_active())
542
0
        aType = sc::OT_VALUE;
543
544
0
    if (m_pSolverSettings->GetObjectiveType() != aType)
545
0
        bModified = true;
546
547
    // Check if model constraints changed
548
0
    std::vector<sc::ModelConstraint> vCurConditions = m_pSolverSettings->GetConstraints();
549
0
    if (!bModified && vCurConditions.size() != m_aConditions.size())
550
0
        bModified = true;
551
0
    else
552
0
    {
553
        // Here the size of both vectors is the same
554
        // Now it needs to check the contents of the constraints
555
0
        for (size_t i = 0; i < vCurConditions.size(); i++)
556
0
        {
557
0
            if (vCurConditions[i].aLeftStr != m_aConditions[i].aLeftStr
558
0
                || vCurConditions[i].nOperator != m_aConditions[i].nOperator
559
0
                || vCurConditions[i].aRightStr != m_aConditions[i].aRightStr)
560
0
                bModified = true;
561
562
0
            if (bModified)
563
0
                break;
564
0
        }
565
0
    }
566
567
    // Check if the solver engine name and its options have changed
568
0
    if (m_pSolverSettings->GetParameter(sc::SP_LO_ENGINE) != maEngine)
569
0
    {
570
0
        bModified = true;
571
0
    }
572
0
    else
573
0
    {
574
        // The solver engine hasn't changed, so we need to check if engine options changed
575
        // Query current engine options; here we start by creating a copy of maProperties
576
        // to ensure the order is the same
577
0
        css::uno::Sequence<css::beans::PropertyValue> vCurOptions(maProperties);
578
0
        m_pSolverSettings->GetEngineOptions(vCurOptions);
579
580
0
        for (sal_Int32 i = 0; i < vCurOptions.getLength(); i++)
581
0
        {
582
0
            if (vCurOptions[i].Value != maProperties[i].Value)
583
0
            {
584
0
                bModified = true;
585
0
                break;
586
0
            }
587
0
        }
588
0
    }
589
590
    // Effectively save settings to file if modifications were made
591
0
    if (bModified)
592
0
    {
593
0
        m_pSolverSettings->SetParameter(sc::SP_OBJ_CELL, m_xEdObjectiveCell->GetText());
594
0
        m_pSolverSettings->SetParameter(sc::SP_OBJ_VAL, m_xEdTargetValue->GetText());
595
0
        m_pSolverSettings->SetParameter(sc::SP_VAR_CELLS, m_xEdVariableCells->GetText());
596
0
        m_pSolverSettings->SetObjectiveType(aType);
597
0
        m_pSolverSettings->SetConstraints(m_aConditions);
598
0
        m_pSolverSettings->SetParameter(sc::SP_LO_ENGINE, maEngine);
599
0
        m_pSolverSettings->SetEngineOptions(maProperties);
600
0
        m_pSolverSettings->SaveSolverSettings();
601
0
    }
602
0
}
603
// Test if a LO engine implementation exists
604
bool ScOptSolverDlg::IsEngineAvailable(std::u16string_view sEngineName)
605
0
{
606
0
    auto nIndex = comphelper::findValue(maImplNames, sEngineName);
607
0
    return nIndex != -1;
608
0
}
609
610
// Handler:
611
612
IMPL_LINK(ScOptSolverDlg, BtnHdl, weld::Button&, rBtn, void)
613
0
{
614
0
    auto xKeepAlive = shared_from_this();
615
0
    if (&rBtn == m_xBtnSolve.get() || &rBtn == m_xBtnClose.get())
616
0
    {
617
0
        bool bSolve = ( &rBtn == m_xBtnSolve.get() );
618
619
0
        SetDispatcherLock( false );
620
0
        SwitchToDocument();
621
622
0
        bool bClose = true;
623
0
        if ( bSolve )
624
0
            bClose = CallSolver();
625
626
0
        if ( bClose )
627
0
        {
628
            // Close: write dialog settings to DocShell for subsequent calls
629
0
            ReadConditions();
630
0
            SaveSolverSettings();
631
0
            response(RET_CLOSE);
632
0
        }
633
0
        else
634
0
        {
635
            // no solution -> dialog is kept open
636
0
            SetDispatcherLock( true );
637
0
        }
638
0
    }
639
0
    else if (&rBtn == m_xBtnOpt.get())
640
0
    {
641
        //! move options dialog to UI lib?
642
0
        m_xOptDlg = std::make_shared<ScSolverOptionsDialog>(m_xDialog.get(), maImplNames, maDescriptions, maEngine, maProperties);
643
0
        weld::DialogController::runAsync(m_xOptDlg, [this](sal_Int32 nResult){
644
0
            if (nResult == RET_OK)
645
0
            {
646
0
                maEngine = m_xOptDlg->GetEngine();
647
0
                maProperties = m_xOptDlg->GetProperties();
648
0
            }
649
0
            m_xOptDlg.reset();
650
0
        });
651
0
    }
652
0
    else if (&rBtn == m_xBtnResetAll.get())
653
0
    {
654
0
        OUString sEmpty;
655
0
        m_xEdObjectiveCell->SetText(sEmpty);
656
0
        m_xEdTargetValue->SetText(sEmpty);
657
0
        m_xEdVariableCells->SetText(sEmpty);
658
659
        // Get default property values of solver implementations
660
0
        maEngine = maImplNames[0];
661
0
        maProperties = ScSolverUtil::GetDefaults( maEngine );
662
663
        // Clear all conditions (Constraints)
664
0
        m_aConditions.clear();
665
0
        ShowConditions();
666
667
0
        m_xRbMax->set_active(true);
668
0
        m_xEdObjectiveCell->GrabFocus();
669
0
        mpEdActive = m_xEdObjectiveCell.get();
670
0
    }
671
0
}
672
673
IMPL_LINK( ScOptSolverDlg, GetEditFocusHdl, formula::RefEdit&, rCtrl, void )
674
0
{
675
0
    formula::RefEdit* pEdit = nullptr;
676
0
    mpEdActive = nullptr;
677
678
0
    if( &rCtrl == m_xEdObjectiveCell.get() )
679
0
        pEdit = mpEdActive = m_xEdObjectiveCell.get();
680
0
    else if( &rCtrl == m_xEdTargetValue.get() )
681
0
        pEdit = mpEdActive = m_xEdTargetValue.get();
682
0
    else if( &rCtrl == m_xEdVariableCells.get() )
683
0
        pEdit = mpEdActive = m_xEdVariableCells.get();
684
0
    for ( sal_uInt16 nRow = 0; nRow < EDIT_ROW_COUNT; ++nRow )
685
0
    {
686
0
        if( &rCtrl == mpLeftEdit[nRow]  )
687
0
            pEdit = mpEdActive = mpLeftEdit[nRow];
688
0
        else if( &rCtrl == mpRightEdit[nRow]  )
689
0
            pEdit = mpEdActive = mpRightEdit[nRow];
690
0
    }
691
692
0
    if( pEdit )
693
0
        pEdit->SelectAll();
694
0
}
695
696
IMPL_LINK( ScOptSolverDlg, GetButtonFocusHdl, formula::RefButton&, rCtrl, void )
697
0
{
698
0
    formula::RefEdit* pEdit = nullptr;
699
0
    mpEdActive = nullptr;
700
701
0
    if( &rCtrl == m_xRBObjectiveCell.get() )
702
0
        pEdit = mpEdActive = m_xEdObjectiveCell.get();
703
0
    else if( &rCtrl == m_xRBTargetValue.get() )
704
0
        pEdit = mpEdActive = m_xEdTargetValue.get();
705
0
    else if( &rCtrl == m_xRBVariableCells.get() )
706
0
        pEdit = mpEdActive = m_xEdVariableCells.get();
707
0
    for ( sal_uInt16 nRow = 0; nRow < EDIT_ROW_COUNT; ++nRow )
708
0
    {
709
0
        if( &rCtrl == mpLeftButton[nRow] )
710
0
            pEdit = mpEdActive = mpLeftEdit[nRow];
711
0
        else if( &rCtrl == mpRightButton[nRow] )
712
0
            pEdit = mpEdActive = mpRightEdit[nRow];
713
0
    }
714
715
0
    if( pEdit )
716
0
        pEdit->SelectAll();
717
0
}
718
719
720
IMPL_LINK(ScOptSolverDlg, GetFocusHdl, weld::Widget&, rCtrl, void)
721
0
{
722
0
    if( &rCtrl == m_xRbValue.get() )                   // focus on "Value of" radio button
723
0
        mpEdActive = m_xEdTargetValue.get();          // use value edit for ref input, but don't change selection
724
0
    else
725
0
    {
726
0
        for ( sal_uInt16 nRow = 0; nRow < EDIT_ROW_COUNT; ++nRow )
727
0
        {
728
0
            if( &rCtrl == mpOperator[nRow] )    // focus on "operator" list box
729
0
                mpEdActive = mpRightEdit[nRow];     // use right edit for ref input, but don't change selection
730
0
        }
731
0
    }
732
0
}
733
734
IMPL_LINK_NOARG(ScOptSolverDlg, LoseEditFocusHdl, formula::RefEdit&, void)
735
0
{
736
0
    mbDlgLostFocus = !m_xDialog->has_toplevel_focus();
737
0
}
738
739
IMPL_LINK_NOARG(ScOptSolverDlg, LoseButtonFocusHdl, formula::RefButton&, void)
740
0
{
741
0
    mbDlgLostFocus = !m_xDialog->has_toplevel_focus();
742
0
}
743
744
IMPL_LINK(ScOptSolverDlg, DelBtnHdl, weld::Button&, rBtn, void)
745
0
{
746
0
    for ( sal_uInt16 nRow = 0; nRow < EDIT_ROW_COUNT; ++nRow )
747
0
        if (&rBtn == mpDelButton[nRow])
748
0
        {
749
0
            bool bHadFocus = rBtn.has_focus();
750
751
0
            ReadConditions();
752
0
            tools::Long nVecPos = nScrollPos + nRow;
753
0
            if ( nVecPos < static_cast<tools::Long>(m_aConditions.size()) )
754
0
            {
755
0
                m_aConditions.erase( m_aConditions.begin() + nVecPos );
756
0
                ShowConditions();
757
758
0
                if ( bHadFocus && !rBtn.get_sensitive() )
759
0
                {
760
                    // If the button is disabled, focus would normally move to the next control,
761
                    // (left edit of the next row). Move it to left edit of this row instead.
762
763
0
                    mpEdActive = mpLeftEdit[nRow];
764
0
                    mpEdActive->GrabFocus();
765
0
                }
766
0
            }
767
0
        }
768
0
}
769
770
IMPL_LINK_NOARG(ScOptSolverDlg, TargetModifyHdl, formula::RefEdit&, void)
771
0
{
772
    // modify handler for the target edit:
773
    //  select "Value of" if something is input into the edit
774
0
    if ( !m_xEdTargetValue->GetText().isEmpty() )
775
0
        m_xRbValue->set_active(true);
776
0
}
777
778
IMPL_LINK_NOARG(ScOptSolverDlg, CondModifyHdl, formula::RefEdit&, void)
779
0
{
780
    // modify handler for the condition edits, just to enable/disable "delete" buttons
781
0
    ReadConditions();
782
0
    EnableButtons();
783
0
}
784
785
IMPL_LINK_NOARG(ScOptSolverDlg, SelectHdl, weld::ComboBox&, void)
786
0
{
787
    // select handler for operator list boxes, just to enable/disable "delete" buttons
788
0
    ReadConditions();
789
0
    EnableButtons();
790
0
}
791
792
IMPL_LINK_NOARG(ScOptSolverDlg, ScrollHdl, weld::ScrolledWindow&, void)
793
0
{
794
0
    ReadConditions();
795
0
    nScrollPos = m_xScrollBar->vadjustment_get_value();
796
0
    ShowConditions();
797
0
    if( mpEdActive )
798
0
        mpEdActive->SelectAll();
799
0
}
800
801
IMPL_LINK( ScOptSolverDlg, CursorUpHdl, ScCursorRefEdit&, rEdit, void )
802
0
{
803
0
    if ( &rEdit == mpLeftEdit[0] || &rEdit == mpRightEdit[0] )
804
0
    {
805
0
        if ( nScrollPos > 0 )
806
0
        {
807
0
            ReadConditions();
808
0
            --nScrollPos;
809
0
            ShowConditions();
810
0
            if( mpEdActive )
811
0
                mpEdActive->SelectAll();
812
0
        }
813
0
    }
814
0
    else
815
0
    {
816
0
        formula::RefEdit* pFocus = nullptr;
817
0
        for ( sal_uInt16 nRow = 1; nRow < EDIT_ROW_COUNT; ++nRow )      // second row or below: move focus
818
0
        {
819
0
            if ( &rEdit == mpLeftEdit[nRow] )
820
0
                pFocus = mpLeftEdit[nRow-1];
821
0
            else if ( &rEdit == mpRightEdit[nRow] )
822
0
                pFocus = mpRightEdit[nRow-1];
823
0
        }
824
0
        if (pFocus)
825
0
        {
826
0
            mpEdActive = pFocus;
827
0
            pFocus->GrabFocus();
828
0
        }
829
0
    }
830
0
}
831
832
IMPL_LINK( ScOptSolverDlg, CursorDownHdl, ScCursorRefEdit&, rEdit, void )
833
0
{
834
0
    if ( &rEdit == mpLeftEdit[EDIT_ROW_COUNT-1] || &rEdit == mpRightEdit[EDIT_ROW_COUNT-1] )
835
0
    {
836
        //! limit scroll position?
837
0
        ReadConditions();
838
0
        ++nScrollPos;
839
0
        ShowConditions();
840
0
        if( mpEdActive )
841
0
            mpEdActive->SelectAll();
842
0
    }
843
0
    else
844
0
    {
845
0
        formula::RefEdit* pFocus = nullptr;
846
0
        for ( sal_uInt16 nRow = 0; nRow+1 < EDIT_ROW_COUNT; ++nRow )      // before last row: move focus
847
0
        {
848
0
            if ( &rEdit == mpLeftEdit[nRow] )
849
0
                pFocus = mpLeftEdit[nRow+1];
850
0
            else if ( &rEdit == mpRightEdit[nRow] )
851
0
                pFocus = mpRightEdit[nRow+1];
852
0
        }
853
0
        if (pFocus)
854
0
        {
855
0
            mpEdActive = pFocus;
856
0
            pFocus->GrabFocus();
857
0
        }
858
0
    }
859
0
}
860
861
// Converts the position of the operator in the dropdown menu to a ConstraintOperator type
862
sc::ConstraintOperator ScOptSolverDlg::OperatorIndexToConstraintOperator(sal_Int32 nIndex)
863
0
{
864
0
    switch(nIndex)
865
0
    {
866
0
        case 0  : return sc::CO_LESS_EQUAL; break;
867
0
        case 1  : return sc::CO_EQUAL; break;
868
0
        case 2  : return sc::CO_GREATER_EQUAL; break;
869
0
        case 3  : return sc::CO_INTEGER; break;
870
0
        case 4  : return sc::CO_BINARY; break;
871
0
        default : return sc::CO_LESS_EQUAL; break;
872
0
    }
873
0
}
874
875
void ScOptSolverDlg::ShowError( bool bCondition, formula::RefEdit* pFocus )
876
0
{
877
0
    OUString aMessage = bCondition ? maConditionError : maInputError;
878
0
    std::unique_ptr<weld::MessageDialog> xBox(Application::CreateMessageDialog(m_xDialog.get(),
879
0
                                              VclMessageType::Warning, VclButtonsType::Ok,
880
0
                                              aMessage));
881
0
    xBox->run();
882
0
    if (pFocus)
883
0
    {
884
0
        mpEdActive = pFocus;
885
0
        pFocus->GrabFocus();
886
0
    }
887
0
}
888
889
bool ScOptSolverDlg::ParseRef( ScRange& rRange, const OUString& rInput, bool bAllowRange )
890
0
{
891
0
    ScAddress::Details aDetails(mrDoc.GetAddressConvention(), 0, 0);
892
0
    ScRefFlags nFlags = rRange.ParseAny( rInput, mrDoc, aDetails );
893
0
    if ( nFlags & ScRefFlags::VALID )
894
0
    {
895
0
        if ( (nFlags & ScRefFlags::TAB_3D) == ScRefFlags::ZERO)
896
0
            rRange.aStart.SetTab( mnCurTab );
897
0
        if ( (nFlags & ScRefFlags::TAB2_3D) == ScRefFlags::ZERO)
898
0
            rRange.aEnd.SetTab( rRange.aStart.Tab() );
899
0
        return ( bAllowRange || rRange.aStart == rRange.aEnd );
900
0
    }
901
0
    else if ( ScRangeUtil::MakeRangeFromName( rInput, mrDoc, mnCurTab, rRange, RUTL_NAMES, aDetails ) )
902
0
        return ( bAllowRange || rRange.aStart == rRange.aEnd );
903
904
0
    return false;   // not recognized
905
0
}
906
907
bool ScOptSolverDlg::FindTimeout( sal_Int32& rTimeout )
908
0
{
909
0
    bool bFound = false;
910
911
0
    if ( !maProperties.hasElements() )
912
0
        maProperties = ScSolverUtil::GetDefaults( maEngine );   // get property defaults from component
913
914
0
    sal_Int32 nPropCount = maProperties.getLength();
915
0
    for (sal_Int32 nProp=0; nProp<nPropCount && !bFound; ++nProp)
916
0
    {
917
0
        const beans::PropertyValue& rValue = maProperties[nProp];
918
0
        if ( rValue.Name == SC_UNONAME_TIMEOUT )
919
0
            bFound = ( rValue.Value >>= rTimeout );
920
0
    }
921
0
    return bFound;
922
0
}
923
924
OUString ScOptSolverDlg::GetCellStrAddress(css::table::CellAddress aUnoAddress)
925
0
{
926
0
    ScAddress aScAddr;
927
0
    ScUnoConversion::FillScAddress(aScAddr, aUnoAddress);
928
0
    ScRange aRange(aScAddr);
929
0
    return aRange.Format(mrDoc, ScRefFlags::RANGE_ABS);
930
0
}
931
932
bool ScOptSolverDlg::CallSolver()       // return true -> close dialog after calling
933
0
{
934
    // show progress dialog
935
936
0
    auto xProgress = std::make_shared<ScSolverProgressDialog>(m_xDialog.get());
937
0
    sal_Int32 nTimeout = 0;
938
0
    if ( FindTimeout( nTimeout ) )
939
0
        xProgress->SetTimeLimit( nTimeout );
940
0
    else
941
0
        xProgress->HideTimeLimit();
942
943
0
    weld::DialogController::runAsync(xProgress, [](sal_Int32 /*nResult*/){});
944
945
    // try to make sure the progress dialog is painted before continuing
946
0
    Application::Reschedule(true);
947
948
    // collect solver parameters
949
950
0
    ReadConditions();
951
952
0
    rtl::Reference<ScModelObj> xDocument( mpDocShell->GetModel() );
953
954
0
    ScRange aObjRange;
955
0
    if ( !ParseRef( aObjRange, m_xEdObjectiveCell->GetText(), false ) )
956
0
    {
957
0
        ShowError( false, m_xEdObjectiveCell.get() );
958
0
        return false;
959
0
    }
960
0
    table::CellAddress aObjective( aObjRange.aStart.Tab(), aObjRange.aStart.Col(), aObjRange.aStart.Row() );
961
962
    // "changing cells" can be several ranges
963
0
    ScRangeList aVarRanges;
964
0
    if ( !ParseWithNames( aVarRanges, m_xEdVariableCells->GetText(), mrDoc ) )
965
0
    {
966
0
        ShowError( false, m_xEdVariableCells.get() );
967
0
        return false;
968
0
    }
969
0
    uno::Sequence<table::CellAddress> aVariables;
970
0
    sal_Int32 nVarPos = 0;
971
972
0
    for ( size_t nRangePos=0, nRange = aVarRanges.size(); nRangePos < nRange; ++nRangePos )
973
0
    {
974
0
        ScRange aRange( aVarRanges[ nRangePos ] );
975
0
        aRange.PutInOrder();
976
0
        SCTAB nTab = aRange.aStart.Tab();
977
978
        // resolve into single cells
979
980
0
        sal_Int32 nAdd = ( aRange.aEnd.Col() - aRange.aStart.Col() + 1 ) *
981
0
                         ( aRange.aEnd.Row() - aRange.aStart.Row() + 1 );
982
0
        aVariables.realloc( nVarPos + nAdd );
983
0
        auto pVariables = aVariables.getArray();
984
985
0
        for (SCROW nRow = aRange.aStart.Row(); nRow <= aRange.aEnd.Row(); ++nRow)
986
0
            for (SCCOL nCol = aRange.aStart.Col(); nCol <= aRange.aEnd.Col(); ++nCol)
987
0
                pVariables[nVarPos++] = table::CellAddress( nTab, nCol, nRow );
988
0
    }
989
990
0
    uno::Sequence<sheet::SolverConstraint> aConstraints;
991
0
    sal_Int32 nConstrPos = 0;
992
0
    for ( const auto& rConstr : m_aConditions )
993
0
    {
994
0
        if ( !rConstr.aLeftStr.isEmpty() )
995
0
        {
996
0
            sheet::SolverConstraint aConstraint;
997
            // Order of list box entries must match enum values.
998
            // The enum SolverConstraintOperator starts at zero, whereas ConstraintOperator starts at 1
999
            // hence we need to subtract -1 here
1000
0
            aConstraint.Operator = static_cast<sheet::SolverConstraintOperator>(rConstr.nOperator - 1);
1001
1002
0
            ScRange aLeftRange;
1003
0
            if ( !ParseRef( aLeftRange, rConstr.aLeftStr, true ) )
1004
0
            {
1005
0
                ShowError( true, nullptr );
1006
0
                return false;
1007
0
            }
1008
1009
0
            bool bIsRange = false;
1010
0
            ScRange aRightRange;
1011
0
            if ( ParseRef( aRightRange, rConstr.aRightStr, true ) )
1012
0
            {
1013
0
                if ( aRightRange.aStart == aRightRange.aEnd )
1014
0
                    aConstraint.Right <<= table::CellAddress( aRightRange.aStart.Tab(),
1015
0
                                                              aRightRange.aStart.Col(), aRightRange.aStart.Row() );
1016
0
                else if ( aRightRange.aEnd.Col()-aRightRange.aStart.Col() == aLeftRange.aEnd.Col()-aLeftRange.aStart.Col() &&
1017
0
                          aRightRange.aEnd.Row()-aRightRange.aStart.Row() == aLeftRange.aEnd.Row()-aLeftRange.aStart.Row() )
1018
0
                    bIsRange = true;    // same size as "left" range, resolve into single cells
1019
0
                else
1020
0
                {
1021
0
                    ShowError( true, nullptr );
1022
0
                    return false;
1023
0
                }
1024
0
            }
1025
0
            else
1026
0
            {
1027
0
                sal_uInt32 nFormat = 0;     //! explicit language?
1028
0
                double fValue = 0.0;
1029
0
                if ( mrDoc.GetFormatTable()->IsNumberFormat( rConstr.aRightStr, nFormat, fValue ) )
1030
0
                    aConstraint.Right <<= fValue;
1031
0
                else if ( aConstraint.Operator != sheet::SolverConstraintOperator_INTEGER &&
1032
0
                          aConstraint.Operator != sheet::SolverConstraintOperator_BINARY )
1033
0
                {
1034
0
                    ShowError( true, nullptr );
1035
0
                    return false;
1036
0
                }
1037
0
            }
1038
1039
            // resolve into single cells
1040
1041
0
            sal_Int32 nAdd = ( aLeftRange.aEnd.Col() - aLeftRange.aStart.Col() + 1 ) *
1042
0
                             ( aLeftRange.aEnd.Row() - aLeftRange.aStart.Row() + 1 );
1043
0
            aConstraints.realloc( nConstrPos + nAdd );
1044
0
            auto pConstraints = aConstraints.getArray();
1045
1046
0
            for (SCROW nRow = aLeftRange.aStart.Row(); nRow <= aLeftRange.aEnd.Row(); ++nRow)
1047
0
                for (SCCOL nCol = aLeftRange.aStart.Col(); nCol <= aLeftRange.aEnd.Col(); ++nCol)
1048
0
                {
1049
0
                    aConstraint.Left = table::CellAddress( aLeftRange.aStart.Tab(), nCol, nRow );
1050
0
                    if ( bIsRange )
1051
0
                        aConstraint.Right <<= table::CellAddress( aRightRange.aStart.Tab(),
1052
0
                            aRightRange.aStart.Col() + ( nCol - aLeftRange.aStart.Col() ),
1053
0
                            aRightRange.aStart.Row() + ( nRow - aLeftRange.aStart.Row() ) );
1054
1055
0
                    pConstraints[nConstrPos++] = aConstraint;
1056
0
                }
1057
0
        }
1058
0
    }
1059
1060
0
    bool bMaximize = m_xRbMax->get_active();
1061
0
    if ( m_xRbValue->get_active() )
1062
0
    {
1063
        // handle "value of" with an additional constraint (and then minimize)
1064
1065
0
        sheet::SolverConstraint aConstraint;
1066
0
        aConstraint.Left     = aObjective;
1067
0
        aConstraint.Operator = sheet::SolverConstraintOperator_EQUAL;
1068
1069
0
        OUString aValStr = m_xEdTargetValue->GetText();
1070
0
        ScRange aRightRange;
1071
0
        if ( ParseRef( aRightRange, aValStr, false ) )
1072
0
            aConstraint.Right <<= table::CellAddress( aRightRange.aStart.Tab(),
1073
0
                                                      aRightRange.aStart.Col(), aRightRange.aStart.Row() );
1074
0
        else
1075
0
        {
1076
0
            sal_uInt32 nFormat = 0;     //! explicit language?
1077
0
            double fValue = 0.0;
1078
0
            if ( mrDoc.GetFormatTable()->IsNumberFormat( aValStr, nFormat, fValue ) )
1079
0
                aConstraint.Right <<= fValue;
1080
0
            else
1081
0
            {
1082
0
                ShowError( false, m_xEdTargetValue.get() );
1083
0
                return false;
1084
0
            }
1085
0
        }
1086
1087
0
        aConstraints.realloc( nConstrPos + 1 );
1088
0
        aConstraints.getArray()[nConstrPos++] = std::move(aConstraint);
1089
0
    }
1090
1091
    // copy old document values
1092
1093
0
    sal_Int32 nVarCount = aVariables.getLength();
1094
0
    uno::Sequence<double> aOldValues( nVarCount );
1095
0
    std::transform(std::cbegin(aVariables), std::cend(aVariables), aOldValues.getArray(),
1096
0
        [this](const table::CellAddress& rVariable) -> double {
1097
0
            ScAddress aCellPos;
1098
0
            ScUnoConversion::FillScAddress( aCellPos, rVariable );
1099
0
            return mrDoc.GetValue( aCellPos );
1100
0
        });
1101
1102
    // create and initialize solver
1103
1104
0
    uno::Reference<sheet::XSolver> xSolver = ScSolverUtil::GetSolver( maEngine );
1105
0
    OSL_ENSURE( xSolver.is(), "can't get solver component" );
1106
0
    if ( !xSolver.is() )
1107
0
        return false;
1108
1109
0
    xSolver->setDocument( xDocument );
1110
0
    xSolver->setObjective( aObjective );
1111
0
    xSolver->setVariables( aVariables );
1112
0
    xSolver->setConstraints( aConstraints );
1113
0
    xSolver->setMaximize( bMaximize );
1114
1115
    // set options
1116
0
    uno::Reference<beans::XPropertySet> xOptProp(xSolver, uno::UNO_QUERY);
1117
0
    if ( xOptProp.is() )
1118
0
    {
1119
0
        for (const beans::PropertyValue& rValue : maProperties)
1120
0
        {
1121
0
            try
1122
0
            {
1123
0
                xOptProp->setPropertyValue( rValue.Name, rValue.Value );
1124
0
            }
1125
0
            catch ( uno::Exception & )
1126
0
            {
1127
0
                OSL_FAIL("Exception in solver option property");
1128
0
            }
1129
0
        }
1130
0
    }
1131
1132
    // tdf#162760 The solver engine may crash unexpectedly, so we need a try...catch here
1133
0
    bool bSuccess(false);
1134
0
    try
1135
0
    {
1136
0
        xSolver->solve();
1137
0
        bSuccess = xSolver->getSuccess();
1138
0
    }
1139
0
    catch (const uno::RuntimeException&)
1140
0
    {
1141
0
        std::unique_ptr<weld::MessageDialog> xBox(Application::CreateMessageDialog(m_xDialog.get(),
1142
0
                                                  VclMessageType::Error, VclButtonsType::Ok,
1143
0
                                                  ScResId(STR_SOLVER_ENGINE_ERROR)));
1144
0
        xBox->run();
1145
0
    }
1146
1147
0
    xProgress->response(RET_CLOSE);
1148
1149
0
    bool bClose = false;
1150
0
    bool bRestore = true;   // restore old values unless a solution is accepted
1151
0
    if ( bSuccess )
1152
0
    {
1153
        // put solution into document so it is visible when asking
1154
0
        uno::Sequence<double> aSolution = xSolver->getSolution();
1155
0
        if ( aSolution.getLength() == nVarCount )
1156
0
        {
1157
0
            mpDocShell->LockPaint();
1158
0
            ScDocFunc &rFunc = mpDocShell->GetDocFunc();
1159
0
            for (nVarPos=0; nVarPos<nVarCount; ++nVarPos)
1160
0
            {
1161
0
                ScAddress aCellPos;
1162
0
                ScUnoConversion::FillScAddress(aCellPos, aVariables[nVarPos]);
1163
0
                rFunc.SetValueCell(aCellPos, aSolution[nVarPos], false);
1164
0
            }
1165
0
            mpDocShell->UnlockPaint();
1166
0
        }
1167
        //! else error?
1168
1169
        // take formatted result from document (result value from component is ignored)
1170
0
        OUString aResultStr = mrDoc.GetString(
1171
0
            static_cast<SCCOL>(aObjective.Column), static_cast<SCROW>(aObjective.Row),
1172
0
            static_cast<SCTAB>(aObjective.Sheet));
1173
1174
0
        ScSolverSuccessDialog aDialog(m_xDialog.get(), aResultStr);
1175
0
        if (aDialog.run() == RET_OK)
1176
0
        {
1177
            // keep results and close dialog
1178
0
            bRestore = false;
1179
0
            bClose = true;
1180
0
        }
1181
0
    }
1182
0
    else
1183
0
    {
1184
0
        OUString aError;
1185
0
        uno::Reference<sheet::XSolverDescription> xDesc( xSolver, uno::UNO_QUERY );
1186
0
        if ( xDesc.is() )
1187
0
            aError = xDesc->getStatusDescription();         // error description from component
1188
0
        ScSolverNoSolutionDialog aDialog(m_xDialog.get(), aError);
1189
0
        aDialog.run();
1190
0
    }
1191
1192
0
    if ( bRestore )         // restore old values
1193
0
    {
1194
0
        mpDocShell->LockPaint();
1195
0
        ScDocFunc &rFunc = mpDocShell->GetDocFunc();
1196
0
        for (nVarPos=0; nVarPos<nVarCount; ++nVarPos)
1197
0
        {
1198
0
            ScAddress aCellPos;
1199
0
            ScUnoConversion::FillScAddress( aCellPos, aVariables[nVarPos] );
1200
0
            rFunc.SetValueCell(aCellPos, aOldValues[nVarPos], false);
1201
0
        }
1202
0
        mpDocShell->UnlockPaint();
1203
0
    }
1204
1205
    // Generate sensitivity report if user wants it
1206
0
    uno::Reference<css::beans::XPropertySetInfo> xInfo = xOptProp->getPropertySetInfo();
1207
0
    bool bUserWantsReport = false;
1208
0
    if (xInfo->hasPropertyByName("GenSensitivityReport"))
1209
0
        xOptProp->getPropertyValue("GenSensitivityReport") >>= bUserWantsReport;
1210
1211
0
    if (bSuccess && bUserWantsReport)
1212
0
    {
1213
        // Retrieve the sensitivity analysis report
1214
0
        css::sheet::SensitivityReport aSensitivity;
1215
0
        bool bHasReportObj = xOptProp->getPropertyValue("SensitivityReport") >>= aSensitivity;
1216
1217
0
        if (bHasReportObj && aSensitivity.HasReport)
1218
0
        {
1219
            // Define the Tab name where the sensitivity analysis will be written to
1220
0
            OUString sNewTabName;
1221
0
            SCTAB nNewTab;
1222
0
            mrDoc.GetName(mnCurTab, sNewTabName);
1223
0
            sNewTabName += "_" + ScResId(STR_SENSITIVITY);
1224
            // Check if the new Tab name exists
1225
0
            if (mrDoc.GetTable(sNewTabName, nNewTab))
1226
0
            {
1227
                // Add numbers to the end of the Tab name to make it unique
1228
0
                SCTAB i = 1;
1229
0
                OUString aName;
1230
0
                do
1231
0
                {
1232
0
                    i++;
1233
0
                    aName = sNewTabName + "_" + OUString::number(static_cast<sal_Int32>(i));
1234
0
                }
1235
0
                while(mrDoc.GetTable(aName, nNewTab));
1236
0
                sNewTabName = aName;
1237
0
            }
1238
1239
            // Insert new sheet to the document and start writing the report
1240
0
            ScDocFunc &rFunc = mpDocShell->GetDocFunc();
1241
0
            rFunc.InsertTable(mnCurTab + 1, sNewTabName, false, false);
1242
0
            SCTAB nReportTab;
1243
0
            if (!mrDoc.GetTable(sNewTabName, nReportTab))
1244
0
            {
1245
0
                SAL_WARN("sc", "Could not get the just inserted table!");
1246
0
                return false;
1247
0
            }
1248
1249
            // Used to input data in the new sheet
1250
0
            ScAddress aOutputAddress(0, 0, nReportTab);
1251
0
            ScAddress::Details mAddressDetails(mrDoc, aOutputAddress);
1252
0
            AddressWalkerWriter aOutput(aOutputAddress, mpDocShell, mrDoc,
1253
0
                                        formula::FormulaGrammar::mergeToGrammar(formula::FormulaGrammar::GRAM_ENGLISH, mAddressDetails.eConv));
1254
0
            aOutput.writeBoldString(ScResId(STR_SENSITIVITY_TITLE));
1255
0
            aOutput.newLine();
1256
0
            aOutput.writeString(ScResId(STR_SOLVER_ENGINE) + " " + maEngine);
1257
0
            aOutput.newLine();
1258
0
            aOutput.newLine();
1259
1260
            // Objective cell section
1261
0
            aOutput.writeBoldString(ScResId(STR_SENSITIVITY_OBJCELL));
1262
0
            aOutput.newLine();
1263
0
            aOutput.formatAsColumnHeader(2);
1264
0
            aOutput.writeString(ScResId(STR_SENSITIVITY_CELL));
1265
0
            aOutput.nextColumn();
1266
0
            aOutput.writeString(ScResId(STR_SENSITIVITY_FINALVALUE));
1267
0
            aOutput.newLine();
1268
0
            aOutput.formatTableBottom(2);
1269
0
            aOutput.writeString(GetCellStrAddress(xSolver->getObjective()));
1270
0
            aOutput.nextColumn();
1271
0
            aOutput.writeValue(xSolver->getResultValue());
1272
0
            aOutput.newLine();
1273
0
            aOutput.newLine();
1274
1275
            // Variable cell section
1276
0
            aOutput.writeBoldString(ScResId(STR_SENSITIVITY_VARCELLS));
1277
0
            aOutput.newLine();
1278
0
            aOutput.formatAsColumnHeader(6);
1279
0
            aOutput.writeString(ScResId(STR_SENSITIVITY_CELL));
1280
0
            aOutput.nextColumn();
1281
0
            aOutput.writeString(ScResId(STR_SENSITIVITY_FINALVALUE));
1282
0
            aOutput.nextColumn();
1283
0
            aOutput.writeString(ScResId(STR_SENSITIVITY_REDUCED));
1284
0
            aOutput.nextColumn();
1285
0
            aOutput.writeString(ScResId(STR_SENSITIVITY_OBJCOEFF));
1286
0
            aOutput.nextColumn();
1287
0
            aOutput.writeString(ScResId(STR_SENSITIVITY_DECREASE));
1288
0
            aOutput.nextColumn();
1289
0
            aOutput.writeString(ScResId(STR_SENSITIVITY_INCREASE));
1290
0
            aOutput.newLine();
1291
1292
0
            uno::Sequence<double> aSolution = xSolver->getSolution();
1293
0
            uno::Sequence<double> aObjCoefficients = aSensitivity.ObjCoefficients;
1294
0
            uno::Sequence<double> aObjReducedCosts = aSensitivity.ObjReducedCosts;
1295
0
            uno::Sequence<double> aObjAllowableDecreases = aSensitivity.ObjAllowableDecreases;
1296
0
            uno::Sequence<double> aObjAllowableIncreases = aSensitivity.ObjAllowableIncreases;
1297
0
            sal_Int32 nRows = aVariables.getLength();
1298
0
            for (sal_Int32 i = 0; i < nRows; i++)
1299
0
            {
1300
0
                if (i == nRows - 1)
1301
0
                    aOutput.formatTableBottom(6);
1302
0
                aOutput.writeString(GetCellStrAddress(aVariables[i]));
1303
0
                aOutput.nextColumn();
1304
0
                aOutput.writeValue(aSolution[i]);
1305
0
                aOutput.nextColumn();
1306
0
                aOutput.writeValue(aObjReducedCosts[i]);
1307
0
                aOutput.nextColumn();
1308
0
                aOutput.writeValue(aObjCoefficients[i]);
1309
0
                aOutput.nextColumn();
1310
0
                aOutput.writeValue(aObjAllowableDecreases[i]);
1311
0
                aOutput.nextColumn();
1312
0
                aOutput.writeValue(aObjAllowableIncreases[i]);
1313
0
                aOutput.newLine();
1314
0
            }
1315
0
            aOutput.newLine();
1316
1317
            // Constraints section
1318
0
            aOutput.writeBoldString(ScResId(STR_SENSITIVITY_CONSTRAINTS));
1319
0
            aOutput.newLine();
1320
0
            aOutput.formatAsColumnHeader(6);
1321
0
            aOutput.writeString(ScResId(STR_SENSITIVITY_CELL));
1322
0
            aOutput.nextColumn();
1323
0
            aOutput.writeString(ScResId(STR_SENSITIVITY_FINALVALUE));
1324
0
            aOutput.nextColumn();
1325
0
            aOutput.writeString(ScResId(STR_SENSITIVITY_SHADOWPRICE));
1326
0
            aOutput.nextColumn();
1327
0
            aOutput.writeString(ScResId(STR_SENSITIVITY_RHS));
1328
0
            aOutput.nextColumn();
1329
0
            aOutput.writeString(ScResId(STR_SENSITIVITY_DECREASE));
1330
0
            aOutput.nextColumn();
1331
0
            aOutput.writeString(ScResId(STR_SENSITIVITY_INCREASE));
1332
0
            aOutput.newLine();
1333
1334
0
            uno::Sequence<double> aConstrValues = aSensitivity.ConstrValues;
1335
0
            uno::Sequence<double> aConstrRHS = aSensitivity.ConstrRHS;
1336
0
            uno::Sequence<double> aConstrShadowPrices = aSensitivity.ConstrShadowPrices;
1337
0
            uno::Sequence<double> aConstrAllowableDecreases = aSensitivity.ConstrAllowableDecreases;
1338
0
            uno::Sequence<double> aConstrAllowableIncreases = aSensitivity.ConstrAllowableIncreases;
1339
0
            nRows = aConstraints.getLength();
1340
0
            for (sal_Int32 i = 0; i < nRows; i++)
1341
0
            {
1342
0
                if (i == nRows - 1)
1343
0
                    aOutput.formatTableBottom(6);
1344
0
                aOutput.writeString(GetCellStrAddress(aConstraints[i].Left));
1345
0
                aOutput.nextColumn();
1346
0
                aOutput.writeValue(aConstrValues[i]);
1347
0
                aOutput.nextColumn();
1348
0
                aOutput.writeValue(aConstrShadowPrices[i]);
1349
0
                aOutput.nextColumn();
1350
0
                aOutput.writeValue(aConstrRHS[i]);
1351
0
                aOutput.nextColumn();
1352
0
                aOutput.writeValue(aConstrAllowableDecreases[i]);
1353
0
                aOutput.nextColumn();
1354
0
                aOutput.writeValue(aConstrAllowableIncreases[i]);
1355
0
                aOutput.newLine();
1356
0
            }
1357
1358
            // Disable grid lines in the sensitivity report
1359
0
            if (ScTabViewShell* pViewSh = ScTabViewShell::GetActiveViewShell())
1360
0
            {
1361
0
                ScViewData& rData = pViewSh->GetViewData();
1362
0
                rData.SetTabNo(nReportTab);
1363
0
                rData.SetShowGrid(false);
1364
0
                rData.SetTabNo(mnCurTab);
1365
0
            }
1366
0
        }
1367
0
    }
1368
1369
0
    return bClose;
1370
0
}
1371
1372
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */