File: patchcanvas.py

package info (click to toggle)
raysession 0.17.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 19,168 kB
  • sloc: python: 44,371; sh: 1,538; makefile: 208; xml: 86
file content (1395 lines) | stat: -rw-r--r-- 43,461 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# PatchBay Canvas engine using QGraphicsView/Scene
# Copyright (C) 2010-2019 Filipe Coelho <falktx@falktx.com>
# Copyright (C) 2019-2024 Mathieu Picot <picotmathieu@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# For a full copy of the GNU General Public License see the doc/GPL.txt file.

import logging
from pathlib import Path
import time
from typing import Callable

from qtpy.QtCore import (
    Slot, Signal, QObject, QPointF, QRectF,#type:ignore
    QSettings, QTimer)

from patshared import (
    PortMode,
    BoxLayoutMode,
    BoxType,
    GroupPos
    )

from .init_values import (
    AliasingReason,
    CanvasNeverInit,
    GridStyle,
    PortSubType,
    PortType,
    Joining,
    canvas,
    options,
    features,
    CanvasOptionsObject,
    CanvasFeaturesObject,
    MAX_PLUGIN_ID_ALLOWED,
    GroupObject,
    PortObject,
    PortgrpObject,
    ConnectionObject,
    BoxHidding,
    Zv
)

from .utils import (
    nearest_on_grid, 
    previous_left_on_grid,
    previous_top_on_grid)
from .box_widget import BoxWidget
from .port_widget import PortWidget
from .grouped_lines_widget import GroupedLinesWidget
from .hidden_conn_widget import HiddenConnWidget
from .theme_manager import ThemeData, ThemeManager
from .scene import PatchScene
from .scene_view import PatchGraphicsView
from .proto_callbacker import ProtoCallbacker


_logger = logging.getLogger(__name__)
_logging_str = ''
'''used by patchbay_api decorator to get function_name
and arguments, easily usable by logger'''


# decorator
def patchbay_api(func: Callable):
    '''decorator for API callable functions.
    It makes debug logs and also a global logging string
    usable directly in the functions'''

    def wrapper(*args, **kwargs):
        args_strs = [str(arg) for arg in args]
        args_strs += [f"{k}={v}" for k, v in kwargs.items()]

        global _logging_str
        _logging_str = f"{func.__name__}({', '.join(args_strs)})"
        _logger.debug(_logging_str)
        return func(*args, **kwargs)
    return wrapper


class CanvasObject(QObject):
    port_added = Signal(int, int)
    port_removed = Signal(int, int)
    connection_added = Signal(int)
    connection_removed = Signal(int)
    move_boxes_finished = Signal()

    def __init__(self, parent=None):
        QObject.__init__(self, parent)
        self._gps_to_join = set[int]()
        self.move_boxes_finished.connect(self._join_after_move)

        self.connect_update_timer = QTimer()
        self.connect_update_timer.setInterval(0)
        self.connect_update_timer.setSingleShot(True)
        self.connect_update_timer.timeout.connect(
            self._connect_update_timer_finished)
        
        self._aliasing_reason = AliasingReason.NONE
        self._aliasing_timer_started_at = 0.0
        self._aliasing_move_timer = QTimer()
        self._aliasing_move_timer.setInterval(0)
        self._aliasing_move_timer.setSingleShot(True)
        self._aliasing_move_timer.timeout.connect(
            self._aliasing_move_timer_finished)
        
        self._aliasing_view_timer = QTimer()
        self._aliasing_view_timer.setInterval(500)
        self._aliasing_view_timer.setSingleShot(True)
        self._aliasing_view_timer.timeout.connect(
            self._aliasing_view_timer_finished)

    @Slot()
    def _connect_update_timer_finished(self):
        GroupedLinesWidget.change_all_prepared_conns()

    @Slot()
    def _aliasing_move_timer_finished(self):
        if time.time() - self._aliasing_timer_started_at > 0.060:
            canvas.set_aliasing_reason(self._aliasing_reason, True)
        
        if self._aliasing_reason is AliasingReason.VIEW_MOVE:
            self._aliasing_view_timer.start()

    @Slot()
    def _aliasing_view_timer_finished(self):
        canvas.set_aliasing_reason(AliasingReason.VIEW_MOVE, False)

    def start_aliasing_check(self, aliasing_reason: AliasingReason):
        self._aliasing_reason = aliasing_reason
        self._aliasing_timer_started_at = time.time()
        self._aliasing_move_timer.start()

    @Slot()
    def _join_after_move(self):
        for group_id in self._gps_to_join:
            join_group(group_id)

        self._gps_to_join.clear()
        
        canvas.cb.animation_finished()

    def add_group_to_join(self, group_id: int):
        self._gps_to_join.add(group_id)
    
    def rm_group_to_join(self, group_id: int):
        self._gps_to_join.discard(group_id)
            
    def rm_all_groups_to_join(self):
        self._gps_to_join.clear()


@patchbay_api
def init(view: PatchGraphicsView, callbacker: ProtoCallbacker,
          theme_paths: tuple[Path, ...], fallback_theme: str):
    if canvas.initiated:
        _logger.critical("init() - already initiated")
        return

    if not callbacker:
        _logger.critical("init() - fatal error: callback not set")
        return

    canvas.initiated = True
    canvas._cb = callbacker
    canvas._scene = PatchScene(view)
    view.setScene(canvas._scene)
    
    canvas.initial_pos = QPointF(0, 0)
    canvas.size_rect = QRectF()

    if canvas._qobject is None:
        canvas._qobject = CanvasObject()

    if canvas.settings is None:
        # TODO : may remove this because it is not used
        # while features.handle_positions is False. 
        canvas.settings = QSettings()

    if canvas.theme_manager is None:
        canvas.theme_manager = ThemeManager(theme_paths)
        if not canvas.theme_manager.set_theme(options.theme_name):
            if canvas.theme_manager.set_theme(fallback_theme):
                _logger.warning(
                f"theme '{options.theme_name}' has not been found,"
                f"use '{fallback_theme}' instead.")
            else:
                _logger.warning(
                f"theme '{options.theme_name}' has not been found,"
                "use the very ugly fallback theme.")
                canvas.theme_manager.set_fallback_theme()

        canvas.theme.load_cache()

    canvas._scene.zoom_reset()    

@patchbay_api
def set_loading_items(yesno: bool, auto_redraw=False, prevent_overlap=True):
    '''while canvas is loading items (groups or ports, connections...)
    items will be added, but not redrawn.
    This is an optimization that prevents a lot of redraws.
    Think to set loading items at False and use redraw_all_groups
    or redraw_group once the long operation is finished'''
    canvas.ensure_init()
    canvas.loading_items = yesno
    
    if not yesno and auto_redraw:
        both_done = set[int]()
        boxes = list[BoxWidget]()
        
        for group_id in canvas.groups_to_redraw_out:
            group = canvas.get_group(group_id)
            if group is None:
                continue

            for box in group.widgets:
                port_mode = box.get_port_mode()
                if port_mode & PortMode.OUTPUT:
                    box.update_positions(scene_checks=False)
                    if box.isVisible():
                        boxes.append(box)
                    
                    if port_mode & PortMode.INPUT:
                        both_done.add(group_id)
        
        for group_id in canvas.groups_to_redraw_in:
            if group_id in both_done:
                continue
            
            group = canvas.get_group(group_id)
            if group is None:
                continue

            for box in group.widgets:
                port_mode = box.get_port_mode()
                if port_mode & PortMode.INPUT:
                    box.update_positions(scene_checks=False)
                    if box.isVisible():
                        boxes.append(box)
        
        if prevent_overlap:
            for box in boxes:
                canvas.scene.deplace_boxes_from_repulsers([box])
        
        if canvas.groups_to_redraw_out or canvas.groups_to_redraw_in:
            canvas.scene.resize_the_scene()
        canvas.scene.update()
    
    canvas.groups_to_redraw_out.clear()
    canvas.groups_to_redraw_in.clear()

@patchbay_api
def add_group(group_id: int, group_name: str, split: bool,
              box_type: BoxType, icon_name: str, gpos: GroupPos):
    if canvas.get_group(group_id) is not None:
        _logger.error(f"{_logging_str} - group already exists.")
        return

    group = GroupObject()
    group.group_id = group_id
    group.group_name = group_name
    group.splitted = split
    group.box_type = box_type
    group.icon_name = icon_name
    group.plugin_id = -1
    group.plugin_ui = False
    group.plugin_inline = False
    group.handle_client_gui = False
    group.gui_visible = False
    group.gpos = gpos
    group.widgets = list[BoxWidget]()

    if split:
        out_box = BoxWidget(group, PortMode.OUTPUT)
        out_box.set_top_left(nearest_on_grid(gpos.boxes[PortMode.OUTPUT].pos))
        group.widgets.append(out_box)

        in_box = BoxWidget(group, PortMode.INPUT)
        in_box.set_top_left(nearest_on_grid(gpos.boxes[PortMode.INPUT].pos))
        group.widgets.append(in_box)

    else:
        box = BoxWidget(group, PortMode.BOTH)
        box.set_top_left(nearest_on_grid(gpos.boxes[PortMode.BOTH].pos))
        group.widgets.append(box)

    canvas.add_group(group)

    if canvas.loading_items:
        canvas.groups_to_redraw_in.add(group_id)
        canvas.groups_to_redraw_out.add(group_id)
        return

    if canvas.scene is not None:
        QTimer.singleShot(0, canvas.scene.update)

@patchbay_api
def remove_group(group_id: int, save_positions=True):
    canvas.ensure_init()
    group = canvas.get_group(group_id)
    if group is None:
        _logger.error(f"{_logging_str} - unable to find group to remove")
        return
    
    for box in group.widgets:
        box.remove_icon_from_scene()
        canvas.scene.remove_box(box)
    
    canvas.remove_group(group)
    canvas.group_plugin_map.pop(group.plugin_id, None)

    if canvas.loading_items:
        canvas.groups_to_redraw_in.add(group_id)
        canvas.groups_to_redraw_out.add(group_id)
        return

    QTimer.singleShot(0, canvas.scene.update)
    QTimer.singleShot(0, canvas.scene.resize_the_scene)

@patchbay_api
def rename_group(group_id: int, new_group_name: str):
    group = canvas.get_group(group_id)
    if group is None:
        _logger.critical(f"{_logging_str} - unable to find group to rename")
        return

    group.group_name = new_group_name    
    for box in group.widgets:
        box._group_name = new_group_name
        if not canvas.loading_items:
            box.update_positions()

    if canvas.loading_items:
        canvas.groups_to_redraw_in.add(group_id)
        canvas.groups_to_redraw_out.add(group_id)
        return

    if canvas.scene is not None:
        QTimer.singleShot(0, canvas.scene.update)

@patchbay_api
def split_group(group_id: int, on_place=False, redraw=True):
    '''Split inputs and outputs in two box widgets.

    on_place: the new boxes will have a pos near from the existing one
    
    redraw: draw the box, quite long operation. Needed for 'on_place'
    to be effective.'''
    canvas.ensure_init()

    group = canvas.get_group(group_id)
    if group is None:
        _logger.error(f"{_logging_str} - unable to find group to split")
        return
    
    if group.splitted:
        _logger.error(
            f"{_logging_str} - group is already splitted")
        return

    if not group.widgets:
        _logger.error(
            f"{_logging_str} - group has no box widget to split")
        return

    box = group.widgets[0]
    wrap = box.is_wrapped()
    ex_rect = QRectF(box.sceneBoundingRect())        
    new_box = BoxWidget(group, PortMode.INPUT)
    new_box.setPos(box.pos())
    new_box.set_wrapped(wrap, animate=False)
    
    for portgroup in canvas.list_portgroups(group_id):
        if (portgroup.port_mode is PortMode.INPUT
                and portgroup.widget is not None):
            portgroup.widget.setParentItem(new_box)
            
    for port in canvas.list_ports(group_id):
        if (port.port_mode is PortMode.INPUT
                and port.widget is not None):
            port.widget.setParentItem(new_box)

    box.set_port_mode(PortMode.OUTPUT)
    group.widgets.append(new_box)
    canvas.add_box(new_box)
    group.splitted = True

    group.gpos.set_splitted(True)
    canvas.cb.group_splitted(group_id)
    
    if not redraw:
        return
    
    full_width = canvas.theme.box_spacing
    
    for box in group.widgets:
        box.update_positions(even_animated=True, scene_checks=False)
        full_width += box.boundingRect().width()
                
    if on_place:
        for box in group.widgets:
            if box.get_current_port_mode() is PortMode.OUTPUT:
                group.gpos.boxes[PortMode.OUTPUT].pos = (
                    previous_left_on_grid(
                        int(ex_rect.right() + (full_width - ex_rect.width()) / 2
                            - box.boundingRect().width())),
                    previous_top_on_grid(
                        int(ex_rect.y()))
                )
            else:
                group.gpos.boxes[PortMode.INPUT].pos = (
                    previous_left_on_grid(
                        int(ex_rect.left() - (full_width - ex_rect.width()) / 2)),
                    previous_top_on_grid(int(ex_rect.y()))
                )
        
        move_group_boxes(group_id, group.gpos)    
        canvas.scene.deplace_boxes_from_repulsers(
            [b for b in group.widgets if b.isVisible()])

    QTimer.singleShot(0, canvas.scene.update)

@patchbay_api
def join_group(group_id: int):
    canvas.ensure_init()
    group = canvas.get_group(group_id)
    if group is None:
        _logger.error(f"{_logging_str} - unable to find groups to join")
        return

    if not group.splitted:
        _logger.error(f"{_logging_str} - group is not splitted")
        return

    wrap = True
    for box in group.widgets:
        wrap = wrap and box.is_wrapped()

    eater, eaten = group.widgets

    for portgroup in canvas.list_portgroups(group_id=group_id):
        if (portgroup.port_mode is eaten.get_port_mode()
                and portgroup.widget is not None):
            portgroup.widget.setParentItem(eater)
    
    for port in canvas.list_ports(group_id=group_id):
        if (port.port_mode is eaten.get_port_mode()
                and port.widget is not None):
            port.widget.setParentItem(eater)

    eater.set_port_mode(PortMode.BOTH)
    eaten.remove_icon_from_scene()
    canvas.scene.remove_box(eaten)
    group.widgets.remove(eaten)
    canvas.remove_box(eaten)
    group.splitted = False
    del eaten

    eater.send_move_callback()
    eater.set_wrapped(wrap, animate=False)
    eater.update_positions(scene_checks=False)

    canvas.cb.group_joined(group_id)
    QTimer.singleShot(0, canvas.scene.update)

@patchbay_api
def repulse_all_boxes():
    canvas.ensure_init()
    if options.prevent_overlap:
        canvas.scene.full_repulse()      

@patchbay_api
def repulse_from_group(group_id: int, port_mode: PortMode):
    if not options.prevent_overlap:
        return

    group = canvas.get_group(group_id)
    if group is None:
        return
    
    canvas.ensure_init()
    
    for box in group.widgets:
        if (box.get_port_mode() & port_mode
                and (box.isVisible()
                     or (box in canvas.scene.move_boxes
                         and canvas.scene.move_boxes[box].hidding_state
                            is BoxHidding.RESTORING))):
            canvas.scene.deplace_boxes_from_repulsers([box])

@patchbay_api
def redraw_all_groups(force_no_prevent_overlap=False, theme_change=False):
    if canvas.loading_items:
        return

    canvas.ensure_init()
    # We are redrawing all groups.
    # For optimization reason we prevent here to resize the scene
    # at each group draw, we'll do it once all is done,
    # same for prevent_overlap.
    elastic = options.elastic
    prevent_overlap = options.prevent_overlap
    options.elastic = False
    options.prevent_overlap = False

    for box in canvas.list_boxes():
        box.update_positions(
            without_connections=True,
            scene_checks=False,
            theme_change=theme_change)

    for group_out in canvas.group_list:
        for group_in in canvas.group_list:
            GroupedLinesWidget.connections_changed(
                group_out.group_id, group_in.group_id)
        
    if elastic:
        canvas.scene.set_elastic(True)
    
    if prevent_overlap:
        options.prevent_overlap = True
        if not force_no_prevent_overlap:
            repulse_all_boxes()
    
    if not elastic or prevent_overlap:
        QTimer.singleShot(0, canvas.scene.update)

@patchbay_api
def redraw_group(group_id: int, ensure_visible=False, prevent_overlap=True):
    if canvas.loading_items:
        return
    
    group = canvas.get_group(group_id)
    if group is None:
        _logger.error(f"{_logging_str}, no group to redraw")
        return

    canvas.ensure_init()

    for box in group.widgets:
        box.update_positions(scene_checks=prevent_overlap)

    canvas.scene.update()

    if ensure_visible:
        for box in group.widgets:
            canvas.scene.center_view_on(box)
            break

@patchbay_api
def change_grid_width(grid_width: int):
    canvas.ensure_init()
    if grid_width <= 0:
        _logger.error(
            f'Can not change the grid width to a value <= 0 : {grid_width}')
        return
    
    options.cell_width = grid_width
    
    canvas.scene.update_grid_widget()
    
    for box in canvas.list_boxes():
        box.fix_pos()
        
    redraw_all_groups()

@patchbay_api
def change_grid_height(grid_height: int):
    canvas.ensure_init()
    if grid_height <= 0:
        _logger.error(
            f'Can not change the grid height to a value <= 0 : {grid_height}')
        return
    
    options.cell_height = grid_height
    
    canvas.scene.update_grid_widget()
    
    for box in canvas.list_boxes():
        box.fix_pos()
        
    redraw_all_groups()

@patchbay_api
def change_grid_widget_style(style: GridStyle):
    canvas.ensure_init()
    options.grid_style = style
    canvas.scene.update_grid_style()

@patchbay_api
def move_group_boxes(
        group_id: int, gpos: GroupPos,
        redraw=PortMode.NULL, restore=PortMode.NULL):
    '''Highly optimized function used at view change.
    Only things that need to be redrawn are redrawn.
    Any change in this function can easily create unwanted bugs ;)
    
    restore is required because the previous box_pos can be hidden
    and this one shown, but without ports
    (e.g. a pure audio group in midi view)'''
    canvas.ensure_init()
    group = canvas.get_group(group_id)
    if group is None:
        return

    group.gpos = gpos
    split = gpos.is_splitted()
    join = False
    splitted = False
    orig_rect = QRectF()

    if group.splitted != split:
        if split:
            for box in group.widgets:
                if box._port_mode is PortMode.BOTH:
                    orig_rect = QRectF(box.sceneBoundingRect())
                    break

            split_group(group_id, redraw=False)
            splitted = True
            redraw |= PortMode.BOTH
        else:
            join = True

    for port_mode, box_pos, in gpos.boxes.items():
        for box in group.widgets:
            if box.get_port_mode() is not port_mode:
                continue

            if box._layout_mode is not box_pos.layout_mode:
                box.set_layout_mode(box_pos.layout_mode)
                redraw |= port_mode

            if box.is_hidding_or_restore() and not box_pos.is_hidden():
                redraw |= port_mode

            if join:
                wanted_wrap = gpos.boxes[PortMode.BOTH].is_wrapped()
            else:
                wanted_wrap = box_pos.is_wrapped()

            if box.is_wrapped() is not wanted_wrap:
                # we need to update the box now, because the port_list
                # of the box is not re-evaluted when we update positions
                # during the wrap/unwrap animation.
                box.update_positions(
                    even_animated=True, scene_checks=False)
                box.set_wrapped(
                    wanted_wrap, prevent_overlap=False)
                redraw &= ~port_mode

            if redraw & port_mode:
                box.update_positions(
                    even_animated=True, scene_checks=False)
            
            if splitted and not orig_rect.isNull():
                # the splitted boxes start with inputs aligned to the inputs
                # of the previous joined box, and same for the outputs.
                if port_mode is PortMode.INPUT:
                    box.set_top_left((orig_rect.left(), orig_rect.top()))
                elif port_mode is PortMode.OUTPUT:
                    box.set_top_left(
                        (orig_rect.right() - box.boundingRect().width(),
                         orig_rect.top()))
            
            xy = nearest_on_grid(box_pos.pos)

            if box_pos.is_hidden():
                if box.isVisible():
                    canvas.scene.add_box_to_animation_hidding(box)
            
            elif restore & port_mode:
                if join:
                    canvas.scene.add_box_to_animation_restore(box)

                    both_pos = nearest_on_grid(gpos.boxes[PortMode.BOTH].pos)

                    if port_mode is PortMode.OUTPUT:
                        canvas.qobject.add_group_to_join(group.group_id)
                        joined_widget = BoxWidget(group, PortMode.BOTH)
                        joined_rect = joined_widget.get_dummy_rect()
                        canvas.scene.remove_box(joined_widget)
                        joined_rect.translate(QPointF(*both_pos))

                        canvas.scene.add_box_to_animation(
                            box, *both_pos,
                            joining=Joining.YES,
                            joined_rect=joined_rect)
                    else:
                        canvas.scene.add_box_to_animation(
                            box, *both_pos,
                            joining=Joining.YES)
                else:
                    box.set_top_left(xy)
                    canvas.scene.add_box_to_animation(box, *xy)
                    canvas.scene.add_box_to_animation_restore(box)

            else:
                if box.hidder_widget is not None:
                    canvas.scene.removeItem(box.hidder_widget)
                    box.hidder_widget = None

                if join:
                    both_pos = nearest_on_grid(gpos.boxes[PortMode.BOTH].pos)

                    if port_mode is PortMode.OUTPUT:
                        canvas.qobject.add_group_to_join(group.group_id)

                        joined_widget = BoxWidget(group, PortMode.BOTH)
                        joined_rect = joined_widget.get_dummy_rect()
                        canvas.scene.remove_box(joined_widget)
                        joined_rect.translate(QPointF(*both_pos))
                    
                        canvas.scene.add_box_to_animation(
                            box, *both_pos,
                            joining=Joining.YES,
                            joined_rect=joined_rect)
                    else:
                        canvas.scene.add_box_to_animation(
                            box, *both_pos,
                            joining=Joining.YES)
                else:
                    canvas.scene.add_box_to_animation(
                        box, *xy, joining=Joining.NO)

@patchbay_api
def wrap_group_box(group_id: int, port_mode: PortMode, yesno: bool):
    group = canvas.get_group(group_id)
    if group is None:
        return

    for box in group.widgets:
        if box.get_port_mode() is port_mode:
            box.set_wrapped(yesno, animate=True,
                            prevent_overlap=True)

@patchbay_api
def set_group_layout_mode(group_id: int, port_mode: PortMode,
                          layout_mode: BoxLayoutMode,
                          prevent_overlap=True):
    group = canvas.get_group(group_id)
    if group is None:
        _logger.warning(
            "set_group_layout_mode, no group with group_id {group_id}")
        return
    
    group.gpos.boxes[port_mode].layout_mode = layout_mode
    
    if canvas.loading_items:
        return

    for box in group.widgets:
        if (box.get_port_mode() is port_mode
                and box._layout_mode is not layout_mode):
            box.set_layout_mode(layout_mode)
            box.update_positions(scene_checks=prevent_overlap)

@patchbay_api
def clear_selection():
    canvas.ensure_init()
    canvas.scene.clear_selection()

# ------------------------------------------------------------------------

@patchbay_api
def set_group_icon(group_id: int, box_type: BoxType, icon_name: str):
    canvas.ensure_init()
    group = canvas.get_group(group_id)
    if group is None:
        _logger.critical(f"{_logging_str} - unable to find group to change icon")
        return
    
    group.box_type = box_type
    group.icon_name = icon_name

    for box in group.widgets:
        box.set_icon(box_type, icon_name)

    if canvas.loading_items:
        canvas.groups_to_redraw_out.add(group_id)
        canvas.groups_to_redraw_in.add(group_id)
        return

    QTimer.singleShot(0, canvas.scene.update)

@patchbay_api
def set_group_as_plugin(group_id: int, plugin_id: int,
                        has_ui: bool, has_inline_display: bool):
    group = canvas.get_group(group_id)
    if group is None:
        _logger.critical(f"{_logging_str} - unable to find group to set as plugin")
        return

    group.plugin_id = plugin_id
    group.plugin_ui = has_ui
    group.plugin_inline = has_inline_display
    
    for box in group.widgets:
        box.set_as_plugin(plugin_id, has_ui, has_inline_display)

    canvas.group_plugin_map[plugin_id] = group

# ---------------------------------------------

@patchbay_api
def add_port(group_id: int, port_id: int, port_name: str,
             port_mode: PortMode, port_type: PortType,
             port_subtype: PortSubType):
    canvas.ensure_init()
    if canvas.get_port(group_id, port_id) is not None:
        _logger.critical(f"{_logging_str} - port already exists")

    group = canvas.get_group(group_id)
    if group is None:
        _logger.critical(f"{_logging_str} - Unable to find parent group")
        return
    
    for box in group.widgets:
        if port_mode in box.get_port_mode():
            break
    else:
        _logger.error(f"{_logging_str} - Unable to find a box for port")
        return

    port = PortObject()
    port.group_id = group_id
    port.port_id = port_id
    port.port_name = port_name
    port.port_mode = port_mode
    port.port_type = port_type
    port.portgrp_id = 0
    port.port_subtype = port_subtype
    port.hidden_conn_widget = None
    port.widget = PortWidget(port, box)
    
    port.widget.setVisible(box.ports_are_visible())
    canvas.add_port(port)

    if canvas.loading_items:
        if port_mode is PortMode.INPUT:
            canvas.groups_to_redraw_in.add(group_id)
        elif port_mode is PortMode.OUTPUT:
            canvas.groups_to_redraw_out.add(group_id)
        return

    box.update_positions()

    QTimer.singleShot(0, canvas.scene.update)

@patchbay_api
def remove_port(group_id: int, port_id: int):
    canvas.ensure_init()
    port = canvas.get_port(group_id, port_id)
    if port is None:
        _logger.critical(f"{_logging_str} - Unable to find port to remove")
        return

    if port.portgrp_id:
        _logger.critical(f"{_logging_str} - Port is in portgroup " 
                            f"{port.portgrp_id}, remove it before !")
        return

    if port.hidden_conn_widget is not None:
        canvas.scene.removeItem(port.hidden_conn_widget)
        port.hidden_conn_widget = None

    item = port.widget
    box = None
    
    if item is not None:
        box = item.parentItem()
        canvas.scene.removeItem(item)

    del item
    canvas.remove_port(port)

    canvas.qobject.port_removed.emit(group_id, port_id)
    if canvas.loading_items:
        if port.port_mode is PortMode.OUTPUT:
            canvas.groups_to_redraw_out.add(group_id)
        else:
            canvas.groups_to_redraw_in.add(group_id)
        return

    if box is not None:
        box.update_positions()

    QTimer.singleShot(0, canvas.scene.update)

@patchbay_api
def rename_port(group_id: int, port_id: int, new_port_name: str):
    canvas.ensure_init()
    port = canvas.get_port(group_id, port_id)
    if port is None:
        _logger.critical(f"{_logging_str} - Unable to find port to rename")
        return

    if new_port_name != port.port_name:
        port.port_name = new_port_name
        port.widget.set_port_name(new_port_name)

    if canvas.loading_items:
        if port.port_mode is PortMode.OUTPUT:
            canvas.groups_to_redraw_out.add(group_id)
        else:
            canvas.groups_to_redraw_in.add(group_id)
        return

    port.widget.parentItem().update_positions()

    QTimer.singleShot(0, canvas.scene.update)

@patchbay_api
def port_has_hidden_connection(group_id: int, port_id: int, yesno: bool):
    port = canvas.get_port(group_id, port_id)
    if port is None:
        _logger.critical(
            f"{_logging_str} - Unable to find port to set hidden connection")
        return

    if bool(port.hidden_conn_widget is None) == bool(not yesno):
        return

    canvas.ensure_init()

    if yesno:
        port.hidden_conn_widget = HiddenConnWidget(port.widget)
        canvas.scene.addItem(port.hidden_conn_widget)

    else:
        if port.hidden_conn_widget is not None:
            canvas.scene.removeItem(port.hidden_conn_widget)
        del port.hidden_conn_widget
        port.hidden_conn_widget = None

    if canvas.loading_items:
        return

    QTimer.singleShot(0, canvas.scene.update)

@patchbay_api
def add_portgroup(group_id: int, portgrp_id: int, port_mode: PortMode,
                  port_type: PortType, port_subtype: PortSubType,
                  port_id_list: list[int]):
    if canvas.get_portgroup(group_id, portgrp_id) is not None:
        _logger.critical(f"{_logging_str} - portgroup already exists")
        return
    
    portgrp = PortgrpObject()
    portgrp.group_id = group_id
    portgrp.portgrp_id = portgrp_id
    portgrp.port_mode = port_mode
    portgrp.port_type = port_type
    portgrp.port_subtype = port_subtype
    portgrp.port_id_list = list(port_id_list)
    portgrp.widget = None

    i = 0
    # check that port ids are present and groupable in this group
    for port in canvas.list_ports(group_id=group_id):
        if (port.port_type is port_type
                and port.port_mode is port_mode):
            if port.port_id == port_id_list[i]:
                if port.portgrp_id:
                    _logger.error(
                        f"{_logging_str} - "
                        f"port id {port.port_id} is already "
                        f"in portgroup {port.portgrp_id}")
                    return

                i += 1

                if i == len(port_id_list):
                    # everything seems ok for this portgroup, stop the check
                    break

            elif i > 0:
                _logger.error(f"{_logging_str} - port ids are not consecutive")
                return
    else:
        _logger.error(f"{_logging_str} - not enought ports with port_id_list")
        return

    # modify ports impacted by portgroup
    for port in canvas.list_ports(group_id=group_id):
        if (port.port_id in port_id_list):
            port.set_portgroup_id(
                portgrp_id, port_id_list.index(port.port_id), len(port_id_list))

    canvas.add_portgroup(portgrp)
    
    # add portgroup widget and refresh the view
    group = canvas.get_group(group_id)
    if group is None:
        return
    
    for box in group.widgets:
        if box.get_port_mode() & port_mode:
            portgrp.widget = box.add_portgroup_from_group(portgrp)

            if not canvas.loading_items:
                box.update_positions()

@patchbay_api
def remove_portgroup(group_id: int, portgrp_id: int):
    canvas.ensure_init()
    box_widget = None

    for portgrp in canvas.list_portgroups(group_id=group_id):
        if portgrp.portgrp_id == portgrp_id:
            # set portgrp_id to the concerned ports
            for port in canvas.list_ports(group_id=group_id):
                if port.portgrp_id == portgrp_id:
                    port.set_portgroup_id(0, 0, 1)

            if portgrp.widget is not None:
                item = portgrp.widget
                box_widget = item.parentItem()
                canvas.scene.removeItem(item)
                del item
                portgrp.widget = None
            break
    else:
        _logger.error(f"{_logging_str} - Unable to find portgrp to remove")
        return

    canvas.remove_portgroup(portgrp)

    if canvas.loading_items:
        return

    if box_widget is not None:
        box_widget.update_positions()

    QTimer.singleShot(0, canvas.scene.update)

@patchbay_api
def clear_all():
    GroupedLinesWidget.clear_all_widgets()
    canvas.clear_all()

@patchbay_api
def connect_ports(connection_id: int, group_out_id: int, port_out_id: int,
                  group_in_id: int, port_in_id: int):
    canvas.ensure_init()
    out_port = canvas.get_port(group_out_id, port_out_id)
    in_port = canvas.get_port(group_in_id, port_in_id)
    
    if out_port is None or in_port is None:
        _logger.critical(f"{_logging_str} - unable to find ports to connect")
        return

    connection = ConnectionObject()
    connection.connection_id = connection_id
    connection.group_in_id = group_in_id
    connection.port_in_id = port_in_id
    connection.group_out_id = group_out_id
    connection.port_out_id = port_out_id
    connection.port_type = out_port.port_type
    connection.ready_to_disc = False
    connection.in_selected = False
    connection.out_selected = False
    canvas.add_connection(connection)

    GroupedLinesWidget.prepare_conn_changes(group_out_id, group_in_id)
    canvas.qobject.connect_update_timer.start()
    canvas.qobject.connection_added.emit(connection_id)
    
    if canvas.loading_items:
        return

    QTimer.singleShot(0, canvas.scene.update)

@patchbay_api
def disconnect_ports(connection_id: int):
    connection = canvas.get_connection(connection_id)
    if connection is None:
        _logger.critical(
            f"{_logging_str} - unable to find connection ports")
        return
    
    tmp_conn = connection.copy()
    canvas.remove_connection(connection)
    
    GroupedLinesWidget.prepare_conn_changes(
        tmp_conn.group_out_id, tmp_conn.group_in_id)
    
    canvas.qobject.connect_update_timer.start()
    canvas.qobject.connection_removed.emit(connection_id)

    out_port = canvas.get_port(tmp_conn.group_out_id, tmp_conn.port_out_id)
    in_port = canvas.get_port(tmp_conn.group_in_id, tmp_conn.port_in_id)
    
    if out_port is None or in_port is None:
        _logger.info(f"{_logging_str} - connection cleaned after its ports")
        return

    if out_port.widget is None or in_port.widget is None:
        _logger.error(f"{_logging_str} - port has no widget")
        return        

    if canvas.loading_items:
        return

    QTimer.singleShot(0, canvas.scene.update)

@patchbay_api
def animate_before_hide_box(group_id: int, port_mode: PortMode):
    canvas.ensure_init()
    group = canvas.get_group(group_id)
    if group is None:
        _logger.info(f"{_logging_str} - failed to find group")
        return

    for box in group.widgets:
        if port_mode & box._port_mode:
            canvas.scene.add_box_to_animation_hidding(box)
    
# ----------------------------------------------------------------------------

@patchbay_api
def start_aliasing_check(aliasing_reason: AliasingReason):
    canvas.ensure_init()
    canvas.qobject.start_aliasing_check(aliasing_reason)

@patchbay_api
def set_aliasing_reason(aliasing_reason: AliasingReason, yesno: bool):
    canvas.set_aliasing_reason(aliasing_reason, yesno)

@patchbay_api
def get_theme() -> str:
    if canvas.theme_manager is None:
        raise CanvasNeverInit
    return canvas.theme_manager.get_theme()

@patchbay_api
def list_themes() -> list[ThemeData]:
    if canvas.theme_manager is None:
        raise CanvasNeverInit
    return canvas.theme_manager.list_themes()

@patchbay_api
def change_theme(theme_name='') -> bool:
    if canvas.theme_manager is None:
        raise CanvasNeverInit
    ret = canvas.theme_manager.set_theme(theme_name)
    if ret:
        options.theme_name = theme_name
    return ret

@patchbay_api
def copy_and_load_current_theme(new_theme_name: str) -> int:
    if canvas.theme_manager is None:
        raise CanvasNeverInit
    return canvas.theme_manager.copy_and_load_current_theme(new_theme_name)

# ----------------------------------------------------------------------------
@patchbay_api
def redraw_plugin_group(plugin_id: int):
    group = canvas.group_plugin_map.get(plugin_id, None)

    if group is None:
        _logger.critical(f"{_logging_str} - unable to find group")
        return

    assert isinstance(group, GroupObject)

    for box in group.widgets:
        box.redraw_inline_display()

@patchbay_api
def handle_plugin_removed(plugin_id: int):
    group = canvas.group_plugin_map.pop(plugin_id, None)

    if group is not None:
        assert isinstance(group, GroupObject)
        group.plugin_id = -1
        group.plugin_ui = False
        group.plugin_inline = False
        
        for box in group.widgets:
            box.remove_as_plugin()

    for group in canvas.group_list:
        if (group.plugin_id < plugin_id
                or group.plugin_id > MAX_PLUGIN_ID_ALLOWED):
            continue

        group.plugin_id -= 1
        
        for box in group.widgets:
            box._plugin_id -= 1

        canvas.group_plugin_map[plugin_id] = group

@patchbay_api
def handle_all_plugins_removed():
    canvas.group_plugin_map = {}

    for group in canvas.group_list:
        if group.plugin_id < 0:
            continue
        if group.plugin_id > MAX_PLUGIN_ID_ALLOWED:
            continue

        group.plugin_id = -1
        group.plugin_ui = False
        group.plugin_inline = False
        
        for box in group.widgets:
            box.remove_as_plugin()

@patchbay_api
def set_auto_select_items(yesno: bool):
    options.auto_select_items = yesno
    
    for box in canvas.list_boxes():
        box.setAcceptHoverEvents(yesno)
    
    for portgrp in canvas.list_portgroups():
        if portgrp.widget is not None:
            portgrp.widget.setAcceptHoverEvents(yesno)
            
    for port in canvas.list_ports():
        if port.widget is not None:
            port.widget.setAcceptHoverEvents(yesno)

@patchbay_api
def set_elastic(yesno: bool):
    canvas.ensure_init()
    canvas.scene.set_elastic(yesno)

@patchbay_api
def set_prevent_overlap(yesno: bool):
    options.prevent_overlap = yesno
    if yesno:
        redraw_all_groups()

@patchbay_api
def set_borders_navigation(yesno: bool):
    options.borders_navigation = yesno

@patchbay_api
def set_max_port_width(width: int):
    options.max_port_width = width
    redraw_all_groups()

@patchbay_api
def set_default_zoom(default_zoom: int):
    options.default_zoom = default_zoom

@patchbay_api
def semi_hide_groups(group_ids: set[int]):
    for group in canvas.group_list:
        semi_hidden = group.group_id in group_ids
        for box in group.widgets:
            box.semi_hide(semi_hidden)
            box.setZValue(
                Zv.OPAC_BOX.value if semi_hidden else Zv.BOX.value)
    
    GroupedLinesWidget.groups_semi_hidden(group_ids)

@patchbay_api
def invert_boxes_selection():
    canvas.ensure_init()
    canvas.scene.invert_boxes_selection()

@patchbay_api
def select_port(group_id: int, port_id: int):
    canvas.ensure_init()
    port = canvas.get_port(group_id, port_id)
    if port is None:
        return
    
    if port.widget is None:
        return
    
    box = port.widget.parentItem()
    canvas.scene.clearSelection()

    if box.is_wrapped():
        canvas.scene.center_view_on(box)
        box.setSelected(True)
    else:
        canvas.scene.center_view_on(port.widget)
        port.widget.setSelected(True)

@patchbay_api
def select_filtered_group_box(group_id: int, n_select=1):
    canvas.ensure_init()
    group = canvas.get_group(group_id)
    if group is None:
        return
    
    n_widget = 1

    for box in group.widgets:
        if box.isVisible():
            if n_select == n_widget:
                canvas.scene.clearSelection()
                box.setSelected(True)
                canvas.scene.center_view_on(box)
                break

            n_widget += 1

@patchbay_api
def get_box_true_layout(group_id: int, port_mode: PortMode) -> BoxLayoutMode:
    '''Should never return BoxLayoutMode.AUTO'''
    group = canvas.get_group(group_id)
    if group is None:
        return BoxLayoutMode.AUTO
    
    for box in group.widgets:
        if box.get_port_mode() is port_mode:
            return box.get_current_layout_mode()
    
    return BoxLayoutMode.AUTO

@patchbay_api
def get_number_of_boxes(group_id: int) -> int:
    group = canvas.get_group(group_id)
    if group is None:
        return 0
    
    return len([b for b in group.widgets if b.isVisible()])

@patchbay_api    
def set_semi_hide_opacity(opacity: float):
    options.semi_hide_opacity = opacity

    for box in canvas.list_boxes():
        box.update_opacity()
                
    GroupedLinesWidget.update_opacity()

@patchbay_api
def set_optional_gui_state(group_id: int, visible: bool):
    canvas.ensure_init()
    group = canvas.get_group(group_id)
    if group is None:
        return

    group.handle_client_gui = True
    group.gui_visible = visible

    for widget in group.widgets:
        if widget is not None:
            widget.set_optional_gui_state(visible)
    
    if not canvas.loading_items:
        canvas.scene.update()

@patchbay_api
def zoom_reset():
    canvas.ensure_init()
    canvas.scene.zoom_reset()
    
@patchbay_api
def zoom_fit():
    canvas.ensure_init()
    canvas.scene.zoom_fit()

@patchbay_api
def save_cache():
    canvas.ensure_init()
    canvas.theme.save_cache()

@patchbay_api
def set_grouped_box_layout_ratio(value: float):
    options.box_grouped_auto_layout_ratio = max(min(2.0, value), 0.0)
    redraw_all_groups()

@patchbay_api
def set_options(new_options: CanvasOptionsObject):
    if not canvas.initiated:
        options.__dict__ = new_options.__dict__.copy()

@patchbay_api
def set_features(new_features: CanvasFeaturesObject):
    if not canvas.initiated:
        features.__dict__ = new_features.__dict__.copy()