Debian Codegraph @

layla/ligand_editor_canvas/tools.cpp

raw
1 /* layla/ligand_editor_canvas/tools.cpp
2 *
3 * Copyright 2023 by Global Phasing Ltd.
4 * Author: Jakub Smulski
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or (at
9 * your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 * 02110-1301, USA
20 */
21
22 #include "tools.hpp"
23 #include "core.hpp"
24 #include "model.hpp"
25 #include <exception>
26 #include <algorithm>
27 #include <memory>
28 #include <optional>
29 #include <stdexcept>
30 #include <string>
31 #include <utility>
32 #include <variant>
33 #include <boost/range/iterator_range.hpp>
34 #include <rdkit/GraphMol/MolOps.h>
35 #include <rdkit/GraphMol/PeriodicTable.h>
36 #include <rdkit/GraphMol/QueryOps.h>
37 #include "../ligand_editor_canvas.hpp"
38 #include "../utils.hpp"
39
40 using namespace coot::ligand_editor_canvas;
41
42 void Tool::on_load(impl::WidgetCoreData& widget_data) {
43 // nothing by default
44 }
45
46 void Tool::on_click(ClickContext& ctx, int x, int y) {
47 // nothing by default
48 }
49
50 void Tool::on_blank_space_click(ClickContext& ctx, int x, int y) {
51 g_debug("The click could not be resolved to any atom or bond.");
52 }
53
54 void Tool::on_release(ClickContext& ctx, int x, int y) {
55 // nothing by default
56 }
57
58 void Tool::after_molecule_click(MoleculeClickContext& ctx) {
59 // nothing by default
60 }
61
62 bool Tool::on_molecule_click(MoleculeClickContext& ctx) {
63 // nothing by default
64 return true;
65 }
66
67 void Tool::on_bond_click(MoleculeClickContext& ctx, CanvasMolecule::Bond&) {
68 // nothing by default
69 g_debug("The tool does not operate on bonds.");
70 }
71
72 void Tool::on_atom_click(MoleculeClickContext& ctx, CanvasMolecule::Atom&) {
73 // nothing by default
74 g_debug("The tool does not operate on atoms.");
75 }
76
77 void Tool::on_right_click(ClickContext& ctx, int x, int y) {
78 // nothing by default
79 }
80
81 void Tool::on_blank_space_right_click(ClickContext& ctx, int x, int y) {
82 g_debug("The click could not be resolved to any atom or bond.");
83 }
84
85 bool Tool::on_molecule_right_click(MoleculeClickContext& ctx) {
86 // nothing by default
87 return true;
88 }
89
90 void Tool::on_bond_right_click(MoleculeClickContext& ctx, CanvasMolecule::Bond&) {
91 // nothing by default
92 g_debug("The tool does not handle right-click on bonds.");
93 }
94
95 void Tool::on_atom_right_click(MoleculeClickContext& ctx, CanvasMolecule::Atom&) {
96 // nothing by default
97 g_debug("The tool does not handle right-click on atoms.");
98 }
99
100 void Tool::after_molecule_right_click(MoleculeClickContext& ctx) {
101 // nothing by default
102 }
103
104 bool Tool::on_hover(ClickContext& ctx, int x, int y) {
105 // not processing hover events by default
106 return false;
107 }
108
109 void Tool::on_blank_space_hover(ClickContext& ctx, int x, int y) {
110 // nothing by default
111 }
112
113 bool Tool::on_molecule_hover(MoleculeClickContext& ctx) {
114 // nothing by default
115 return true;
116 }
117
118 void Tool::on_bond_hover(MoleculeClickContext& ctx, CanvasMolecule::Bond&) {
119 // nothing by default
120 }
121
122 void Tool::on_atom_hover(MoleculeClickContext& ctx, CanvasMolecule::Atom&) {
123 // nothing by default
124 }
125
126 void Tool::after_molecule_hover(MoleculeClickContext& ctx) {
127 // nothing by default
128 }
129
130 std::string Tool::get_exception_message_prefix() const noexcept {
131 return "An error occured: ";
132 }
133
134 Tool::~Tool() {
135
136 }
137
138 Tool::ClickContext::ClickContext(impl::WidgetCoreData& widget_data) :widget_data(widget_data) {
139
140 }
141
142 Tool::MoleculeClickContext::MoleculeClickContext(ClickContext super, unsigned int mol_idx, std::shared_ptr<RDKit::RWMol>& rdkit_mol, CanvasMolecule& canvas_mol)
143 :ClickContext(super), rdkit_mol(rdkit_mol), canvas_mol(canvas_mol) {
144 this->mol_idx = mol_idx;
145 }
146
147 void ActiveTool::on_load() {
148 if(this->tool) {
149 this->tool->on_load(*this->widget_data);
150 }
151 }
152
153 void ActiveTool::on_click(bool alt_pressed, bool ctrl_pressed, int x, int y, bool right_click) {
154 if(!this->tool) {
155 return;
156 }
157 Tool::ClickContext ctx(*this->widget_data);
158 ctx.control_pressed = ctrl_pressed;
159 ctx.alt_pressed = alt_pressed;
160
161
162 if(!right_click) {
163 this->tool->on_click(ctx, x, y);
164 } else {
165 this->tool->on_right_click(ctx, x, y);
166 }
167 auto click_result = this->widget_data->resolve_click(x, y);
168 if(click_result.has_value()) {
169 auto [bond_or_atom,molecule_idx] = *click_result;
170 auto& rdkit_mol = *this->widget_data->rdkit_molecules->at(molecule_idx);
171 auto& canvas_mol = *this->widget_data->molecules->at(molecule_idx);
172 try{
173 Tool::MoleculeClickContext mctx(ctx, molecule_idx, rdkit_mol, canvas_mol);
174 if(!right_click) {
175 if(!this->tool->on_molecule_click(mctx)) {
176 return;
177 }
178 } else {
179 if(!this->tool->on_molecule_right_click(mctx)) {
180 return;
181 }
182 }
183 if(std::holds_alternative<CanvasMolecule::Atom>(bond_or_atom)) {
184 auto atom = std::get<CanvasMolecule::Atom>(std::move(bond_or_atom));
185 if(!right_click) {
186 this->tool->on_atom_click(mctx, atom);
187 } else {
188 this->tool->on_atom_right_click(mctx, atom);
189 }
190 } else { // a bond
191 auto bond = std::get<CanvasMolecule::Bond>(std::move(bond_or_atom));
192 if(!right_click) {
193 this->tool->on_bond_click(mctx, bond);
194 } else {
195 this->tool->on_bond_right_click(mctx, bond);
196 }
197 }
198 if(!right_click) {
199 this->tool->after_molecule_click(mctx);
200 } else {
201 this->tool->after_molecule_right_click(mctx);
202 }
203 // } catch(RDKit::AtomSanitizeException& e) {
204 // g_warning("Invalid change: %s",e.what());
205 // std::string msg = "Invalid change: "; msg += e.what();
206 // this->widget_data->update_status(msg.c_str());
207 // this->widget_data->rollback_current_edition();
208 // canvas_mol.highlight_atom(e.getAtomIdx(), CanvasMolecule::HighlightType::Error);
209
210 } catch(std::exception& e) {
211 g_warning("An error occured: %s",e.what());
212 std::string msg = this->tool->get_exception_message_prefix() + e.what();
213 this->widget_data->update_status(msg.c_str());
214 this->widget_data->rollback_current_edition();
215 }
216 } else {
217 if(!right_click) {
218 this->tool->on_blank_space_click(ctx, x, y);
219 } else {
220 this->tool->on_blank_space_right_click(ctx, x, y);
221 }
222 }
223 }
224
225 void ActiveTool::on_release(bool alt_pressed, bool ctrl_pressed, int x, int y, bool right_click) {
226 if(!this->tool) {
227 return;
228 }
229 Tool::ClickContext ctx(*this->widget_data);
230 ctx.control_pressed = ctrl_pressed;
231 ctx.alt_pressed = alt_pressed;
232
233 if(right_click) {
234 g_warning("todo: Add support for releasing right-clicks in the tools API (when needed).");
235 return;
236 }
237
238 this->tool->on_release(ctx, x, y);
239 }
240
241 void ActiveTool::on_hover(bool alt_pressed, bool ctrl_pressed, int x, int y) {
242 if(!this->tool) {
243 return;
244 }
245 Tool::ClickContext ctx(*this->widget_data);
246 ctx.control_pressed = ctrl_pressed;
247 ctx.alt_pressed = alt_pressed;
248
249 if(!this->tool->on_hover(ctx, x, y)) {
250 return;
251 }
252 auto hover_result = this->widget_data->resolve_click(x, y);
253 if(hover_result.has_value()) {
254 auto [bond_or_atom,molecule_idx] = *hover_result;
255 auto& rdkit_mol = *this->widget_data->rdkit_molecules->at(molecule_idx);
256 auto& canvas_mol = *this->widget_data->molecules->at(molecule_idx);
257 try{
258 Tool::MoleculeClickContext mctx(ctx, molecule_idx, rdkit_mol, canvas_mol);
259 if(!this->tool->on_molecule_hover(mctx)) {
260 return;
261 }
262 if(std::holds_alternative<CanvasMolecule::Atom>(bond_or_atom)) {
263 auto atom = std::get<CanvasMolecule::Atom>(std::move(bond_or_atom));
264 this->tool->on_atom_hover(mctx, atom);
265 } else { // a bond
266 auto bond = std::get<CanvasMolecule::Bond>(std::move(bond_or_atom));
267 this->tool->on_bond_hover(mctx, bond);
268 }
269 this->tool->after_molecule_hover(mctx);
270 } catch(std::exception& e) {
271 g_warning("An error occured: %s",e.what());
272 std::string msg = this->tool->get_exception_message_prefix() + e.what();
273 this->widget_data->update_status(msg.c_str());
274 this->widget_data->rollback_current_edition();
275 }
276 } else {
277 this->tool->on_blank_space_hover(ctx, x, y);
278 }
279 }
280
281
282 void TransformTool::on_click(ClickContext& ctx, int x, int y) {
283 auto mol_opt = ctx.widget_data.resolve_click(x, y);
284 if(mol_opt.has_value()) {
285 auto [atom_or_bond,mol_id] = mol_opt.value();
286 this->transform_manager->begin_transform(x, y, this->mode);
287 this->transform_manager->set_canvas_molecule_index(mol_id);
288 ctx.widget_data.begin_edition();
289 }
290 }
291
292 bool TransformTool::on_molecule_click(MoleculeClickContext& ctx) {
293 return false;
294 }
295
296 TransformTool::TransformTool(TransformManager::Mode mode) noexcept {
297 this->mode = mode;
298 this->transform_manager = nullptr;
299 }
300
301 void TransformTool::set_transform_manager(TransformManager* mgr) noexcept {
302 this->transform_manager = mgr;
303 }
304
305
306 BondModifier::BondModifier(BondModifierMode mode) noexcept {
307 this->mode = mode;
308 this->molecule_idx_and_first_atom_of_new_bond = std::nullopt;
309 this->is_in_drag = false;
310 }
311
312 bool BondModifier::is_creating_bond() const noexcept {
313 return this->is_in_drag;
314 }
315
316 void BondModifier::begin_creating_bond(unsigned int molecule_idx, unsigned int atom_idx) noexcept {
317 this->is_in_drag = true;
318 this->molecule_idx_and_first_atom_of_new_bond = std::make_pair(molecule_idx,atom_idx);
319 }
320
321 void BondModifier::finish_creating_bond() noexcept {
322 this->is_in_drag = false;
323 this->molecule_idx_and_first_atom_of_new_bond = std::nullopt;
324 }
325
326 std::optional<std::pair<unsigned int,unsigned int>> BondModifier::get_molecule_idx_and_first_atom_of_new_bond() const noexcept {
327 return this->molecule_idx_and_first_atom_of_new_bond;
328 }
329
330
331 TransformManager::TransformManager() noexcept {
332 this->state = IdleState();
333 }
334
335 bool TransformManager::is_active() const noexcept {
336 return !std::holds_alternative<IdleState>(this->state);
337 }
338
339 void TransformManager::begin_transform(int x, int y, Mode mode) noexcept {
340 switch(mode) {
341 case Mode::Rotation: {
342 auto rot = RotationState();
343 rot.original_rotation_pos = std::make_pair(x,y);
344 rot.current_rotation_pos = std::make_pair(x, y);
345 rot.last_absolute_angle = 0.f;
346 this->state = rot;
347 break;
348 }
349 case Mode::Translation: {
350 auto tr = TranslationState();
351 tr.prev_move_pos = std::make_pair(x,y);
352 tr.current_move_pos = std::make_pair(x, y);
353 this->state = tr;
354 break;
355 }
356 }
357 }
358
359 double TransformManager::RotationState::get_current_absolute_angle(bool snap_to_angle) const {
360 auto [x1,y1] = this->original_rotation_pos;
361 auto [x2,y2] = this->current_rotation_pos;
362 auto diff_x = x2 - x1;
363 auto diff_y = y1 - y2;
364 auto diff_original = ((double)(diff_x + diff_y)) / 125.0;
365 if(snap_to_angle) {
366 const double snap = 15.f / 180 * M_PI;
367 int divided = diff_original / snap;
368 if(divided != 0) {
369 diff_original = divided * snap;
370 } else {
371 diff_original = 0;
372 }
373 }
374 return diff_original;
375 }
376
377 void TransformManager::update_current_cursor_pos(int x, int y, bool snap) noexcept {
378 RotationState* rot = std::get_if<RotationState>(&this->state);
379 if(rot) {
380 rot->last_absolute_angle = rot->get_current_absolute_angle(snap);
381 rot->current_rotation_pos = std::make_pair(x, y);
382 return;
383 }
384 TranslationState* tr = std::get_if<TranslationState>(&this->state);
385 if(tr) {
386 tr->prev_move_pos = tr->current_move_pos;
387 tr->current_move_pos = std::make_pair(x, y);
388 return;
389 }
390 }
391
392 void TransformManager::end_transform() noexcept {
393 this->state = IdleState();
394 this->canvas_mol_idx = std::nullopt;
395 }
396
397 void TransformManager::set_canvas_molecule_index(unsigned int idx) noexcept {
398 this->canvas_mol_idx = idx;
399 }
400
401 void TransformManager::apply_current_transform_state(impl::WidgetCoreData* widget_data, bool snap_to_angle, bool about_to_end) const {
402 if(!this->canvas_mol_idx.has_value()) {
403 return;
404 }
405 auto& mol = *widget_data->molecules->at(this->canvas_mol_idx.value());
406 const RotationState* rot = std::get_if<RotationState>(&this->state);
407 if(rot) {
408 auto angle = rot->get_current_angle_diff(snap_to_angle);
409 auto abs_angle = rot->get_current_absolute_angle(snap_to_angle) / M_PI * 180;
410 mol.rotate_by_angle(angle);
411 mol.lower_from_rdkit(!widget_data->allow_invalid_molecules, false);
412 std::string msg;
413 if (about_to_end) {
414 msg = "Molecule rotated by: " + std::to_string(abs_angle) + " degrees.";
415 } else {
416 msg = "Current molecule rotation: " + std::to_string(abs_angle) + " degrees.";
417 }
418 widget_data->update_status(msg.c_str());
419 return;
420 }
421 const TranslationState* tr = std::get_if<TranslationState>(&this->state);
422 if(tr) {
423 auto [offset_x,offset_y] = tr->get_current_offset();
424 mol.apply_canvas_translation(offset_x, offset_y);
425 return;
426 }
427 }
428
429 std::pair<int,int> TransformManager::TranslationState::get_current_offset() const {
430 auto [x1,y1] = this->prev_move_pos;
431 auto [x2,y2] = this->current_move_pos;
432 return std::make_pair(x2 - x1, y2 - y1);
433 }
434
435 double TransformManager::RotationState::get_current_angle_diff(bool snap_to_angle) const {
436 auto original = this->get_current_absolute_angle(snap_to_angle);
437 auto diff = original - this->last_absolute_angle;
438 return diff;
439 }
440
441 StructureInsertion::StructureInsertion(StructureInsertion::Structure st) noexcept
442 :structure(st) {
443
444 }
445
446 StructureInsertion::Structure StructureInsertion::get_structure() const noexcept {
447 return this->structure;
448 }
449
450
451 CanvasMolecule::BondType BondModifier::get_target_bond_type() const noexcept {
452 switch (this->mode) {
453 default:
454 case BondModifierMode::Single:{
455 return CanvasMolecule::BondType::Single;
456 }
457 case BondModifierMode::Double:{
458 return CanvasMolecule::BondType::Double;
459 }
460 case BondModifierMode::Triple:{
461 return CanvasMolecule::BondType::Triple;
462 }
463 }
464 }
465
466 ActiveTool::ActiveTool() noexcept {
467 // nothing
468 }
469
470 ActiveTool::ActiveTool(ElementInsertion insertion) noexcept {
471 this->tool = std::make_unique<ElementInsertion>(std::move(insertion));
472 }
473
474 ActiveTool::ActiveTool(BondModifier modifier) noexcept {
475 this->tool = std::make_unique<BondModifier>(std::move(modifier));
476 }
477
478 ActiveTool::ActiveTool(DeleteTool deltool) noexcept {
479 this->tool = std::make_unique<DeleteTool>(std::move(deltool));
480 }
481
482 ActiveTool::ActiveTool(ChargeModifier chargemod) noexcept {
483 this->tool = std::make_unique<ChargeModifier>(std::move(chargemod));
484 }
485
486 ActiveTool::ActiveTool(TransformTool mov) noexcept {
487 mov.set_transform_manager(&this->transform_manager);
488 this->tool = std::make_unique<TransformTool>(std::move(mov));
489 }
490
491 ActiveTool::ActiveTool(StructureInsertion insertion) noexcept {
492 this->tool = std::make_unique<StructureInsertion>(std::move(insertion));
493 }
494
495 ActiveTool::ActiveTool(GeometryModifier modifier) noexcept {
496 this->tool = std::make_unique<GeometryModifier>(std::move(modifier));
497 }
498
499 ActiveTool::ActiveTool(FormatTool fmt) noexcept {
500 this->tool = std::make_unique<FormatTool>(std::move(fmt));
501 }
502
503 ActiveTool::ActiveTool(FlipTool flip) noexcept {
504 this->tool = std::make_unique<FlipTool>(std::move(flip));
505 }
506
507 ActiveTool::ActiveTool(RemoveHydrogensTool rh) noexcept {
508 this->tool = std::make_unique<RemoveHydrogensTool>(std::move(rh));
509 }
510
511 void ActiveTool::set_core_widget_data(impl::CootLigandEditorCanvasPriv* owning_widget) noexcept {
512 this->widget_data = static_cast<impl::WidgetCoreData*>(owning_widget);
513 }
514
515 bool ElementInsertion::on_molecule_click(MoleculeClickContext& ctx) {
516 ctx.widget_data.begin_edition();
517 return true;
518 }
519
520 void ElementInsertion::on_bond_click(MoleculeClickContext& ctx, CanvasMolecule::Bond& bond) {
521 unsigned int atomic_number = this->get_atomic_number();
522 // auto el_name = RDKit::PeriodicTable::getTable()->getElementSymbol(atomic_number);
523 auto* new_atom = new RDKit::Atom(atomic_number);
524 ctx.rdkit_mol->removeBond(bond.first_atom_idx, bond.second_atom_idx);
525 unsigned int new_atom_idx = ctx.rdkit_mol->addAtom(new_atom, true, true);
526 ctx.rdkit_mol->addBond(bond.first_atom_idx, new_atom_idx, RDKit::Bond::SINGLE);
527 ctx.rdkit_mol->addBond(new_atom_idx, bond.second_atom_idx, RDKit::Bond::SINGLE);
528 ctx.widget_data.update_status("Atom has been inserted.");
529 }
530
531 void ElementInsertion::on_atom_click(MoleculeClickContext& ctx, CanvasMolecule::Atom& atom) {
532 unsigned int atomic_number = this->get_atomic_number();
533 auto el_name = RDKit::PeriodicTable::getTable()->getElementSymbol(atomic_number);
534 g_debug("Appending element '%u' (%s) to destination atom: idx=%i, symbol=%s.",atomic_number,el_name.c_str(),atom.idx,atom.symbol.c_str());
535 auto* new_atom = new RDKit::Atom(std::string(el_name));
536 ctx.rdkit_mol->replaceAtom(atom.idx, new_atom);
537 ctx.widget_data.update_status("Atom has been replaced.");
538 }
539
540 void ElementInsertion::after_molecule_click(MoleculeClickContext& ctx) {
541 ctx.canvas_mol.lower_from_rdkit(!ctx.widget_data.allow_invalid_molecules);
542 ctx.widget_data.finalize_edition();
543 }
544
545 std::string ElementInsertion::get_exception_message_prefix() const noexcept {
546 return "Could not insert atom: ";
547 }
548
549 bool BondModifier::on_molecule_click(MoleculeClickContext& ctx) {
550 ctx.widget_data.begin_edition();
551 return true;
552 }
553
554 void BondModifier::on_bond_click(MoleculeClickContext& ctx, CanvasMolecule::Bond& bond) {
555 auto* rdkit_bond = ctx.rdkit_mol->getBondBetweenAtoms(bond.first_atom_idx,bond.second_atom_idx);
556 RDKit::MolOps::Kekulize(*ctx.rdkit_mol.get());
557 auto old_type = rdkit_bond->getBondType();
558 rdkit_bond->setBondType(CanvasMolecule::bond_type_to_rdkit(this->get_target_bond_type()));
559 try {
560 this->sanitize_molecule(ctx.widget_data, *ctx.rdkit_mol.get());
561 }catch(std::exception& e) {
562 // rollback
563 g_warning("Rolling back invalid molecule change that makes it unable to sanitize with the following error: %s",e.what());
564 rdkit_bond->setBondType(old_type);
565 this->sanitize_molecule(ctx.widget_data, *ctx.rdkit_mol.get());
566 // rethrow
567 throw std::runtime_error(std::string("Invalid bond modification: ") + e.what());
568 }
569 ctx.widget_data.update_status("Bond has been altered.");
570 ctx.canvas_mol.lower_from_rdkit(!ctx.widget_data.allow_invalid_molecules);
571 ctx.widget_data.finalize_edition();
572 }
573
574 void BondModifier::on_atom_click(MoleculeClickContext& ctx, CanvasMolecule::Atom& atom) {
575 this->begin_creating_bond(ctx.mol_idx, atom.idx);
576 }
577
578 std::string BondModifier::get_exception_message_prefix() const noexcept {
579 return "Could not alter/create bond: ";
580 }
581
582 bool ActiveTool::is_creating_bond() const noexcept {
583 const BondModifier* mod = dynamic_cast<const BondModifier*>(this->tool.get());
584 if (mod) {
585 return mod->is_creating_bond();
586 }
587 return false;
588 }
589
590 void BondModifier::on_release(ClickContext& ctx, int x, int y) {
591 if(!this->is_creating_bond()) {
592 return;
593 }
594 impl::WidgetCoreData& widget_data = ctx.widget_data;
595
596 auto click_result = widget_data.resolve_click(x, y);
597 auto [original_molecule_idx, first_atom_idx] = this->get_molecule_idx_and_first_atom_of_new_bond().value();
598 this->finish_creating_bond();
599 widget_data.currently_created_bond = std::nullopt;
600
601 if(click_result.has_value()) {
602 try{
603 auto [bond_or_atom,molecule_idx] = *click_result;
604 if(std::holds_alternative<CanvasMolecule::Atom>(bond_or_atom)) {
605 auto second_atom = std::get<CanvasMolecule::Atom>(std::move(bond_or_atom));
606 if(original_molecule_idx != molecule_idx) {
607 widget_data.update_status("Cannot create bond between different molecules!");
608 widget_data.rollback_current_edition();
609 return;
610 }
611 auto& rdkit_mol = *widget_data.rdkit_molecules->at(molecule_idx);
612 RDKit::MolOps::Kekulize(*rdkit_mol.get());
613 if(first_atom_idx == second_atom.idx) {
614 auto* new_atom = new RDKit::Atom(6);
615 auto new_atom_idx = rdkit_mol->addAtom(new_atom,false,true);
616 rdkit_mol->addBond(new_atom_idx,second_atom.idx,CanvasMolecule::bond_type_to_rdkit(this->get_target_bond_type()));
617 g_info("New atom added: idx=%i",new_atom_idx);
618 widget_data.update_status("New carbon atom added.");
619 } else {
620 rdkit_mol->addBond(first_atom_idx,second_atom.idx,CanvasMolecule::bond_type_to_rdkit(this->get_target_bond_type()));
621 widget_data.update_status("Created new bond between atoms.");
622 }
623 this->sanitize_molecule(widget_data, *rdkit_mol.get());
624 auto& canvas_mol = *widget_data.molecules->at(molecule_idx);
625 canvas_mol.lower_from_rdkit(!widget_data.allow_invalid_molecules);
626 widget_data.finalize_edition();
627 } else {
628 widget_data.update_status("Can't link bond to a bond!");
629 widget_data.rollback_current_edition();
630 }
631 } catch(std::exception& e) {
632 g_warning("An error occured: %s",e.what());
633 std::string msg = std::string("Could not alter/create bond: ") + e.what();
634 widget_data.update_status(msg.c_str());
635 widget_data.rollback_current_edition();
636 }
637 } else {
638 std::string msg = "The new bond goes nowhere.";
639 widget_data.update_status(msg.c_str());
640 widget_data.rollback_current_edition();
641 }
642 }
643
644 void GeometryModifier::on_bond_click(MoleculeClickContext& ctx, CanvasMolecule::Bond& bond) {
645 ctx.widget_data.begin_edition();
646 auto* rdkit_bond = ctx.rdkit_mol->getBondBetweenAtoms(bond.first_atom_idx,bond.second_atom_idx);
647
648 auto bond_geometry = CanvasMolecule::bond_geometry_from_rdkit(rdkit_bond->getBondDir());
649 auto new_bond_geometry = CanvasMolecule::cycle_bond_geometry(bond_geometry);
650 g_debug("Target bond geometry: %u",static_cast<unsigned int>(new_bond_geometry));
651 rdkit_bond->setBondDir(CanvasMolecule::bond_geometry_to_rdkit(new_bond_geometry));
652
653 ctx.widget_data.update_status("Geometry of bond has been altered.");
654 ctx.canvas_mol.lower_from_rdkit(!ctx.widget_data.allow_invalid_molecules);
655 g_debug("Final bond geometry: %u",static_cast<unsigned int>(CanvasMolecule::bond_geometry_from_rdkit(rdkit_bond->getBondDir())));
656 ctx.widget_data.finalize_edition();
657 }
658
659 std::string GeometryModifier::get_exception_message_prefix() const noexcept {
660 return "Could not alter bond geometry: ";
661 }
662
663 void ChargeModifier::on_atom_right_click(MoleculeClickContext& ctx, CanvasMolecule::Atom& atom) {
664 ctx.widget_data.begin_edition();
665 // Do we need this here?
666 RDKit::MolOps::Kekulize(*ctx.rdkit_mol.get());
667 auto* rdkit_atom = ctx.rdkit_mol->getAtomWithIdx(atom.idx);
668 int old_charge = rdkit_atom->getFormalCharge();
669
670 rdkit_atom->setFormalCharge(old_charge + 1);
671
672 ctx.widget_data.update_status("Charge of atom has been increased.");
673
674 Tool::sanitize_molecule(ctx.widget_data, *ctx.rdkit_mol.get());
675 ctx.canvas_mol.lower_from_rdkit(!ctx.widget_data.allow_invalid_molecules);
676
677 ctx.widget_data.finalize_edition();
678 }
679
680 void ChargeModifier::on_atom_click(MoleculeClickContext& ctx, CanvasMolecule::Atom& atom) {
681 ctx.widget_data.begin_edition();
682 // Do we need this here?
683 RDKit::MolOps::Kekulize(*ctx.rdkit_mol.get());
684 auto* rdkit_atom = ctx.rdkit_mol->getAtomWithIdx(atom.idx);
685 int old_charge = rdkit_atom->getFormalCharge();
686
687 // const RDKit::PeriodicTable *table = RDKit::PeriodicTable::getTable();
688 // auto valence_list = table->getValenceList(rdkit_atom->getAtomicNum());
689 // auto valence_list_to_string = [&](){
690 // std::string valence_list_string = "[";
691 // auto vl_it = valence_list.begin();
692 // while(vl_it != valence_list.end()) {
693 // valence_list_string += std::to_string(*vl_it);
694 // vl_it++;
695 // if(vl_it != valence_list.end()) {
696 // valence_list_string += ", ";
697 // }
698 // }
699 // valence_list_string += "]";
700 // return valence_list_string;
701 // };
702
703 // auto valence_list_string = valence_list_to_string();
704 // g_debug(
705 // "Valence list from RDKit: %s Num of outer shell electrons: %i",
706 // valence_list_string.c_str(),
707 // table->getNouterElecs(rdkit_atom->getAtomicNum())
708 // );
709
710 // g_warning("todo: Fix-up computing plausible charges for atoms in the charge tool.");
711 // // We won't have to clear the list when it'll have the right contents (something to be fixed)
712 // valence_list.clear();
713 // // valence_list.push_back(0);
714 // for(int i = -4; i != 5; i++) {
715 // valence_list.push_back(i);
716 // }
717
718 // auto it = std::find(valence_list.begin(),valence_list.end(),old_charge);
719 // if(it != valence_list.end()) {
720 // it++;
721 // }
722 // if(it == valence_list.end()) {
723 // it = valence_list.begin();
724 // }
725
726 // int new_charge = *it;
727
728 // valence_list_string = valence_list_to_string();
729 // g_info("Old formal charge: %i New formal charge: %i List: %s",old_charge,new_charge,valence_list_string.c_str());
730 // rdkit_atom->setFormalCharge(new_charge);
731
732 rdkit_atom->setFormalCharge(old_charge - 1);
733
734 ctx.widget_data.update_status("Charge of atom has been decreased.");
735
736 Tool::sanitize_molecule(ctx.widget_data, *ctx.rdkit_mol.get());
737 ctx.canvas_mol.lower_from_rdkit(!ctx.widget_data.allow_invalid_molecules);
738
739 ctx.widget_data.finalize_edition();
740 }
741
742 std::string ChargeModifier::get_exception_message_prefix() const noexcept {
743 return "Could not alter charge: ";
744 }
745
746 DeleteTool::ListOfAtomsOrBonds DeleteTool::trace_chain_impl(const RDKit::ROMol* mol, std::set<unsigned int>& processed_atoms, RDKit::Atom const* rdatom) {
747 DeleteTool::ListOfAtomsOrBonds ret;
748 ret.push_back(rdatom->getIdx());
749 processed_atoms.emplace(rdatom->getIdx());
750 for(const auto& i: boost::make_iterator_range(mol->getAtomNeighbors(rdatom))) {
751 ret.push_back(std::make_tuple(rdatom->getIdx(), (unsigned int) i));
752 if(processed_atoms.find(i) != processed_atoms.end()) {
753 continue;
754 }
755 processed_atoms.emplace(i);
756 // First, push the bond between this atom and the neighbor atom
757 auto list = trace_chain_impl(mol, processed_atoms, mol->getAtomWithIdx(i));
758 // Append list to ret
759 ret.insert(ret.end(), list.begin(), list.end());
760 }
761 return ret;
762 }
763
764 bool DeleteTool::chain_contains_majority_of_atoms(const ListOfAtomsOrBonds& chain, const RDKit::ROMol* mol) {
765 unsigned int no_atoms = std::count_if(chain.cbegin(), chain.cend(), [](const AtomOrBond& el){
766 return std::holds_alternative<unsigned int>(el);
767 });
768 return no_atoms >= mol->getNumAtoms() / 2;
769 }
770
771 DeleteTool::ListOfAtomsOrBonds DeleteTool::trace_rchain(const MoleculeClickContext& ctx, const CanvasMolecule::Atom& atom) {
772 RDKit::Atom const* rdatom = ctx.rdkit_mol->getAtomWithIdx(atom.idx);
773 const RDKit::ROMol* mol = ctx.rdkit_mol.get();
774
775 std::set<unsigned int> processed_atoms;
776 DeleteTool::ListOfAtomsOrBonds ret;
777 ret.push_back(rdatom->getIdx());
778 processed_atoms.emplace(rdatom->getIdx());
779 unsigned int neighbors_count = 0;
780 // Is there no better idea?
781 for(const auto& _i: boost::make_iterator_range(mol->getAtomNeighbors(rdatom))) {
782 neighbors_count += 1;
783 }
784 // Skip tracing in-ring atoms
785 if(neighbors_count <= 1 || (neighbors_count == 2 && RDKit::queryIsAtomInRing(rdatom))) {
786 return ret;
787 }
788
789 std::vector<DeleteTool::ListOfAtomsOrBonds> branches;
790 for(const auto& i: boost::make_iterator_range(mol->getAtomNeighbors(rdatom))) {
791 if(processed_atoms.find(i) != processed_atoms.end()) {
792 continue;
793 }
794 DeleteTool::ListOfAtomsOrBonds list;
795 // First, push the bond between this atom and the branch atom
796 list.push_back(std::make_tuple(rdatom->getIdx(), (unsigned int) i));
797 auto list2 = trace_chain_impl(mol, processed_atoms, mol->getAtomWithIdx(i));
798 // Append list2 to list
799 list.insert(list.end(), list2.begin(), list2.end());
800 branches.push_back(list);
801 processed_atoms.emplace(i);
802 }
803 // Iterator to the shortest branch
804 auto it = std::min_element(branches.begin(), branches.end(), [](const std::vector<DeleteTool::AtomOrBond>& a, const std::vector<DeleteTool::AtomOrBond>& b){
805 return a.size() < b.size();
806 });
807 if(it != branches.end()) {
808 if(!chain_contains_majority_of_atoms(*it, mol)) {
809 // Append the smallest branch to our result
810 ret.insert(ret.end(), it->begin(), it->end());
811 }
812 }
813 return ret;
814 }
815
816 DeleteTool::ListOfAtomsOrBonds DeleteTool::trace_rchain(const MoleculeClickContext& ctx, const CanvasMolecule::Bond& bond) {
817 const RDKit::ROMol* mol = ctx.rdkit_mol.get();
818
819 DeleteTool::ListOfAtomsOrBonds ret;
820 ret.push_back(std::make_tuple(bond.first_atom_idx, bond.second_atom_idx));
821
822 // Skip in-ring bonds
823 if(RDKit::queryIsBondInRing(mol->getBondBetweenAtoms(bond.first_atom_idx, bond.second_atom_idx))) {
824 return ret;
825 }
826
827 std::set<unsigned int> processed_atoms1;
828 processed_atoms1.insert(bond.first_atom_idx);
829 processed_atoms1.insert(bond.second_atom_idx);
830 std::set<unsigned int> processed_atoms2 = processed_atoms1;
831
832 auto case1 = trace_chain_impl(mol, processed_atoms1, mol->getAtomWithIdx(bond.first_atom_idx));
833 auto case2 = trace_chain_impl(mol, processed_atoms2, mol->getAtomWithIdx(bond.second_atom_idx));
834
835 if(case1.size() <= case2.size() && ! chain_contains_majority_of_atoms(case1, mol)) {
836 ret.insert(ret.end(), case1.begin(), case1.end());
837 } else if(! chain_contains_majority_of_atoms(case2, mol)) {
838 ret.insert(ret.end(), case2.begin(), case2.end());
839 }
840
841 return ret;
842 }
843
844 bool DeleteTool::on_hover(ClickContext& ctx, int x, int y) {
845 return true;
846 }
847
848 bool DeleteTool::on_molecule_hover(MoleculeClickContext& ctx) {
849 if(ctx.control_pressed && !ctx.alt_pressed) {
850 // Highlight whole molecule for deletion
851 for(unsigned int i = 0; i < ctx.rdkit_mol->getNumAtoms(); i++) {
852 ctx.canvas_mol.add_atom_highlight(i, CanvasMolecule::HighlightType::Hover);
853 }
854 ctx.canvas_mol.add_highlight_to_all_bonds(CanvasMolecule::HighlightType::Hover);
855 return false;
856 }
857 return true;
858 }
859
860 void DeleteTool::on_bond_hover(MoleculeClickContext& ctx, CanvasMolecule::Bond& bond) {
861 if(ctx.control_pressed && ctx.alt_pressed) {
862 // No need to do anything for single-atom mode
863 return;
864 }
865 auto rchain = trace_rchain(ctx, bond);
866 this->highlight_rchain(ctx, rchain);
867 }
868
869 void DeleteTool::on_atom_hover(MoleculeClickContext& ctx, CanvasMolecule::Atom& atom) {
870 if(ctx.control_pressed && ctx.alt_pressed) {
871 // No need to do anything for single-atom mode
872 return;
873 }
874 auto rchain = trace_rchain(ctx, atom);
875 this->highlight_rchain(ctx, rchain);
876 }
877
878 bool DeleteTool::on_molecule_click(MoleculeClickContext& ctx) {
879 if(ctx.control_pressed) {
880 // Single-atom deletion mode
881 if(ctx.alt_pressed) {
882 // Cannot do it here
883 // widget_data.begin_edition();
884 RDKit::MolOps::Kekulize(*ctx.rdkit_mol.get());
885 return true;
886 }
887 // Whole molecule deletion mode
888 ctx.widget_data.delete_molecule_with_idx(ctx.mol_idx);
889 return false;
890 } else {
891 // Regular R-chain deletion mode
892 return true;
893 }
894 }
895
896 void DeleteTool::remove_rchain(const MoleculeClickContext& ctx, const ListOfAtomsOrBonds& chain) {
897 // First, remove bonds
898 for(const auto& i: chain) {
899 if(std::holds_alternative<std::tuple<unsigned int, unsigned int>>(i)) { // bond
900 auto [idx_a, idx_b] = std::get<std::tuple<unsigned int, unsigned int>>(i);
901 //g_debug("RCHAIN ITEM: BOND %u->%u", idx_a, idx_b);
902 ctx.rdkit_mol->removeBond(idx_a, idx_b);
903 }
904 }
905 // Then atoms
906 std::vector<unsigned int> atoms;
907 for(const auto& i: chain) {
908 if(std::holds_alternative<unsigned int>(i)) { // atom
909 unsigned int atom_idx = std::get<unsigned int>(i);
910 atoms.push_back(atom_idx);
911 }
912 }
913 std::sort(atoms.begin(), atoms.end(), [](unsigned int a, unsigned int b){
914 return a >= b;
915 });
916
917 for(const auto& atom_idx: atoms) {
918 //g_debug("RCHAIN ITEM: ATOM %u", atom_idx);
919 ctx.rdkit_mol->removeAtom(atom_idx);
920 ctx.canvas_mol.update_cached_atom_coordinate_map_after_atom_removal(atom_idx);
921 }
922 }
923
924 void DeleteTool::highlight_rchain(const MoleculeClickContext& ctx, const ListOfAtomsOrBonds& chain) {
925 for(const auto& i: chain) {
926 if(std::holds_alternative<unsigned int>(i)) { // atom
927 unsigned int atom_idx = std::get<unsigned int>(i);
928 ctx.canvas_mol.add_atom_highlight(atom_idx, CanvasMolecule::HighlightType::Hover);
929 } else { // bond
930 auto [idx_a, idx_b] = std::get<std::tuple<unsigned int, unsigned int>>(i);
931 ctx.canvas_mol.add_bond_highlight(idx_a, idx_b, CanvasMolecule::HighlightType::Hover);
932 }
933 }
934 }
935
936 void DeleteTool::on_bond_click(MoleculeClickContext& ctx, CanvasMolecule::Bond& bond) {
937 ctx.widget_data.begin_edition();
938 if(ctx.control_pressed && ctx.alt_pressed) { // Single-atom mode
939 ctx.rdkit_mol->removeBond(bond.first_atom_idx, bond.second_atom_idx);
940 ctx.widget_data.update_status("Bond has been deleted.");
941 } else { // R-chain mode
942 auto rchain = trace_rchain(ctx, bond);
943 this->remove_rchain(ctx, rchain);
944 }
945 }
946
947 void DeleteTool::on_atom_click(MoleculeClickContext& ctx, CanvasMolecule::Atom& atom) {
948 if(ctx.rdkit_mol->getNumAtoms() <= 1) {
949 // For 1-atom molecules, we switch to the whole-moleculue deletion mode.
950 // This is triggered by not beginning edition
951 // Look at after_molecule_click for reference
952 return;
953 }
954 ctx.widget_data.begin_edition();
955 if(ctx.control_pressed && ctx.alt_pressed) { // Single-atom mode
956 ctx.rdkit_mol->removeAtom(atom.idx);
957 ctx.canvas_mol.update_cached_atom_coordinate_map_after_atom_removal(atom.idx);
958 ctx.widget_data.update_status("Atom has been deleted.");
959 } else { // R-chain mode
960 auto rchain = trace_rchain(ctx, atom);
961 this->remove_rchain(ctx, rchain);
962 }
963 }
964
965 void DeleteTool::after_molecule_click(MoleculeClickContext& ctx) {
966 if(ctx.widget_data.is_in_edition()) {
967 Tool::sanitize_molecule(ctx.widget_data, *ctx.rdkit_mol.get());
968 ctx.canvas_mol.lower_from_rdkit(!ctx.widget_data.allow_invalid_molecules);
969 ctx.widget_data.finalize_edition();
970 } else {
971 ctx.widget_data.delete_molecule_with_idx(ctx.mol_idx);
972 }
973 }
974
975 std::string DeleteTool::get_exception_message_prefix() const noexcept {
976 return "Could not delete atom/bond: ";
977 }
978
979
980 unsigned int StructureInsertion::append_carbon(RDKit::RWMol* rdkit_mol_ptr, unsigned int target_idx, RDKit::Bond::BondType bond_type) {
981 RDKit::Atom* new_carbon = new RDKit::Atom(6);
982 auto new_carbon_idx = rdkit_mol_ptr->addAtom(new_carbon,false,true);
983 rdkit_mol_ptr->addBond(target_idx,new_carbon_idx,bond_type);
984 return new_carbon_idx;
985 }
986
987 unsigned int StructureInsertion::append_carbon_chain(RDKit::RWMol* rdkit_mol_ptr, unsigned int chain_start_idx, std::size_t atom_count) {
988 unsigned int current_atom = chain_start_idx;
989 for(std::size_t i = 0; i < atom_count; i++) {
990 current_atom = append_carbon(rdkit_mol_ptr, current_atom);
991 }
992 return current_atom;
993 }
994
995 void StructureInsertion::append_structure_to_atom(RDKit::RWMol* rdkit_mol_ptr, unsigned int atom_idx, bool spiro) const {
996 unsigned int first_carbon;
997 if(spiro) {
998 first_carbon = atom_idx;
999 } else {
1000 first_carbon = append_carbon(rdkit_mol_ptr, atom_idx);
1001 }
1002 switch (this->get_structure()) {
1003 case Structure::CycloPropaneRing: {
1004 auto third_carbon = append_carbon_chain(rdkit_mol_ptr, first_carbon,2);
1005 rdkit_mol_ptr->addBond(first_carbon,third_carbon,RDKit::Bond::SINGLE);
1006 break;
1007 }
1008 case Structure::CycloButaneRing: {
1009 auto last_carbon = append_carbon_chain(rdkit_mol_ptr, first_carbon,3);
1010 rdkit_mol_ptr->addBond(first_carbon,last_carbon,RDKit::Bond::SINGLE);
1011 break;
1012 }
1013 case Structure::CycloPentaneRing: {
1014 auto last_carbon = append_carbon_chain(rdkit_mol_ptr, first_carbon,4);
1015 rdkit_mol_ptr->addBond(first_carbon,last_carbon,RDKit::Bond::SINGLE);
1016 break;
1017 }
1018 case Structure::CycloHexaneRing: {
1019 auto last_carbon = append_carbon_chain(rdkit_mol_ptr, first_carbon,5);
1020 rdkit_mol_ptr->addBond(first_carbon,last_carbon,RDKit::Bond::SINGLE);
1021 break;
1022 }
1023 case Structure::BenzeneRing: {
1024 auto second_carbon = append_carbon(rdkit_mol_ptr, first_carbon);
1025 auto third_carbon = append_carbon(rdkit_mol_ptr, second_carbon, RDKit::Bond::DOUBLE);
1026 auto fourth_carbon = append_carbon(rdkit_mol_ptr, third_carbon);
1027 auto fifth_carbon = append_carbon(rdkit_mol_ptr, fourth_carbon, RDKit::Bond::DOUBLE);
1028 auto sixth_carbon = append_carbon(rdkit_mol_ptr, fifth_carbon);
1029 rdkit_mol_ptr->addBond(first_carbon,sixth_carbon,RDKit::Bond::DOUBLE);
1030 break;
1031 }
1032 case Structure::CycloHeptaneRing: {
1033 auto last_carbon = append_carbon_chain(rdkit_mol_ptr, first_carbon,6);
1034 rdkit_mol_ptr->addBond(first_carbon,last_carbon,RDKit::Bond::SINGLE);
1035 break;
1036 }
1037 case Structure::CycloOctaneRing: {
1038 auto last_carbon = append_carbon_chain(rdkit_mol_ptr, first_carbon,7);
1039 rdkit_mol_ptr->addBond(first_carbon,last_carbon,RDKit::Bond::SINGLE);
1040 break;
1041 }
1042 }
1043 }
1044
1045
1046 bool StructureInsertion::on_molecule_click(MoleculeClickContext& ctx) {
1047 ctx.widget_data.begin_edition();
1048 // This causes problems with appending benzene to a benzene
1049 // RDKit::MolOps::Kekulize(*ctx.rdkit_mol.get());
1050 return true;
1051 }
1052
1053 void StructureInsertion::on_bond_click(MoleculeClickContext& ctx, CanvasMolecule::Bond& bond) {
1054 auto last_carbon = bond.second_atom_idx;
1055 auto first_carbon = bond.first_atom_idx;
1056 auto structure_kind = this->get_structure();
1057 auto& rdkit_mol = ctx.rdkit_mol;
1058 auto* rdkit_mol_ptr = rdkit_mol.get();
1059 switch (structure_kind) {
1060 case Structure::CycloPropaneRing: {
1061 auto second_carbon = append_carbon(rdkit_mol_ptr, first_carbon);
1062 rdkit_mol->addBond(second_carbon,last_carbon,RDKit::Bond::SINGLE);
1063 break;
1064 }
1065 case Structure::CycloButaneRing: {
1066 auto fourth_carbon = append_carbon_chain(rdkit_mol_ptr, first_carbon,2);
1067 rdkit_mol->addBond(last_carbon,fourth_carbon,RDKit::Bond::SINGLE);
1068 break;
1069 }
1070 case Structure::CycloPentaneRing: {
1071 auto fifth_carbon = append_carbon_chain(rdkit_mol_ptr, first_carbon,3);
1072 rdkit_mol->addBond(last_carbon,fifth_carbon,RDKit::Bond::SINGLE);
1073 break;
1074 }
1075 case Structure::CycloHexaneRing: {
1076 auto sixth_carbon = append_carbon_chain(rdkit_mol_ptr, first_carbon,4);
1077 rdkit_mol->addBond(last_carbon,sixth_carbon,RDKit::Bond::SINGLE);
1078 break;
1079 }
1080 case Structure::BenzeneRing: {
1081 auto second_carbon = append_carbon(rdkit_mol_ptr, first_carbon,RDKit::Bond::DOUBLE);
1082 auto third_carbon = append_carbon(rdkit_mol_ptr, second_carbon);
1083 auto fourth_carbon = append_carbon(rdkit_mol_ptr, third_carbon,RDKit::Bond::DOUBLE);
1084 auto fifth_carbon = append_carbon(rdkit_mol_ptr, fourth_carbon);
1085 rdkit_mol->addBond(last_carbon,fifth_carbon,RDKit::Bond::DOUBLE);
1086 break;
1087 }
1088 case Structure::CycloHeptaneRing: {
1089 auto seventh_carbon = append_carbon_chain(rdkit_mol_ptr, first_carbon,5);
1090 rdkit_mol->addBond(last_carbon,seventh_carbon,RDKit::Bond::SINGLE);
1091 break;
1092 }
1093 case Structure::CycloOctaneRing: {
1094 auto eigth_carbon = append_carbon_chain(rdkit_mol_ptr, first_carbon,6);
1095 rdkit_mol->addBond(last_carbon,eigth_carbon,RDKit::Bond::SINGLE);
1096 break;
1097 }
1098 }
1099 ctx.widget_data.update_status("Carbon ring has been added, adjacent to the bond.");
1100 }
1101
1102 void StructureInsertion::on_atom_click(MoleculeClickContext& ctx, CanvasMolecule::Atom& atom) {
1103 bool spiro = ctx.control_pressed;
1104 this->append_structure_to_atom(ctx.rdkit_mol.get(),atom.idx, spiro);
1105 ctx.widget_data.update_status("Carbon ring has been appended to the atom.");
1106 }
1107
1108 void StructureInsertion::after_molecule_click(MoleculeClickContext& ctx) {
1109 this->sanitize_molecule(ctx.widget_data, *ctx.rdkit_mol);
1110 ctx.canvas_mol.lower_from_rdkit(!ctx.widget_data.allow_invalid_molecules);
1111 ctx.widget_data.finalize_edition();
1112 }
1113
1114 std::string StructureInsertion::get_exception_message_prefix() const noexcept {
1115 return "Could not insert structure: ";
1116 }
1117
1118 void StructureInsertion::on_blank_space_click(ClickContext& ctx, int x, int y) {
1119 g_debug("The click could not be resolved to any atom or bond.");
1120 if(ctx.widget_data.get_molecule_count_impl() == 0) {
1121 g_debug("There are no molecules. Structure insertion will therefore create a new one.");
1122 auto rdkit_mol = std::make_shared<RDKit::RWMol>();
1123 rdkit_mol->addAtom(new RDKit::Atom(6),false,true);
1124 append_structure_to_atom(rdkit_mol.get(),0, false);
1125 rdkit_mol->removeAtom((unsigned int) 0);
1126 // This function calls "begin_edition" and "finalize_edition",
1127 // so we can't call "begin_edition" here above.
1128 RDKit::MolOps::sanitizeMol(*rdkit_mol);
1129
1130 #ifndef __EMSCRIPTEN__
1131 auto* widget_ptr = static_cast<impl::CootLigandEditorCanvasPriv*>(&ctx.widget_data);
1132 coot_ligand_editor_canvas_append_molecule(COOT_COOT_LIGAND_EDITOR_CANVAS(widget_ptr), rdkit_mol);
1133 #else // __EMSCRIPTEN__ defined
1134 // Lhasa-specific includes/definitions
1135 auto* widget_ptr = static_cast<::CootLigandEditorCanvas*>(&ctx.widget_data);
1136 coot_ligand_editor_canvas_append_molecule(widget_ptr, rdkit_mol);
1137 #endif
1138
1139 ctx.widget_data.update_status("New molecule created from carbon ring.");
1140 // todo: make sure that this is crash-safe vs edit/undo
1141 }
1142 }
1143
1144 bool RemoveHydrogensTool::on_molecule_click(MoleculeClickContext& ctx) {
1145 ctx.widget_data.begin_edition();
1146 layla::remove_non_polar_hydrogens(*ctx.rdkit_mol);
1147 this->sanitize_molecule(ctx.widget_data, *ctx.rdkit_mol);
1148 ctx.canvas_mol.lower_from_rdkit(!ctx.widget_data.allow_invalid_molecules);
1149 ctx.widget_data.finalize_edition();
1150 ctx.widget_data.update_status("Non-polar hydrogens have been removed.");
1151 return false;
1152 }
1153
1154 void RemoveHydrogensTool::on_load(impl::WidgetCoreData& widget_data) {
1155 if(widget_data.get_molecule_count_impl() == 1) {
1156 auto idx_of_first = widget_data.get_first_molecule_idx();
1157 auto& canvas_mol = *widget_data.molecules->at(idx_of_first);
1158 auto& rdkit_mol = *widget_data.rdkit_molecules->at(idx_of_first);
1159 ClickContext ctx(widget_data);
1160 ctx.control_pressed = false;
1161 MoleculeClickContext mctx(ctx, 0, rdkit_mol, canvas_mol);
1162 this->on_molecule_click(mctx);
1163 }
1164 }
1165
1166 std::string RemoveHydrogensTool::get_exception_message_prefix() const noexcept {
1167 return "Could not remove hydrogens from molecule: ";
1168 }
1169
1170 void FlipTool::on_load(impl::WidgetCoreData& widget_data) {
1171 if(widget_data.get_molecule_count_impl() == 1) {
1172 auto idx_of_first = widget_data.get_first_molecule_idx();
1173 auto& canvas_mol = *widget_data.molecules->at(idx_of_first);
1174 auto& rdkit_mol = *widget_data.rdkit_molecules->at(idx_of_first);
1175 ClickContext ctx(widget_data);
1176 ctx.control_pressed = false;
1177 MoleculeClickContext mctx(ctx, 0, rdkit_mol, canvas_mol);
1178 this->on_molecule_click(mctx);
1179 }
1180 }
1181
1182 bool FlipTool::on_molecule_click(MoleculeClickContext& ctx) {
1183 ctx.widget_data.begin_edition();
1184 ctx.canvas_mol.perform_flip(this->mode);
1185 ctx.canvas_mol.lower_from_rdkit(!ctx.widget_data.allow_invalid_molecules);
1186 ctx.widget_data.finalize_edition();
1187 ctx.widget_data.update_status("Molecule has been flipped.");
1188 return false;
1189 }
1190
1191 std::string FlipTool::get_exception_message_prefix() const noexcept {
1192 return "Could not flip molecule: ";
1193 }
1194
1195 void FormatTool::on_load(impl::WidgetCoreData& widget_data) {
1196 if(widget_data.get_molecule_count_impl() == 1) {
1197 auto idx_of_first = widget_data.get_first_molecule_idx();
1198 auto& canvas_mol = *widget_data.molecules->at(idx_of_first);
1199 auto& rdkit_mol = *widget_data.rdkit_molecules->at(idx_of_first);
1200 ClickContext ctx(widget_data);
1201 ctx.control_pressed = false;
1202 MoleculeClickContext mctx(ctx, 0, rdkit_mol, canvas_mol);
1203 this->on_molecule_click(mctx);
1204 }
1205 }
1206
1207 bool FormatTool::on_molecule_click(MoleculeClickContext& ctx) {
1208 ctx.widget_data.begin_edition();
1209 ctx.canvas_mol.clear_cached_atom_coordinate_map();
1210 ctx.canvas_mol.lower_from_rdkit(!ctx.widget_data.allow_invalid_molecules, false);
1211 ctx.widget_data.finalize_edition();
1212 ctx.widget_data.update_status("Molecule has been formatted.");
1213 return false;
1214 }
1215
1216 std::string FormatTool::get_exception_message_prefix() const noexcept {
1217 return "Could not format molecule: ";
1218 }
1219
1220 void ActiveTool::begin_transform(int x, int y, TransformManager::Mode mode) {
1221 auto mol_opt = this->widget_data->resolve_click(x, y);
1222 if(mol_opt.has_value()) {
1223 auto [atom_or_bond,mol_id] = mol_opt.value();
1224 transform_manager.begin_transform(x, y, mode);
1225 transform_manager.set_canvas_molecule_index(mol_id);
1226 this->widget_data->begin_edition();
1227 }
1228 }
1229
1230 bool ActiveTool::is_in_transform() const noexcept {
1231 return this->transform_manager.is_active();
1232 }
1233
1234 void ActiveTool::update_transform_cursor_pos(int x, int y, bool snap_to_angle) noexcept {
1235 if(!transform_manager.is_active()) {
1236 return;
1237 }
1238 transform_manager.update_current_cursor_pos(x, y, snap_to_angle);
1239 transform_manager.apply_current_transform_state(this->widget_data, snap_to_angle, false);
1240 }
1241
1242 void ActiveTool::end_transform(bool snap_to_angle) {
1243 if(!transform_manager.is_active()) {
1244 return;
1245 }
1246 transform_manager.apply_current_transform_state(this->widget_data, snap_to_angle, true);
1247 transform_manager.end_transform();
1248 this->widget_data->finalize_edition();
1249 }
1250
1251 void Tool::sanitize_molecule(impl::WidgetCoreData& widget_data, RDKit::RWMol& mol) {
1252 if (!widget_data.allow_invalid_molecules) {
1253 RDKit::MolOps::sanitizeMol(mol);
1254 }
1255 }
1256
1257 std::optional<std::pair<unsigned int,unsigned int>> ActiveTool::get_molecule_idx_and_first_atom_of_new_bond() const noexcept {
1258 const BondModifier* mod = dynamic_cast<const BondModifier*>(this->tool.get());
1259 if(mod) {
1260 return mod->get_molecule_idx_and_first_atom_of_new_bond();
1261 } else {
1262 return std::nullopt;
1263 }
1264 }
1265
1266 ElementInsertion::ElementInsertion(ElementInsertion::Element el) noexcept {
1267 this->element = el;
1268 }
1269
1270 ElementInsertion::ElementInsertion(const char* symbol) {
1271 RDKit::PeriodicTable* t = RDKit::PeriodicTable::getTable();
1272 unsigned int atomic_number = t->getAtomicNumber(symbol);
1273 this->element = atomic_number;
1274 }
1275
1276 unsigned int ElementInsertion::get_atomic_number() const noexcept {
1277 if(std::holds_alternative<Element>(this->element)) {
1278 switch (std::get<Element>(this->element)) {
1279 default:
1280 case ElementInsertion::Element::C:{
1281 return 6;
1282 }
1283 case ElementInsertion::Element::N:{
1284 return 7;
1285 }
1286 case ElementInsertion::Element::O:{
1287 return 8;
1288 }
1289 case ElementInsertion::Element::S:{
1290 return 16;
1291 }
1292 case ElementInsertion::Element::P:{
1293 return 15;
1294 }
1295 case ElementInsertion::Element::H:{
1296 return 1;
1297 }
1298 case ElementInsertion::Element::F:{
1299 return 9;
1300 }
1301 case ElementInsertion::Element::Cl:{
1302 return 17;
1303 }
1304 case ElementInsertion::Element::Br:{
1305 return 35;
1306 }
1307 case ElementInsertion::Element::I:{
1308 return 53;
1309 }
1310 }
1311 } else { // raw atomic number
1312 return std::get<unsigned int>(this->element);
1313 }
1314 }
1315
1316 FlipTool::FlipTool(FlipMode mode) noexcept {
1317 this->mode = mode;
1318 }