-
Notifications
You must be signed in to change notification settings - Fork 0
/
mol_gui.py
executable file
·1517 lines (1431 loc) · 58.1 KB
/
mol_gui.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 25 07:27:35 2022
@author: nicemicro
"""
import tkinter as tk
import sys
from getopt import gnu_getopt
from tkinter import ttk
from tkinter import font as tkfont
from tkinter import filedialog as fd
from math import sqrt, cos, sin, pi, atan2, tan
from enum import IntEnum, auto
from typing import Optional, Sequence, Union, Any, Literal
import mol_eng as eng
import mol_opt as opt
MINDIST = 20
DEFLEN = 30
COS30 = DEFLEN * 3 ** (1 / 2) / 2
XSHIFT = [
0,
0,
DEFLEN,
-DEFLEN,
DEFLEN / 2,
DEFLEN / 2,
-DEFLEN / 2,
-DEFLEN / 2,
COS30,
-COS30,
COS30,
-COS30,
]
YSHIFT = [
DEFLEN,
-DEFLEN,
0,
0,
COS30,
-COS30,
COS30,
-COS30,
DEFLEN / 2,
DEFLEN / 2,
-DEFLEN / 2,
-DEFLEN / 2,
]
class TopToolbar(ttk.Frame):
"""The top toolbar of the window: contains controls for the
program, and stores editor information"""
class Modes(IntEnum):
"""The selectable operations."""
SELECT = auto()
ADD_ATOM = auto()
ADD_BOND = auto()
class EmptyValence(IntEnum):
"""Types of drawing atoms with empty valence shells"""
NOTHING = auto()
HYDROGENS = auto()
ELECTRONS = auto()
empty_val_names: dict[int, str]
def get_is_select(self) -> bool:
return self._mode == self.Modes.SELECT
def get_is_add(self) -> bool:
return self._mode == self.Modes.ADD_ATOM
def get_is_connect(self) -> bool:
return self._mode == self.Modes.ADD_BOND
def get_atom_symbol(self) -> str:
return self._symbol
def get_bond_order(self) -> int:
return self._bond[0]
def get_bond_dativity(self) -> int:
return self._bond[1]
def get_empty_val_style(self) -> int:
index: int = list(self.empty_val_names.values()).index(self._emptyvalence.get())
return list(self.empty_val_names.keys())[index]
def get_hide_carbon(self) -> bool:
return self._hide_carbon.get() == 1
def toss(self, new_value: Any) -> None:
"""Prohibits changing attributes."""
raise AttributeError("This value can not be modified directly.")
is_select = property(get_is_select, toss)
is_add = property(get_is_add, toss)
is_connect = property(get_is_connect, toss)
atom_symbol = property(get_atom_symbol, toss)
bond_order = property(get_bond_order, toss)
bond_dativity = property(get_bond_dativity, toss)
empty_val_style = property(get_empty_val_style, toss)
hide_carbon = property(get_hide_carbon, toss)
def __init__(self, parent: ttk.Frame, controller: tk.Tk) -> None:
ttk.Frame.__init__(self, parent)
#s = ttk.Style()
#s.configure("test.TFrame", background="red")
selected = ttk.Style()
selected.configure(
"active.TButton",
foreground="blue",
background="white",
font="helvetica 9 bold"
)
self.controller: tk.Tk = controller
self._mode: int = self.Modes.ADD_ATOM
self._symbol: str = "C"
self._bond: list[int] = [1, 0]
self.status_text = tk.StringVar()
self.custom_atom_symbol = tk.StringVar()
atom_symbols: list[list[str]] = [
["H", "C", "N", "O", "F", ""],
["", "", "P", "S", "Cl"],
["", "", "", "", "I", "Xe"],
]
self.empty_val_names = {
self.EmptyValence.NOTHING: "Nothing",
self.EmptyValence.HYDROGENS: "Hydrogens",
self.EmptyValence.ELECTRONS: "Electrons",
}
mode_row = ttk.Frame(self, padding="0 0 0 5")
mode_row.grid(row=0, column=0, columnspan=1, sticky="nsew")
mol_style = ttk.Frame(self, padding="10 0 0 5")
mol_style.grid(row=0, column=1, columnspan=2, sticky="nse")
symbol_sel = ttk.Frame(self, padding="0 0 0 5")
symbol_sel.grid(row=1, column=0, columnspan=1, sticky="nsw")
bond_sel = ttk.Frame(self, padding="10 0 0 5")
bond_sel.grid(row=1, column=1, rowspan=2, sticky="nsw")
ttk.Label(self, textvariable=self.status_text).grid(
row=1, column=2, rowspan=1, sticky="nesw"
)
custom_add = ttk.Frame(self, padding="0 0 0 5")
custom_add.grid(row=2, column=0, columnspan=1, sticky="nsew")
self.buttons: dict[str, ttk.Button] = {}
self.buttons["add atom"] = ttk.Button(
mode_row,
text="Add atom",
command=lambda: self.set_mode(self.Modes.ADD_ATOM),
)
self.buttons["add atom"].grid(row=0, column=0, columnspan=1)
self.buttons["connect atoms"] = ttk.Button(
mode_row,
text="Connect atoms",
command=lambda: self.set_mode(self.Modes.ADD_BOND),
)
self.buttons["connect atoms"].grid(row=0, column=1, columnspan=1)
self.buttons["select"] = ttk.Button(
mode_row, text="Select", command=lambda: self.set_mode(self.Modes.SELECT)
)
self.buttons["select"].grid(row=0, column=2, columnspan=1)
self._hide_carbon = tk.IntVar()
self._hide_carbon.set(0)
ttk.Label(mol_style, text="Hide C atom symbols").grid(row=0, column=0)
ttk.Checkbutton(
mol_style,
variable=self._hide_carbon,
offvalue=0,
onvalue=1,
command=self.draw_mode_change,
).grid(row=0, column=1)
self._emptyvalence = tk.StringVar()
self._emptyvalence.set(self.empty_val_names[self.EmptyValence.NOTHING])
ttk.Label(mol_style, text="Atoms with not full valence shells:").grid(
row=0, column=2
)
ttk.OptionMenu(
mol_style,
self._emptyvalence,
self.empty_val_names[self.EmptyValence.NOTHING],
*self.empty_val_names.values(),
command=self.draw_mode_change,
).grid(row=0, column=3)
for row, elements in enumerate(atom_symbols):
for index, symbol in enumerate(elements):
if symbol == "":
continue
self.buttons[f"atom {symbol}"] = ttk.Button(
symbol_sel,
text=symbol,
width=3,
command=lambda symbol=symbol: self.set_symbol(symbol),
)
self.buttons[f"atom {symbol}"].grid(row=row, column=index, columnspan=1)
ttk.Entry(custom_add, textvariable=self.custom_atom_symbol).grid(row=0, column=0, sticky="nsew")
self.buttons["atom custom"] = ttk.Button(
custom_add,
text="Set",
command=self.set_custom_symbol
)
self.buttons["atom custom"].grid(row=0, column=1, sticky="nsew")
self.buttons["bond order 1"] = ttk.Button(
bond_sel, text="--",
width=4,
command=lambda: self.set_bond([1, None]))
self.buttons["bond order 1"].grid(row=0, column=0, columnspan=1)
self.buttons["bond order 2"] = ttk.Button(
bond_sel,
text="==",
width=4,
command=lambda: self.set_bond([2, None])
)
self.buttons["bond order 2"].grid(row=0, column=1, columnspan=1)
self.buttons["bond order 3"] = ttk.Button(
bond_sel,
text="≡≡",
width=4,
command=lambda: self.set_bond([3, None]))
self.buttons["bond order 3"].grid(row=0, column=2, columnspan=1)
self.buttons["bond dative 0"] = ttk.Button(
bond_sel,
text="↮",
width=4,
command=lambda: self.set_bond([None, 0]))
self.buttons["bond dative 0"].grid(row=1, column=0, columnspan=1)
self.buttons["bond dative 1"] = ttk.Button(
bond_sel,
text="⟶",
width=4,
command=lambda: self.set_bond([None, 1]))
self.buttons["bond dative 1"].grid(row=1, column=1, columnspan=1)
self.buttons["bond dative -1"] = ttk.Button(
bond_sel,
text="⟵",
width=4,
command=lambda: self.set_bond([None, -1]))
self.buttons["bond dative -1"].grid(row=1, column=2, columnspan=1)
ttk.Button(bond_sel, text="(-)", width=4, command=self.minus_charge).grid(
row=2, column=0, columnspan=1
)
ttk.Button(bond_sel, text="(+)", width=4, command=self.plus_charge).grid(
row=2, column=1, columnspan=1
)
ttk.Button(bond_sel, text="UP", width=4, command=self.move_above).grid(
row=3, column=0, columnspan=1
)
ttk.Button(bond_sel, text="DOWN", width=4, command=self.move_below).grid(
row=3, column=1, columnspan=1
)
self.status_text_update()
def draw_mode_change(self, _nothing: Optional[Any] = None) -> None:
self.event_generate("<<RedrawAll>>", when="tail")
def status_text_update(self) -> None:
for button in self.buttons.values():
button["style"] = "TButton"
text: str = "MODE: "
if self._mode == self.Modes.ADD_ATOM:
text += "add atom\n"
self.buttons["add atom"]["style"] = "active.TButton"
if f"atom {self._symbol}" in self.buttons:
self.buttons[f"atom {self._symbol}"]["style"] = "active.TButton"
else:
self.buttons["atom custom"]["style"] = "active.TButton"
self.buttons[f"bond order {self._bond[0]}"]["style"] = "active.TButton"
self.buttons[f"bond dative {self._bond[1]}"]["style"] = "active.TButton"
elif self._mode == self.Modes.ADD_BOND:
text += "bond atoms\n"
self.buttons["connect atoms"]["style"] = "active.TButton"
elif self._mode == self.Modes.SELECT:
text += "select\n"
self.buttons["select"]["style"] = "active.TButton"
text += f"ATOM SYMBOL: {self._symbol}\n"
text += f"BOND ORDER: {self._bond[0]} "
if self._bond[1] == 0:
text += "--"
elif self._bond[1] == -1:
text += "⟵"
elif self._bond[1] == 1:
text += "⟶"
self.status_text.set(text)
def set_mode(self, new_mode: int = -1) -> None:
"""Changes the operation mode of the application."""
if new_mode == -1:
new_mode = self.Modes.SELECT
self._mode = new_mode
self.status_text_update()
self.event_generate("<<ModeButtonPress>>", when="tail")
def set_symbol(self, new_symbol: str) -> None:
"""Sets the default atom symbol for the application"""
self.event_generate("<<AtomButtonPress>>", when="tail")
self._symbol = new_symbol
self.status_text_update()
def set_custom_symbol(self) -> None:
"""Sets the default atom symbol to a custom one for the application"""
new_symbol: str = self.custom_atom_symbol.get()
if new_symbol == "":
return
self.set_symbol(new_symbol)
def set_bond(self, bondtype: list[Optional[int]]) -> None:
"""Sets the bond type: [order, dativity]"""
for index, item in enumerate(bondtype):
if item is not None:
self._bond[index] = item
self.event_generate(f"<<BondButton{index}Press>>", when="tail")
self.status_text_update()
def plus_charge(self) -> None:
self.event_generate("<<PlusChargeButtonPress>>", when="tail")
def minus_charge(self) -> None:
self.event_generate("<<MinusChargeButtonPress>>", when="tail")
def move_above(self) -> None:
self.event_generate("<<MoveAboveButtonPress>>", when="tail")
def move_below(self) -> None:
self.event_generate("<<MoveBelowButtonPress>>", when="tail")
class AppContainer(tk.Tk):
"""The main application window."""
class Modes(IntEnum):
"""UI input mdes of the canvas."""
NORMAL = auto()
ADD_LINKED_ATOM = auto()
LINK_ATOMS = auto()
def __init__(self, filename: str, *args, **kwargs) -> None:
tk.Tk.__init__(self, *args, **kwargs)
self.atoms: list[eng.Atom] = []
self.cov_bonds: list[eng.CovBond] = []
self.deloc_bonds: list[eng.Bond] = []
self.graphics: dict[int, Union[eng.Atom, eng.CovBond]] = {}
self.selected: list[int] = []
self.event_listened: bool = False
self.mode = self.Modes.NORMAL
self.filename: str = ""
self.title("Nice Molecules")
if filename != "":
loaded = eng.read_xml(filename)
self.atoms = [thing for thing in loaded if isinstance(thing, eng.Atom)]
self.cov_bonds = [thing for thing in loaded if isinstance(thing, eng.CovBond)]
self.symbol_font: tkfont.Font = tkfont.nametofont("TkDefaultFont")
self.symbol_index_font = tkfont.Font(
font=self.symbol_font.copy(), name="symbol_index_font"
)
self.symbol_index_font.configure(size=8)
self.symbol_font_sel = tkfont.Font(
font=self.symbol_font.copy(), name="symbol_font_sel"
)
self.symbol_font_sel.configure(weight="bold")
self.symbol_index_font_sel = tkfont.Font(
font=self.symbol_index_font.copy(), name="symbol_index_font_sel"
)
self.symbol_index_font_sel.configure(weight="bold")
container = ttk.Frame(self)
container.grid(row=0, column=0, sticky="nsew")
self.columnconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
filemenubar = ttk.Frame(container)
filemenubar.grid(row=0, column=0, sticky="nsew")
ttk.Button(filemenubar, text="Open", command=self.open).grid(row=0, column=0, sticky="nsw")
ttk.Button(filemenubar, text="Save", command=self.save).grid(row=0, column=1, sticky="nsw")
ttk.Button(filemenubar, text="Save as...", command=self.save_as).grid(row=0, column=2, sticky="nsw")
self.toolbar = TopToolbar(container, self)
self.toolbar.grid(row=1, column=0, sticky="nsew")
self.mol_canvas = tk.Canvas(container, width=800, height=600, bg="white")
self.mol_canvas.grid(row=2, column=0, sticky="nsew")
self.mol_canvas.bind("<Button-1>", self.leftclick_canvas)
self.bind("<Delete>", self.delkey_pressed)
self.bind("<F5>", self.optimize_2D)
self.bind("<<RedrawAll>>", lambda x: self.redraw_all())
self.bind("<<ModeButtonPress>>", self.button_pressed_mode)
self.bind("<<AtomButtonPress>>", self.button_pressed_atom)
self.bind("<<BondButton0Press>>", self.button_pressed_order)
self.bind("<<BondButton1Press>>", self.button_pressed_dativity)
self.bind("<<PlusChargeButtonPress>>", lambda x: self.button_pressed_charge(1))
self.bind("<<MinusChargeButtonPress>>", lambda x: self.button_pressed_charge(-1))
self.bind("<<MoveAboveButtonPress>>", lambda x: self.button_pressed_zaxis(1))
self.bind("<<MoveBelowButtonPress>>", lambda x: self.button_pressed_zaxis(-1))
if len(self.atoms) > 0:
self.redraw_all()
def save(self) -> None:
if self.filename == "":
self.save_as()
return
to_save: list[Union[eng.Bond, eng.Atom]] = []
to_save += self.atoms
to_save += self.cov_bonds
eng.to_xml(to_save, self.filename)
print(f"save {self.filename}")
def save_as(self) -> None:
new_file: str = fd.asksaveasfilename(
title = "Save as",
defaultextension = ".nm.xml",
filetypes = (
("Nice Molecules XML", "*.nm.xml"),
)
)
if not isinstance(new_file, str):
return
if new_file == "":
return
print(f"save as {new_file}")
to_save: list[Union[eng.Bond, eng.Atom]] = []
to_save += self.atoms
to_save += self.cov_bonds
eng.to_xml(to_save, new_file)
self.filename = new_file
self.title(self.filename + " - Nice Molecules")
def open(self) -> None:
new_file: str = fd.askopenfilename(
title = "Open a file",
filetypes = (
("Nice Molecules XML", "*.nm.xml"),
("XML", "*.xml"),
("All files", "*.*")
)
)
if not isinstance(new_file, str):
return
print(f"open {new_file}")
loaded: list[Union[eng.Atom, eng.Bond]]
loaded = eng.read_xml(new_file)
self.atoms = [thing for thing in loaded if isinstance(thing, eng.Atom)]
self.cov_bonds = [thing for thing in loaded if isinstance(thing, eng.CovBond)]
self.redraw_all()
self.filename = new_file
self.title(self.filename + " - Nice Molecules")
def button_pressed_mode(self, _event: tk.Event) -> None:
if not self.toolbar.is_select:
self.select_nothing()
def button_pressed_atom(self, _event: tk.Event) -> None:
"""Handles the pressing of the atom symbol buttons in the toolbar:
- in normal mode, if atoms are selected, those are changed to
the symbol what has been selected on the toolbar."""
if self.mode == self.Modes.NORMAL:
changes: bool = False
change_to: Optional[eng.el.Element]
change_to = eng.element_by_symbol(self.toolbar.atom_symbol)
if change_to is None:
change_to = eng.el.CustomElement(self.toolbar.atom_symbol)
for sel_num in self.selected:
if sel_num not in self.graphics:
continue
sel_item = self.graphics[sel_num]
if isinstance(sel_item, eng.Atom):
err: eng.BondingError = sel_item.can_change_element(change_to)
if err == eng.BondingError.OK:
sel_item.change_element(change_to)
changes = True
if changes:
self.selected = []
self.redraw_all()
def button_pressed_order(self, _event: tk.Event) -> None:
"""Handles the pressing of the bond symbol buttons in the toolbar:
- in normal mode, if bonds are selected, the order of those bonds
is changed with regard to the toolbar setting."""
if self.mode == self.Modes.NORMAL:
changes: bool = False
new_order = self.toolbar.bond_order
for sel_num in self.selected:
if sel_num not in self.graphics:
continue
sel_item = self.graphics[sel_num]
if isinstance(sel_item, eng.CovBond):
err: eng.BondingError = sel_item.can_change_order(new_order)
if err == eng.BondingError.OK:
sel_item.order = new_order
changes = True
if changes:
self.selected = []
self.redraw_all()
def button_pressed_dativity(self, _event: tk.Event) -> None:
"""Handles the pressing of the bond symbol buttons in the toolbar:
- in normal mode, if bonds are selected, the dativity of those
bonds is changed with regard to the toolbar setting."""
if self.mode == self.Modes.NORMAL:
changes: bool = False
new_dativity = self.toolbar.bond_dativity
for sel_num in self.selected:
if sel_num not in self.graphics:
continue
sel_item = self.graphics[sel_num]
if isinstance(sel_item, eng.CovBond):
err: eng.BondingError = sel_item.can_change_dativity(new_dativity)
if err == eng.BondingError.OK:
sel_item.dativity = new_dativity
changes = True
if changes:
self.selected = []
self.redraw_all()
def delkey_pressed(self, _event: tk.Event) -> None:
"""Handles the event of the delete key being pressed:
- in normal mode, if there are elements selected, the selected
bonds removed, or atoms and bonds of atoms removed."""
if self.mode == self.Modes.NORMAL and self.selected:
for sel_num in self.selected:
if sel_num not in self.graphics:
continue
sel_item = self.graphics[sel_num]
if isinstance(sel_item, eng.Atom):
removed_bonds = sel_item.unbond_all()
self.graphics = {
key: obj
for key, obj in self.graphics.items()
if obj != sel_item
}
self.atoms.remove(sel_item)
for removed_bond in removed_bonds:
self.graphics = {
key: obj
for key, obj in self.graphics.items()
if obj != removed_bond
}
if isinstance(removed_bond, eng.CovBond):
self.cov_bonds.remove(removed_bond)
else:
self.deloc_bonds.remove(removed_bond)
elif isinstance(sel_item, eng.CovBond):
sel_item.delete()
self.graphics = {
key: obj
for key, obj in self.graphics.items()
if obj != sel_item
}
self.cov_bonds.remove(sel_item)
self.selected = []
self.redraw_all()
def button_pressed_charge(self, charge_change: int) -> None:
"""The charge change button has been pressed."""
if self.mode == self.Modes.NORMAL:
changes: list[int] = []
change_to: int = 0
for sel_num in self.selected:
if sel_num not in self.graphics:
continue
sel_item = self.graphics[sel_num]
if isinstance(sel_item, eng.Atom):
if self.atoms.index(sel_item) in changes:
continue
change_to = sel_item.charge + charge_change
err: eng.BondingError = sel_item.can_ionize(change_to)
if err == eng.BondingError.OK:
sel_item.charge = change_to
changes.append(self.atoms.index(sel_item))
self.redraw_all()
def button_pressed_zaxis(self, change_z: int) -> None:
"""The Z coordinate of the selected atom is moved."""
if self.mode == self.Modes.NORMAL:
changes: list[int] = []
for sel_num in self.selected:
if sel_num not in self.graphics:
continue
sel_item = self.graphics[sel_num]
if isinstance(sel_item, eng.Atom):
if self.atoms.index(sel_item) in changes:
continue
sel_item.coord_z += change_z
changes.append(self.atoms.index(sel_item))
self.redraw_all()
def optimize_2D(self, _event: tk.Event) -> None:
"""Optimize the structural formula based on simple rules."""
if len(self.selected) == 0:
return
for sel_num in self.selected:
if sel_num not in self.graphics:
continue
sel_item = self.graphics[sel_num]
if isinstance(sel_item, eng.Atom):
opt.optimize_2D(sel_item, target_len=DEFLEN)
self.redraw_all()
def leftclick_canvas(self, event: tk.Event) -> None:
"""Handes left click on the canvas:
- if the operation is adding an atom, adds a new atom at the
position of mouse click"""
if self.event_listened:
self.event_listened = False
return
if self.toolbar.is_select:
self.select_nothing()
return
if self.toolbar.is_add:
closestitems: tuple[int, ...] = self.mol_canvas.find_overlapping(
event.x - MINDIST / 2,
event.y - MINDIST / 2,
event.x + MINDIST / 2,
event.y + MINDIST / 2,
)
if len(closestitems) == 0:
item = None
else:
item = closestitems[0]
if item in self.graphics and isinstance(self.graphics[item], eng.Atom):
item_obj = self.graphics[item]
assert isinstance(item_obj, eng.Atom)
if (
-MINDIST < item_obj.coord_x - event.x < MINDIST
and -MINDIST < item_obj.coord_y - event.y < MINDIST
):
return
coords = (event.x, event.y)
self.add_atom(self.toolbar.atom_symbol, coords)
def leftdown_atom(self, atom_id: int, _event: tk.Event) -> None:
"""Handles the event of mouse button press on atom, based on the
operation:
- if selection, current atom is selected,
- if add atom, enters mode to add linked atom,
- if connect atoms, enters mode to connect existing atoms."""
sel_atom = self.atoms[atom_id]
if self.toolbar.is_select:
self.select_nothing()
self.selected = list(self.mol_canvas.find_withtag(f"atom-{atom_id}"))
self.selected += list(self.mol_canvas.find_withtag(f"atom_text-{atom_id}"))
self.mol_canvas.itemconfigure(f"atom-{atom_id}", fill="green")
self.mol_canvas.itemconfigure(f"atom_text-{atom_id}", fill="green")
self.mol_canvas.itemconfigure(
f"atom_rad-{atom_id}", outline="green", width=3
)
self.mol_canvas.itemconfigure(f"atom_lpair-{atom_id}", width=2)
for sel_element in self.selected:
if "atom_text" in self.mol_canvas.gettags(sel_element):
self.change_font_weight(sel_element, "bold")
self.event_listened = True
return
if self.toolbar.is_add:
self.event_listened = True
test_atom = eng.add_atom_by_symbol(self.toolbar.atom_symbol, (0, 0))
if test_atom is None:
test_atom = eng.UnrestrictedAtom(self.toolbar.atom_symbol, (0, 0))
assert test_atom is not None, "Test atom could not be created."
if (
sel_atom.can_bond(
test_atom, self.toolbar.bond_order, self.toolbar.bond_dativity
)
!= eng.BondingError.OK
):
return
self.possible_atoms(sel_atom)
self.mode = self.Modes.ADD_LINKED_ATOM
return
if self.toolbar.is_connect:
self.event_listened = True
self.possible_links(sel_atom)
self.mode = self.Modes.LINK_ATOMS
def mouseup_atom(self, atom_id: int, event: tk.Event) -> None:
"""Handles the events when the mouse is lifted after draging an atom:
- adding linked atom: adds new atom and new bond,
- linking atoms: adds new bond."""
if self.mode == self.Modes.ADD_LINKED_ATOM:
closestitems = self.mol_canvas.find_closest(event.x, event.y)
self.mol_canvas.itemconfigure("ui_help", fill="grey")
item, tags = self.close_selection(closestitems)
if item is None or tags is None or tags[0] != "ui_help":
self.set_normal_mode()
return
atomplace = "atom_here-" + tags[1].split("-")[-1]
new_x = int(self.mol_canvas.coords(atomplace)[0])
new_y = int(self.mol_canvas.coords(atomplace)[1])
atom_connect = self.atoms[atom_id]
new_atom = self.add_atom(self.toolbar.atom_symbol, (new_x, new_y))
new_bond = atom_connect.bond(
new_atom,
order=self.toolbar.bond_order,
dative=self.toolbar.bond_dativity,
)
self.cov_bonds.append(new_bond)
self.redraw_all()
self.set_normal_mode()
if self.mode == self.Modes.LINK_ATOMS:
closestitems = self.mol_canvas.find_closest(event.x, event.y)
self.mol_canvas.itemconfigure("ui_help", fill="#aaaaaa")
self.mol_canvas.itemconfigure("atom", fill="black")
self.mol_canvas.itemconfigure("empty", fill="")
item, tags = self.close_selection(closestitems)
if item is None or tags is None:
self.set_normal_mode()
return
selected_atom = -1
if len(tags) >= 2 and tags[0] == "ui_help":
selected_atom = int(tags[1].split("-")[-1])
if len(tags) >= 1 and tags[0] == "atom":
selected_atom = item
if selected_atom == -1:
self.set_normal_mode()
return
atom_from = self.atoms[atom_id]
atom_to = self.graphics[selected_atom]
assert isinstance(atom_to, eng.Atom), "Trying to bobd to a non-atom"
if (
atom_from.can_bond(
atom_to, self.toolbar.bond_order, self.toolbar.bond_dativity
)
!= eng.BondingError.OK
):
self.set_normal_mode()
return
new_bond = atom_from.bond(
atom_to,
order=self.toolbar.bond_order,
dative=self.toolbar.bond_dativity,
)
assert new_bond is not None, "Creating a bond failed"
self.cov_bonds.append(new_bond)
self.redraw_all()
self.set_normal_mode()
def drag_atom(self, atom_id: int, event: tk.Event) -> None:
"""Handling the dragging of an atom that was clicked on:
- adding linked atom / linking atoms: highlights the
placeholder where new atom / bond will be created."""
if self.mode in (self.Modes.ADD_LINKED_ATOM, self.Modes.LINK_ATOMS):
closestitems = self.mol_canvas.find_closest(event.x, event.y)
self.mol_canvas.itemconfigure("ui_help", fill="#aaaaaa")
self.mol_canvas.itemconfigure("atom", fill="black")
self.mol_canvas.itemconfigure("empty", fill="")
item, tags = self.close_selection(closestitems)
if item is None or tags is None:
return
if self.mode == self.Modes.ADD_LINKED_ATOM:
if len(tags) < 2 or tags[0] != "ui_help":
return
self.mol_canvas.itemconfigure(tags[1], fill="blue")
elif self.mode == self.Modes.LINK_ATOMS:
selected_atom = -1
if len(tags) >= 2 and tags[0] == "ui_help":
selected_atom = int(tags[1].split("-")[-1])
if len(tags) >= 1 and tags[0] == "atom":
selected_atom = item
if selected_atom == -1:
return
atom_from = self.atoms[atom_id]
atom_to = self.graphics[selected_atom]
assert isinstance(atom_to, eng.Atom)
if (
atom_from.can_bond(
atom_to, self.toolbar.bond_order, self.toolbar.bond_dativity
)
!= eng.BondingError.OK
):
return
self.mol_canvas.itemconfigure(f"ui_help-{selected_atom}", fill="blue")
self.mol_canvas.itemconfigure(selected_atom, fill="blue")
def click_bond(self, bond_id: int, _event: tk.Event) -> None:
"""Handling the event of a bond being clicked on:
- if operation is selection, selects the bond, and all lines
that constitute the bond."""
if self.toolbar.is_select:
self.select_nothing()
self.selected = list(self.mol_canvas.find_withtag(f"bond-{bond_id}"))
self.mol_canvas.itemconfigure(f"bond-{bond_id}", fill="green", width=2)
self.event_listened = True
return
def change_font_weight(
self, item_num: int, new_weight: Literal["bold", "normal"]
) -> None:
assert "atom_text" in self.mol_canvas.gettags(
item_num
), "Only text items have fonts."
if "index" in self.mol_canvas.gettags(item_num):
if new_weight == "bold":
self.mol_canvas.itemconfigure(item_num, font=self.symbol_index_font_sel)
return
self.mol_canvas.itemconfigure(item_num, font=self.symbol_index_font)
return
if new_weight == "bold":
self.mol_canvas.itemconfigure(item_num, font=self.symbol_font_sel)
return
self.mol_canvas.itemconfigure(item_num, font=self.symbol_font)
return
def select_nothing(self) -> None:
"""Clears the selection and changes the previously selected objects
back to their default look."""
for sel_num in self.selected:
tags: Sequence[str] = self.mol_canvas.gettags(sel_num)
if "empty" in tags:
self.mol_canvas.itemconfigure(sel_num, fill="")
else:
self.mol_canvas.itemconfigure(sel_num, fill="black")
if "atom_text" in tags:
self.change_font_weight(sel_num, "normal")
if "bond" in tags:
sel_item = self.graphics[sel_num]
assert isinstance(sel_item, eng.CovBond)
atom1: eng.Atom = sel_item.atoms[0]
atom2: eng.Atom = sel_item.atoms[1]
if atom1.coord_z > 0 and atom2.coord_z == atom1.coord_z:
self.mol_canvas.itemconfigure(sel_num, width=3)
else:
self.mol_canvas.itemconfigure(sel_num, width=1)
if "atom_rad" in tags:
self.mol_canvas.itemconfigure(sel_num, outline="black", width=1)
if "atom_lpair" in tags:
self.mol_canvas.itemconfigure(sel_num, width=1)
self.selected = []
def close_selection(
self, closestitems: tuple[int, ...]
) -> tuple[Optional[int], Optional[Sequence[str]]]:
"""Finds the closest item on the canvas to the
listed item on the canvas."""
if len(closestitems) == 0:
self.set_normal_mode()
return None, None
item: int = closestitems[0]
tags: Sequence[str] = self.mol_canvas.gettags(item)
if (len(tags) < 2 or tags[0] != "ui_help") and (
len(tags) < 1 or tags[0] != "atom"
):
return None, None
return item, tags
def set_normal_mode(self) -> None:
"""Returns the application to normal mode."""
self.mol_canvas.delete("ui_help")
self.mode = self.Modes.NORMAL
def possible_links(self, atom_from: eng.Atom) -> None:
"""Draws possible links between atoms to create in
atom connecting mode."""
for atom_link_num in self.graphics:
atom_to = self.graphics[atom_link_num]
if not isinstance(atom_to, eng.Atom):
continue
if (
atom_from.can_bond(
atom_to, self.toolbar.bond_order, self.toolbar.bond_dativity
)
!= eng.BondingError.OK
):
continue
self.draw_bond_atoms(
atom_from,
atom_to,
-1,
self.toolbar.bond_order,
self.toolbar.bond_dativity,
color="#aaaaaa",
tags=("ui_help", f"ui_help-{atom_link_num}"),
)
def possible_atoms(self, atom: eng.Atom) -> None:
"""Draws possible atoms that could be created and joined
to the current atom in linked atom drawing mode."""
num = 1
for (deltax, deltay) in zip(XSHIFT, YSHIFT):
(x1, y1, x2, y2) = (
atom.coord_x + deltax - MINDIST / 2,
atom.coord_y + deltay - MINDIST / 2,
atom.coord_x + deltax + MINDIST / 2,
atom.coord_y + deltay + MINDIST / 2,
)
over = self.mol_canvas.find_overlapping(x1, y1, x2, y2)
over_atom = False
for obj in over:
tags: Sequence[str] = self.mol_canvas.gettags(obj)
if len(tags) > 0 and (
"atom" in tags or "bond" in tags or "atom_text" in tags
):
over_atom = True
break
if over_atom:
num += 1
continue
self.mol_canvas.create_text(
atom.coord_x + deltax,
atom.coord_y + deltay,
text=self.toolbar.atom_symbol,
font=self.symbol_font,
justify="center",
fill="#aaaaaa",
tags=("ui_help", f"ui_help-{num}", f"atom_here-{num}"),
)
obscure: tuple[str, str]
if self.hide_atom(atom):
obscure = ("", f"atom_here-{num}")
else:
obscure = (f"atom_text-{self.atoms.index(atom)}", f"atom_here-{num}")
self.draw_bond_lines(
(
atom.coord_x,
atom.coord_y,
atom.coord_x + deltax,
atom.coord_y + deltay,
),
30,
self.toolbar.bond_order,
self.toolbar.bond_dativity,
obscure_area=obscure,
color="#aaaaaa",
tags=("ui_help", f"ui_help-{num}"),
)
num += 1
def add_atom(self, atom_symbol: str, coords: tuple[float, float]) -> eng.Atom:
"""Adds an atom to the canvas with given symbol at
given coordinates."""
new_atom = eng.add_atom_by_symbol(atom_symbol, coords)
if new_atom is None:
new_atom = eng.UnrestrictedAtom(atom_symbol, coords)
assert new_atom is not None, "Unsuccessful at creating a new atom."
self.atoms.append(new_atom)
self.redraw_all()
return new_atom
def draw_bond_atoms(
self,
atom1: eng.Atom,
atom2: eng.Atom,
bondlen: float = -1,
order: float = -1,
dativity: float = 0,
color: str = "black",
tags: Optional[tuple[str, ...]] = None,
) -> list[int]:
"""Draws the bond between two atom instances."""
x1, y1, x2, y2 = atom1.coord_x, atom1.coord_y, atom2.coord_x, atom2.coord_y
line_thickness: int = 1
line_dash: Optional[tuple[int, int]] = None
if bondlen == -1:
bondlen = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
angle: float = atan2(
atom2.coord_y - atom1.coord_y, atom2.coord_x - atom1.coord_x
)
reverse_second_bond: bool = False
if order == 2:
left1, right1 = eng.angle_side_calc(
eng.angles_rel_angle(atom1.bond_angles, angle), 0.01
)
left2, right2 = eng.angle_side_calc(
eng.angles_rel_angle(atom2.bond_angles, angle), 0.01
)
reverse_second_bond = left1 + left2 > right1 + right2
atomtag1: str = ""
atomtag2: str = ""
if not self.hide_atom(atom1):
atomtag1 = f"atom_text-{self.atoms.index(atom1)}"
if not self.hide_atom(atom2):
atomtag2 = f"atom_text-{self.atoms.index(atom2)}"
if atom1.coord_z > 0 and atom1.coord_z == atom2.coord_z:
line_thickness = 3
if atom1.coord_z < 0 and atom1.coord_z == atom2.coord_z:
line_dash = (2, 1)
triangle: int = atom2.coord_z - atom1.coord_z
if order > 0 and dativity != 0:
triangle = 0
bond_objects = self.draw_bond_lines(
(x1, y1, x2, y2),
bondlen,
order,
dativity,
obscure_area=(atomtag1, atomtag2),
reverse_second_bond=reverse_second_bond,
color=color,
triangle=triangle,