Debian Codegraph @

plugins/dm.objectives/ComponentsDialog.cpp

raw
1 #include "ComponentsDialog.h"
2 #include "Objective.h"
3 #include "ce/ComponentEditorFactory.h"
4
5 #include "itextstream.h"
6 #include "string/convert.h"
7
8 #include "i18n.h"
9 #include <vector>
10
11 #include "wxutil/ChoiceHelper.h"
12 #include <wx/panel.h>
13 #include <wx/button.h>
14 #include <wx/textctrl.h>
15 #include <wx/stattext.h>
16 #include <wx/choice.h>
17 #include <wx/sizer.h>
18 #include <wx/checkbox.h>
19
20 namespace objectives
21 {
22
23 /* CONSTANTS */
24
25 namespace
26 {
27
28 const char* const DIALOG_TITLE = N_("Edit Objective");
29
30 } // namespace
31
32 // Main constructor
33 ComponentsDialog::ComponentsDialog(wxWindow* parent, Objective& objective) :
34 DialogBase(_(DIALOG_TITLE), parent),
35 _objective(objective),
36 _componentList(new wxutil::TreeModel(_columns, true)),
37 _components(objective.components), // copy the components to our local working set
38 _updateMutex(false),
39 _updateNeeded(false)
40 {
41 wxPanel* mainPanel = loadNamedPanel(this, "ObjCompMainPanel");
42
43 // Dialog contains list view, edit panel and buttons
44 setupObjectiveEditPanel();
45
46 makeLabelBold(this, "ObjCompListLabel");
47
48 createListView();
49 setupEditPanel();
50
51 // Populate the list of components
52 populateObjectiveEditPanel();
53 populateComponents();
54
55 mainPanel->Layout();
56 mainPanel->Fit();
57 Fit();
58 CenterOnParent();
59 }
60
61 ComponentsDialog::~ComponentsDialog()
62 {
63 }
64
65 // Create the panel for editing the currently-selected objective
66 void ComponentsDialog::setupObjectiveEditPanel()
67 {
68 _objDescriptionEntry = findNamedObject<wxTextCtrl>(this, "ObjCompDescription");
69 _objStateCombo = findNamedObject<wxChoice>(this, "ObjCompInitialState");
70
71 _diffPanel.reset(new DifficultyPanel(findNamedObject<wxPanel>(this, "ObjCompDiffPanel")));
72
73 // Populate the list of states. This must be done in order to match the
74 // values in the enum, since the index will be used when writing to entity
75 _objStateCombo->Append(Objective::getStateText(Objective::INCOMPLETE),
76 new wxStringClientData(string::to_string(Objective::INCOMPLETE)));
77 _objStateCombo->Append(Objective::getStateText(Objective::COMPLETE),
78 new wxStringClientData(string::to_string(Objective::COMPLETE)));
79 _objStateCombo->Append(Objective::getStateText(Objective::INVALID),
80 new wxStringClientData(string::to_string(Objective::INVALID)));
81 _objStateCombo->Append(Objective::getStateText(Objective::FAILED),
82 new wxStringClientData(string::to_string(Objective::FAILED)));
83
84 _objMandatoryFlag = findNamedObject<wxCheckBox>(this, "ObjCompObjMandatory");
85 _objIrreversibleFlag = findNamedObject<wxCheckBox>(this, "ObjCompObjIrreversible");
86 _objOngoingFlag = findNamedObject<wxCheckBox>(this, "ObjCompObjOngoing");
87 _objVisibleFlag = findNamedObject<wxCheckBox>(this, "ObjCompObjVisible");
88
89 // Enabling objectives
90 _enablingObjs = findNamedObject<wxTextCtrl>(this, "ObjCompEnablingObjectives");
91
92 // Logic
93 _successLogic = findNamedObject<wxTextCtrl>(this, "ObjCompSuccessLogic");
94 _failureLogic = findNamedObject<wxTextCtrl>(this, "ObjCompFailureLogic");
95
96 // Completion/failure scripts
97 _completionScript = findNamedObject<wxTextCtrl>(this, "ObjCompCompletionScript");
98 _failureScript = findNamedObject<wxTextCtrl>(this, "ObjCompFailureScript");
99
100 // Completion/failure targets
101 _completionTarget = findNamedObject<wxTextCtrl>(this, "ObjCompCompletionTarget");
102 _failureTarget = findNamedObject<wxTextCtrl>(this, "ObjCompFailureTarget");
103 }
104
105 // Create list view
106 void ComponentsDialog::createListView()
107 {
108 // Create tree view and connect selection changed callback
109 wxPanel* treeViewPanel = findNamedObject<wxPanel>(this, "ObjCompListViewPanel");
110 _componentView = wxutil::TreeView::CreateWithModel(treeViewPanel, _componentList.get());
111 treeViewPanel->GetSizer()->Add(_componentView, 1, wxEXPAND);
112 treeViewPanel->SetMinClientSize(wxSize(-1, 90));
113
114 _componentView->Connect(wxEVT_DATAVIEW_SELECTION_CHANGED,
115 wxDataViewEventHandler(ComponentsDialog::_onSelectionChanged), NULL, this);
116
117 _componentView->AppendTextColumn("#", _columns.index.getColumnIndex(),
118 wxDATAVIEW_CELL_INERT, wxCOL_WIDTH_AUTOSIZE, wxALIGN_NOT, wxDATAVIEW_COL_SORTABLE);
119 _componentView->AppendTextColumn(_("Type"), _columns.description.getColumnIndex(),
120 wxDATAVIEW_CELL_INERT, wxCOL_WIDTH_AUTOSIZE, wxALIGN_NOT, wxDATAVIEW_COL_SORTABLE);
121
122 // Create Add and Delete buttons for components
123 wxButton* addButton = findNamedObject<wxButton>(this, "ObjCompAddComponentButton");
124 wxButton* delButton = findNamedObject<wxButton>(this, "ObjCompDeleteComponentButton");
125
126 addButton->Connect(wxEVT_BUTTON, wxCommandEventHandler(ComponentsDialog::_onAddComponent), NULL, this);
127 delButton->Connect(wxEVT_BUTTON, wxCommandEventHandler(ComponentsDialog::_onDeleteComponent), NULL, this);
128 }
129
130 // Create edit panel
131 void ComponentsDialog::setupEditPanel()
132 {
133 // Table
134 _editPanel = findNamedObject<wxPanel>(this, "ObjCompComponentEditPanel");
135 _editPanel->Enable(false); // disabled at start
136
137 // Component type dropdown
138 _typeCombo = findNamedObject<wxChoice>(this, "ObjCompComponentType");
139 _typeCombo->Connect(wxEVT_CHOICE, wxCommandEventHandler(ComponentsDialog::_onTypeChanged), NULL, this);
140
141 // Populate the combo box. The set is in ID order.
142 for (ComponentTypeSet::const_iterator i = ComponentType::SET_ALL().begin();
143 i != ComponentType::SET_ALL().end();
144 ++i)
145 {
146 _typeCombo->Append(i->getDisplayName(), new wxStringClientData(string::to_string(i->getId())));
147 }
148
149 // Flags hbox
150 _stateFlag = findNamedObject<wxCheckBox>(this, "ObjCompSatisfiedAtStart");
151 _irreversibleFlag = findNamedObject<wxCheckBox>(this, "ObjCompIrreversible");
152 _invertedFlag = findNamedObject<wxCheckBox>(this, "ObjCompBooleanNOT");
153 _playerResponsibleFlag = findNamedObject<wxCheckBox>(this, "ObjCompPlayerResponsible");
154
155 _stateFlag->Connect(wxEVT_CHECKBOX, wxCommandEventHandler(ComponentsDialog::_onCompToggleChanged), NULL, this);
156 _irreversibleFlag->Connect(wxEVT_CHECKBOX, wxCommandEventHandler(ComponentsDialog::_onCompToggleChanged), NULL, this);
157 _invertedFlag->Connect(wxEVT_CHECKBOX, wxCommandEventHandler(ComponentsDialog::_onCompToggleChanged), NULL, this);
158 _playerResponsibleFlag->Connect(wxEVT_CHECKBOX, wxCommandEventHandler(ComponentsDialog::_onCompToggleChanged), NULL, this);
159
160 _compEditorPanel = findNamedObject<wxPanel>(this, "ObjCompEditorContainer");
161 }
162
163 // Populate the component list
164 void ComponentsDialog::populateComponents()
165 {
166 // Clear the list store
167 _componentList->Clear();
168
169 // Add components from the Objective to the list store
170 for (Objective::ComponentMap::iterator i = _components.begin();
171 i != _components.end();
172 ++i)
173 {
174 wxutil::TreeModel::Row row = _componentList->AddItem();
175
176 row[_columns.index] = i->first;
177 row[_columns.description] = i->second.getString();
178
179 row.SendItemAdded();
180 }
181
182 _updateNeeded = true;
183 }
184
185 void ComponentsDialog::updateComponents()
186 {
187 // Traverse all components and update the items in the list
188 for (Objective::ComponentMap::iterator i = _components.begin();
189 i != _components.end();
190 ++i)
191 {
192 // Find the item in the list store (0th column carries the ID)
193 wxDataViewItem item = _componentList->FindInteger(i->first, _columns.index);
194
195 // Check if we found the item
196 if (item.IsOk())
197 {
198 wxutil::TreeModel::Row row(item, *_componentList);
199
200 row[_columns.index] = i->first;
201 row[_columns.description] = i->second.getString();
202
203 row.SendItemChanged();
204 }
205 }
206 }
207
208 // Populate the edit panel
209 void ComponentsDialog::populateEditPanel(int index)
210 {
211 // Get the component
212 Component& comp = _components[index];
213
214 // Set the flags
215 _stateFlag->SetValue(comp.isSatisfied());
216 _irreversibleFlag->SetValue(comp.isIrreversible());
217 _invertedFlag->SetValue(comp.isInverted());
218 _playerResponsibleFlag->SetValue(comp.isPlayerResponsible());
219
220 // Change the type combo if necessary.
221 // Since the combo box was populated in
222 // ID order, we can simply use our ComponentType's ID as an index.
223 if (_typeCombo->GetSelection() != comp.getType().getId())
224 {
225 // Change the combo selection
226 _typeCombo->Select(comp.getType().getId());
227
228 // Trigger component change, to update editor panel
229 handleTypeChange();
230 }
231 else
232 {
233 // Update the ComponentEditor ourselves, since the new Component has the
234 // same type but we still want to refresh the panel with the new
235 // contents
236 changeComponentEditor(comp);
237 }
238 }
239
240 // Populate the edit panel widgets using the given objective number
241 void ComponentsDialog::populateObjectiveEditPanel()
242 {
243 // Disable callbacks while we're at it
244 _updateMutex = true;
245
246 // Get the objective
247 const Objective& obj = _objective;
248
249 // Set description text
250 _objDescriptionEntry->SetValue(obj.description);
251
252 // Update the difficulty panel
253 _diffPanel->populateFromObjective(obj);
254
255 // Set initial state enum
256 wxutil::ChoiceHelper::SelectItemByStoredId(_objStateCombo, static_cast<int>(obj.state));
257
258 // Set flags
259 _objIrreversibleFlag->SetValue(obj.irreversible);
260 _objOngoingFlag->SetValue(obj.ongoing);
261 _objMandatoryFlag->SetValue(obj.mandatory);
262 _objVisibleFlag->SetValue(obj.visible);
263
264 _enablingObjs->SetValue(obj.enablingObjs);
265
266 _successLogic->SetValue(obj.logic.successLogic);
267 _failureLogic->SetValue(obj.logic.failureLogic);
268
269 _completionScript->SetValue(obj.completionScript);
270 _failureScript->SetValue(obj.failureScript);
271
272 _completionTarget->SetValue(obj.completionTarget);
273 _failureTarget->SetValue(obj.failureTarget);
274
275 _updateMutex = false;
276 }
277
278 // Get selected component index
279 int ComponentsDialog::getSelectedIndex()
280 {
281 // Get the selection if valid
282 wxDataViewItem item = _componentView->GetSelection();
283
284 if (item.IsOk())
285 {
286 // Valid selection, return the contents of the index column
287 wxutil::TreeModel::Row row(item, *_componentList);
288 return row[_columns.index].getInteger();
289 }
290 else
291 {
292 return -1;
293 }
294 }
295
296 // Change component editor
297 void ComponentsDialog::changeComponentEditor(Component& compToEdit)
298 {
299 // greebo: Get a new component editor, any previous one will auto-destroy and
300 // remove its widget from the container.
301 _componentEditor = ce::ComponentEditorFactory::create(
302 _compEditorPanel, compToEdit.getType().getName(), compToEdit
303 );
304
305 if (_componentEditor)
306 {
307 // The widgets are constructed and filled with correct values,
308 // from this point on we can write updates to the component automatically
309 _componentEditor->setActive(true);
310
311 // Get the widget from the ComponentEditor and show it
312 // Pack the widget into the containing frame
313 _compEditorPanel->GetSizer()->Add(_componentEditor->getWidget(), 1, wxEXPAND | wxALL, 12);
314
315 _compEditorPanel->Layout();
316 _compEditorPanel->Fit();
317 findNamedObject<wxPanel>(this, "ObjCompMainPanel")->Fit();
318 Fit();
319 }
320 }
321
322 // Safely write the ComponentEditor contents to the Component
323 void ComponentsDialog::checkWriteComponent()
324 {
325 if (_componentEditor)
326 {
327 _componentEditor->writeToComponent();
328 }
329 }
330
331 void ComponentsDialog::save()
332 {
333 // Write the objective properties
334 _objective.description = _objDescriptionEntry->GetValue().ToStdString();
335
336 // Save the difficulty settings
337 _diffPanel->writeToObjective(_objective);
338
339 // Set the initial state enum value from the combo box index
340 _objective.state = static_cast<Objective::State>(
341 wxutil::ChoiceHelper::GetSelectionId(_objStateCombo));
342
343 // Determine which checkbox is toggled, then update the appropriate flag
344 _objective.mandatory = _objMandatoryFlag->GetValue();
345 _objective.visible = _objVisibleFlag->GetValue();
346 _objective.ongoing = _objOngoingFlag->GetValue();
347 _objective.irreversible = _objIrreversibleFlag->GetValue();
348
349 // Enabling objectives
350 _objective.enablingObjs = _enablingObjs->GetValue();
351
352 // Success/failure logic
353 _objective.logic.successLogic = _successLogic->GetValue();
354 _objective.logic.failureLogic = _failureLogic->GetValue();
355
356 // Completion/Failure script
357 _objective.completionScript = _completionScript->GetValue();
358 _objective.failureScript = _failureScript->GetValue();
359
360 // Completion/Failure targets
361 _objective.completionTarget = _completionTarget->GetValue();
362 _objective.failureTarget = _failureTarget->GetValue();
363
364 // Write the components
365 checkWriteComponent();
366
367 // Copy the working set over the ones in the objective
368 _objective.components.swap(_components);
369 }
370
371 int ComponentsDialog::ShowModal()
372 {
373 int returnCode = DialogBase::ShowModal();
374
375 if (returnCode == wxID_OK)
376 {
377 save();
378 }
379
380 return returnCode;
381 }
382
383 void ComponentsDialog::_onCompToggleChanged(wxCommandEvent& ev)
384 {
385 if (_updateMutex) return;
386
387 // Update the Component working copy. The selected index must be valid, since the
388 // edit panel is only sensitive if a component is selected
389 int idx = getSelectedIndex();
390 assert(idx >= 0);
391
392 Component& comp = _components[idx];
393
394 wxCheckBox* checkbox = dynamic_cast<wxCheckBox*>(ev.GetEventObject());
395
396 if (checkbox == _stateFlag)
397 {
398 comp.setSatisfied(checkbox->GetValue());
399 }
400 else if (checkbox == _irreversibleFlag)
401 {
402 comp.setIrreversible(checkbox->GetValue());
403 }
404 else if (checkbox == _invertedFlag)
405 {
406 comp.setInverted(checkbox->GetValue());
407 }
408 else if (checkbox == _playerResponsibleFlag)
409 {
410 comp.setPlayerResponsible(checkbox->GetValue());
411 }
412
413 // Update the list store
414 updateComponents();
415 }
416
417 void ComponentsDialog::handleSelectionChange()
418 {
419 // Save the existing ComponentEditor contents if req'd
420 checkWriteComponent();
421
422 // Disconnect notification callback
423 _componentChanged.disconnect();
424
425 // Get the selection if valid
426 wxDataViewItem item = _componentView->GetSelection();
427
428 if (!item.IsOk())
429 {
430 // Disable the edit panel and remove the ComponentEditor
431 _compEditorPanel->Enable(false);
432 _editPanel->Enable(false);
433 _componentEditor = objectives::ce::ComponentEditorPtr();
434 }
435 else
436 {
437 // Otherwise populate edit panel with the current component index
438 wxutil::TreeModel::Row row(item, *_componentList);
439 int index = row[_columns.index].getInteger();
440
441 populateEditPanel(index);
442
443 // Enable the edit panel
444 _compEditorPanel->Enable(true);
445 _editPanel->Enable(true);
446
447 // Subscribe to the component
448 Component& comp = _components[index];
449 _componentChanged = comp.signal_Changed().connect(
450 sigc::mem_fun(*this, &ComponentsDialog::_onComponentChanged));
451 }
452 }
453
454 void ComponentsDialog::_onComponentChanged()
455 {
456 wxDataViewItem item = _componentView->GetSelection();
457
458 if (!item.IsOk()) return;
459
460 updateComponents();
461 }
462
463 // Selection changed
464 void ComponentsDialog::_onSelectionChanged(wxDataViewEvent& ev)
465 {
466 handleSelectionChange();
467 }
468
469 // Add a new component
470 void ComponentsDialog::_onAddComponent(wxCommandEvent& ev)
471 {
472 Objective::ComponentMap& components = _components;
473
474 // Find an unused component number (starting from 1)
475 for (int idx = 1; idx < INT_MAX; ++idx)
476 {
477 if (components.find(idx) == components.end()) {
478 // Unused, add a new component here
479 Component comp;
480 components.insert(std::make_pair(idx, comp));
481 break;
482 }
483 }
484
485 // Refresh the component list
486 populateComponents();
487 }
488
489 // Remove a component
490 void ComponentsDialog::_onDeleteComponent(wxCommandEvent& ev)
491 {
492 // Delete the selected component
493 int idx = getSelectedIndex();
494
495 if (idx != -1)
496 {
497 // Remove the selection first, so our selection-changed callback does not
498 // attempt to writeToComponent() after the Component has already been deleted
499 _componentView->UnselectAll();
500
501 // UnselectAll doesn't seem to trigger a selection change
502 handleSelectionChange();
503
504 // Erase the actual component
505 _components.erase(idx);
506
507 // #5810: Re-index the remaining components (shift all higher ones by -1)
508 auto highestKey = _components.rbegin();
509
510 if (highestKey != _components.rend())
511 {
512 for (auto key = idx + 1; key <= highestKey->first; ++key)
513 {
514 // Attempt to move the component with the given key
515 auto node = _components.extract(key);
516
517 // If a component was unlinked from the map, move it downwards by one index
518 if (!node.empty())
519 {
520 node.key()--;
521 _components.insert(std::move(node));
522 }
523 }
524 }
525 }
526
527 // Refresh the list
528 populateComponents();
529 }
530
531 void ComponentsDialog::handleTypeChange()
532 {
533 // Get the current selection
534 int typeId = wxutil::ChoiceHelper::GetSelectionId(_typeCombo);
535
536 // Update the Objective object. The selected index must be valid, since the
537 // edit panel is only sensitive if a component is selected
538 int idx = getSelectedIndex();
539 assert(idx >= 0);
540
541 Component& comp = _components[idx];
542
543 // Store the newly-selected type in the Component
544 comp.setType(ComponentType::getComponentType(typeId));
545
546 // Change the ComponentEditor
547 changeComponentEditor(comp);
548
549 // Update the components list with the new display string
550 wxutil::TreeModel::Row row(_componentView->GetSelection(), *_componentList);
551
552 row[_columns.description] = comp.getString();
553 row.SendItemChanged();
554
555 _updateNeeded = true;
556 }
557
558 // Type combo changed
559 void ComponentsDialog::_onTypeChanged(wxCommandEvent& ev)
560 {
561 handleTypeChange();
562 }
563
564 } // namespace objectives