~martijnbraam/pyatem

ref: dba5191d6959bac972829975e06a3c089595461e pyatem/gtk_switcher/switcher.py -rw-r--r-- 35.0 KiB
dba5191dMartijn Braam Implement AUX M/E 3 months ago
                                                                                
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
from gtk_switcher.layout import LayoutView
from pyatem.command import CutCommand, AutoCommand, FadeToBlackCommand, TransitionSettingsCommand, WipeSettingsCommand, \
    TransitionPositionCommand, TransitionPreviewCommand, ColorGeneratorCommand, MixSettingsCommand, DipSettingsCommand, \
    DveSettingsCommand, AudioMasterPropertiesCommand, FairlightMasterPropertiesCommand, DkeyRateCommand, \
    DkeyAutoCommand, DkeyTieCommand, \
    DkeyOnairCommand, ProgramInputCommand, PreviewInputCommand, KeyOnAirCommand, KeyFillCommand, \
    FadeToBlackConfigCommand, RecorderStatusCommand, AuxSourceCommand
from pyatem.field import TransitionSettingsField, InputPropertiesField

import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib, GObject, Gio, Gdk

gi.require_version('Handy', '1')
from gi.repository import Handy


class SwitcherPage:
    def __init__(self, builder):
        self.main_blocks = builder.get_object('main_blocks')
        self.me = []
        self.layout = {}

        self.mix_rate = builder.get_object('mix_rate')
        self.dip_rate = builder.get_object('dip_rate')
        self.wipe_rate = builder.get_object('wipe_rate')
        self.dve_rate = builder.get_object('dve_rate')
        self.ftb_rate = builder.get_object('ftb_rate')
        self.dip_source = builder.get_object('dip_source')
        self.wipe_symmetry_adj = builder.get_object('wipe_symmetry_adj')
        self.wipe_x_adj = builder.get_object('wipe_x_adj')
        self.wipe_y_adj = builder.get_object('wipe_y_adj')
        self.wipe_width_adj = builder.get_object('wipe_width_adj')
        self.wipe_softness_adj = builder.get_object('wipe_softness_adj')
        self.wipe_fill = builder.get_object('wipe_fill')
        self.wipe_reverse = builder.get_object('wipe_reverse')
        self.wipe_flipflop = builder.get_object('wipe_flipflop')

        self.ftb_afv = builder.get_object('ftb_afv')

        self.keyer_stack = builder.get_object('keyer_stack')

        self.usk_count = 0
        self.usks = {}
        self.dsks = {}
        self.has_models = []

        self.upstream_keyers = builder.get_object('upstream_keyers')
        self.downstream_keyers = builder.get_object('downstream_keyers')

        self.usk1_dve_fill = builder.get_object('usk1_dve_fill')
        self.usk1_mask_en = builder.get_object('usk1_mask_en')
        self.usk1_mask_top = builder.get_object('usk1_mask_top')
        self.usk1_mask_bottom = builder.get_object('usk1_mask_bottom')
        self.usk1_mask_left = builder.get_object('usk1_mask_left')
        self.usk1_mask_right = builder.get_object('usk1_mask_right')

        self.expander_stream_recorder = builder.get_object('expander_stream_recorder')
        self.stream_recorder_filename = builder.get_object('stream_recorder_filename')
        self.stream_recorder_disk2 = builder.get_object('stream_recorder_disk2')
        self.stream_recorder_disk1 = builder.get_object('stream_recorder_disk1')
        self.stream_recorder_disk1_label = builder.get_object('stream_recorder_disk1_label')
        self.stream_recorder_disk2_label = builder.get_object('stream_recorder_disk2_label')
        self.stream_recorder_start = builder.get_object('stream_recorder_start')
        self.stream_recorder_stop = builder.get_object('stream_recorder_stop')
        self.stream_recorder_switch = builder.get_object('stream_recorder_switch')
        self.stream_recorder_clock = builder.get_object('stream_recorder_clock')
        self.stream_recorder_status = builder.get_object('stream_recorder_status')
        self.stream_recorder_disk = [None, None]
        self.disks = {}
        self.aux = {}

        self.grid_aux = builder.get_object('grid_aux')

        self.wipe_style = [
            builder.get_object('wipestyle_h'),
            builder.get_object('wipestyle_v'),
            builder.get_object('wipestyle_mh'),
            builder.get_object('wipestyle_mv'),
            builder.get_object('wipestyle_cross'),
            builder.get_object('wipestyle_box'),
            builder.get_object('wipestyle_diamond'),
            builder.get_object('wipestyle_iris'),
            builder.get_object('wipestyle_box_tl'),
            builder.get_object('wipestyle_box_tr'),
            builder.get_object('wipestyle_box_br'),
            builder.get_object('wipestyle_box_bl'),
            builder.get_object('wipestyle_box_top'),
            builder.get_object('wipestyle_box_right'),
            builder.get_object('wipestyle_box_bottom'),
            builder.get_object('wipestyle_box_left'),
            builder.get_object('wipestyle_diag1'),
            builder.get_object('wipestyle_diag2'),
        ]

        for style, button in enumerate(self.wipe_style):
            button.pattern = style
            button.connect('pressed', self.on_wipe_pattern_clicked)

        self.color1 = builder.get_object('color1')
        self.color2 = builder.get_object('color2')

        self.model_me1_fill = builder.get_object('model_me1_fill')
        self.model_key = builder.get_object('model_key')
        self.model_aux = builder.get_object('model_aux')
        self.model_disks = builder.get_object('model_disks')
        self.model_changing = False
        self.slider_held = False

    def add_mixeffect(self):
        from gtk_switcher.mixeffect import MixEffectBlock
        index = len(self.me)
        me = MixEffectBlock(index)
        self.me.append(me)
        me.set_dsk(False)
        self.main_blocks.add(me)

        me.connect('program-changed', self.on_me_program_changed)
        me.connect('preview-changed', self.on_me_preview_changed)
        me.connect('rate-focus', self.on_rate_focus)
        me.connect('rate-unfocus', self.on_rate_unfocus)
        me.connect('ftb-clicked', self.on_ftb_clicked)
        me.connect('ftb-rate', self.on_ftb_rate_changed)
        me.connect('tbar-position-changed', self.on_tbar_position_changed)
        me.connect('auto-rate-changed', self.on_auto_rate_changed)
        me.connect('auto-clicked', self.on_auto_clicked)
        me.connect('cut-clicked', self.on_cut_clicked)
        me.connect('preview-transition-clicked', self.on_prev_trans_clicked)
        me.connect('style-changed', self.on_style_clicked)
        me.connect('onair-clicked', self.on_onair_clicked)
        me.connect('next-clicked', self.on_next_clicked)
        me.connect('dsk-tie', self.on_dsk_tie_clicked)
        me.connect('dsk-onair', self.on_dsk_onair_clicked)
        me.connect('dsk-auto', self.on_dsk_auto_clicked)
        me.connect('dsk-rate', self.on_dsk_rate_activate)

        layout = LayoutView(index, self.connection)
        self.layout[index] = layout
        layout_exp = Gtk.Expander(label="Layout editor M/E {}".format(index + 1))
        layout_exp.set_margin_start(12)
        layout_exp.set_margin_end(12)
        layout_exp.add(layout)
        layout_exp.show_all()
        self.main_blocks.add(layout_exp)

    def on_cut_clicked(self, widget, index):
        cmd = CutCommand(index=index)
        self.connection.mixer.send_commands([cmd])

    def on_cut_shortcut(self, *args):
        if self.disable_shortcuts:
            return

        cmd = CutCommand(index=0)
        self.connection.mixer.send_commands([cmd])

    def on_auto_clicked(self, widget, index, *args):
        if self.disable_shortcuts and len(args) == 2:
            return

        cmd = AutoCommand(index=index)
        self.connection.mixer.send_commands([cmd])

    def on_auto_shortcut(self, *args):
        if self.disable_shortcuts:
            return

        cmd = AutoCommand(index=0)
        self.connection.mixer.send_commands([cmd])

    def on_ftb_clicked(self, widget, index):
        cmd = FadeToBlackCommand(index=index)
        self.connection.mixer.send_commands([cmd])

    def on_ftb_rate_changed(self, widget, index, frames):
        cmd = FadeToBlackConfigCommand(index=index, frames=frames)
        self.connection.mixer.send_commands([cmd])

    def on_style_clicked(self, widget, index, style):
        s = None
        if style == 'mix':
            s = TransitionSettingsField.STYLE_MIX
        elif style == 'dip':
            s = TransitionSettingsField.STYLE_DIP
        elif style == 'wipe':
            s = TransitionSettingsField.STYLE_WIPE
        elif style == 'sting':
            s = TransitionSettingsField.STYLE_STING
        elif style == 'dve':
            s = TransitionSettingsField.STYLE_DVE
        cmd = TransitionSettingsCommand(index=index, style=s)
        self.connection.mixer.send_commands([cmd])

    def on_wipe_pattern_clicked(self, widget):
        if self.model_changing:
            return
        cmd = WipeSettingsCommand(index=0, pattern=widget.pattern)
        self.connection.mixer.send_commands([cmd])

    def on_tbar_position_changed(self, widget, index, position):
        cmd = TransitionPositionCommand(index=index, position=position)
        self.connection.mixer.send_commands([cmd])

    def on_next_clicked(self, widget, index, current):
        print('next', index, current)
        cmd = TransitionSettingsCommand(index=index, next_transition=current)
        self.connection.mixer.send_commands([cmd])

    def on_prev_trans_clicked(self, widget, index, enabled):
        cmd = TransitionPreviewCommand(index=index, enabled=enabled)
        self.connection.mixer.send_commands([cmd])

    def on_color1_color_set(self, widget):
        color = widget.get_rgba()
        cmd = ColorGeneratorCommand.from_rgb(index=0, red=color.red, green=color.green, blue=color.blue)
        self.connection.mixer.send_commands([cmd])

    def on_color2_color_set(self, widget):
        color = widget.get_rgba()
        cmd = ColorGeneratorCommand.from_rgb(index=1, red=color.red, green=color.green, blue=color.blue)
        self.connection.mixer.send_commands([cmd])

    def on_auto_rate_changed(self, widget, index, style, frames):
        if self.model_changing:
            return
        cmd = None
        # Send new rate to the mixer
        if style == 'mix':
            cmd = MixSettingsCommand(index=index, rate=frames)
        elif style == 'dip':
            cmd = DipSettingsCommand(index=index, rate=frames)
        elif style == 'wipe':
            cmd = WipeSettingsCommand(index=index, rate=frames)
        elif style == 'dve':
            cmd = DveSettingsCommand(index=index, rate=frames)
        if cmd is not None:
            self.connection.mixer.send_commands([cmd])

    def on_dip_source_changed(self, widget):
        if hasattr(widget, 'ignore_change') and widget.ignore_change or self.model_changing:
            return
        cmd = DipSettingsCommand(index=0, source=int(self.dip_source.get_active_id()))
        self.connection.mixer.send_commands([cmd])

    def on_aux_source_changed(self, widget):
        if hasattr(widget, 'ignore_change') and widget.ignore_change or self.model_changing:
            return
        cmd = AuxSourceCommand(widget.index, source=int(widget.get_active_id()))
        self.connection.mixer.send_commands([cmd])

    def on_wipe_symmetry_adj_value_changed(self, widget, *args):
        if self.model_changing:
            return
        cmd = WipeSettingsCommand(index=0, symmetry=int(widget.get_value()))
        self.connection.mixer.send_commands([cmd])

    def on_wipe_x_adj_value_changed(self, widget, *args):
        if self.model_changing:
            return
        cmd = WipeSettingsCommand(index=0, positionx=int(widget.get_value()))
        self.connection.mixer.send_commands([cmd])

    def on_wipe_y_adj_value_changed(self, widget, *args):
        if self.model_changing:
            return
        cmd = WipeSettingsCommand(index=0, positiony=int(widget.get_value()))
        self.connection.mixer.send_commands([cmd])

    def on_wipe_width_adj_value_changed(self, widget, *args):
        if self.model_changing:
            return
        cmd = WipeSettingsCommand(index=0, width=int(widget.get_value()))
        self.connection.mixer.send_commands([cmd])

    def on_wipe_softness_adj_value_changed(self, widget, *args):
        if self.model_changing:
            return
        cmd = WipeSettingsCommand(index=0, softness=int(widget.get_value()))
        self.connection.mixer.send_commands([cmd])

    def on_wipe_fill_changed(self, widget, *args):
        if hasattr(widget, 'ignore_change') and widget.ignore_change or self.model_changing:
            return
        cmd = WipeSettingsCommand(index=0, source=int(widget.get_active_id()))
        self.connection.mixer.send_commands([cmd])
        self.focus_dummy.grab_focus()

    def on_wipe_flipflop_clicked(self, widget, *args):
        if self.model_changing:
            return
        state = widget.get_style_context().has_class('active')
        cmd = WipeSettingsCommand(index=0, flipflop=not state)
        self.connection.mixer.send_commands([cmd])

    def on_wipe_reverse_clicked(self, widget, *args):
        if self.model_changing:
            return
        state = widget.get_style_context().has_class('active')
        cmd = WipeSettingsCommand(index=0, reverse=not state)
        self.connection.mixer.send_commands([cmd])

    def on_ftb_afv_clicked(self, widget, *args):
        # TODO: how to distingish between atem and fairlight?
        cmd = FairlightMasterPropertiesCommand(afv=not widget.get_style_context().has_class('active'))
        self.connection.mixer.send_commands([cmd])

    def on_rate_focus(self, *args):
        self.disable_shortcuts = True

    def on_rate_unfocus(self, *args):
        self.disable_shortcuts = False

    def on_slider_held(self, *args):
        self.slider_held = True

    def on_slider_released(self, *args):
        self.slider_held = False

    def frames_to_time(self, frames):
        # WTF BMD
        if self.mode.rate < 29:
            transition_rate = 25
        elif self.mode.rate < 49:
            transition_rate = 30
        elif self.mode.rate < 59:
            transition_rate = 25
        else:
            transition_rate = 30

        if self.mode is None:
            return '00:00'

        seconds = frames // transition_rate
        frames = frames % transition_rate
        return '{:02d}:{:02d}'.format(int(seconds), int(frames))

    def time_to_frames(self, timestr):
        if self.mode.rate < 29:
            transition_rate = 25
        elif self.mode.rate < 49:
            transition_rate = 30
        elif self.mode.rate < 59:
            transition_rate = 25
        else:
            transition_rate = 30

        if self.mode is None:
            return 0

        part = timestr.split(':')
        if len(part) == 1:
            return int(part[0]) * transition_rate
        elif len(part) == 2:
            return (int(part[0]) * transition_rate) + int(part[1])

    def on_ftb_change(self, data):
        if data.index > len(self.me) - 1:
            print("Got FTB change for non-existing M/E {}".format(data.index + 1))
            return
        self.me[data.index].set_ftb_rate(data.rate)

    def on_transition_mix_change(self, data):
        if data.index > len(self.me) - 1:
            print("Got transition mix change for non-existing M/E {}".format(data.index + 1))
            return

        label = self.frames_to_time(data.rate)
        self.mix_rate.set_text(label)
        self.me[data.index].set_auto_rate('mix', data.rate)

    def on_transition_dip_change(self, data):
        if data.index > len(self.me) - 1:
            print("Got transition dip change for non-existing M/E {}".format(data.index + 1))
            return

        label = self.frames_to_time(data.rate)
        self.dip_rate.set_text(label)
        self.dip_source.ignore_change = True
        self.dip_source.set_active_id(str(data.source))
        self.dip_source.ignore_change = False
        self.me[data.index].set_auto_rate('dip', data.rate)

    def on_transition_wipe_change(self, data):
        if data.index > len(self.me) - 1:
            print("Got transition wipe change for non-existing M/E {}".format(data.index + 1))
            return

        label = self.frames_to_time(data.rate)
        self.wipe_rate.set_text(label)
        self.me[data.index].set_auto_rate('wipe', data.rate)

        for style, button in enumerate(self.wipe_style):
            self.set_class(button, 'stylebtn', True)
            self.set_class(button, 'active', style == data.pattern)

        if not self.slider_held:
            self.model_changing = True
            self.wipe_symmetry_adj.set_value(data.symmetry)
            self.wipe_x_adj.set_value(data.positionx)
            self.wipe_y_adj.set_value(data.positiony)
            self.wipe_width_adj.set_value(data.width)
            self.wipe_softness_adj.set_value(data.softness)
            self.model_changing = False

        self.model_changing = True
        self.wipe_fill.set_active_id(str(data.source))
        self.model_changing = False

        self.wipe_fill.set_sensitive(data.width > 0)
        self.set_class(self.wipe_reverse, 'active', data.reverse)
        self.set_class(self.wipe_flipflop, 'active', data.flipflop)

    def on_transition_dve_change(self, data):
        if data.index > len(self.me) - 1:
            print("Got transition dve change for non-existing M/E {}".format(data.index + 1))
            return

        label = self.frames_to_time(data.rate)
        self.dve_rate.set_text(label)
        self.me[data.index].set_auto_rate('dve', data.rate)

    def _remap(self, value, old_min, old_max, new_min, new_max):
        return ((value - old_min) / (old_max - old_min)) * (new_max - new_min) + new_min

    def on_dsk_change(self, data):
        self.me[0].set_dsk(data)
        if data.index in self.dsks:
            self.dsks[data.index].on_key_properties_change(data)
            label = "Downstream keyer {}".format(data.index + 1)

            top = 9000 - data.top
            bottom = data.bottom + 9000
            left = data.left + 16000
            right = 16000 - data.right
            self.layout[0].update_mask(label, top, bottom, left, right)

    def on_dsk_state_change(self, data):
        self.me[0].set_dsk_state(data)
        label = "Downstream keyer {}".format(data.index + 1)
        self.layout[0].region_onair(label, data.on_air)

    def on_topology_change(self, data):
        for i in range(0, data.me_units - len(self.me)):
            self.add_mixeffect()

        # Topology is only used for downstream keyer count, only available on M/E 1
        self.me[0].set_topology(data)
        self.apply_css(self.me[0], self.provider)

        from gtk_switcher.downstreamkey import DownstreamKeyer
        for widget in self.downstream_keyers:
            self.downstream_keyers.remove(widget)

        for i in range(0, data.downstream_keyers):
            exp = Gtk.Expander()
            exp.get_style_context().add_class('bmdgroup')
            label = "Downstream keyer {}".format(i + 1)
            frame_label = Gtk.Label(label)
            frame_label.get_style_context().add_class("heading")
            exp.set_label_widget(frame_label)
            exp.set_expanded(True)
            dsk = DownstreamKeyer(index=i, connection=self.connection)
            self.dsks[dsk.index] = dsk
            self.has_models.append(dsk)
            exp.add(dsk)
            self.apply_css(dsk, self.provider)
            dsk.set_fill_model(self.model_me1_fill)
            dsk.set_key_model(self.model_key)
            self.downstream_keyers.pack_start(exp, False, True, 0)

            # Add the DSK to the layout editor of M/E 1
            self.layout[0].update_region(label, 0, 0, 16, 9)
            self.layout[0].update_mask(label, 0, 0, 0, 0)
        self.downstream_keyers.show_all()

    def on_dsk_tie_clicked(self, widget, index, dsk, enabled):
        cmd = DkeyTieCommand(index=dsk, tie=enabled)
        self.connection.mixer.send_commands([cmd])

    def on_dsk_onair_clicked(self, widget, index, dsk, enabled):
        cmd = DkeyOnairCommand(index=dsk, on_air=enabled)
        self.connection.mixer.send_commands([cmd])

    def on_dsk_rate_activate(self, widget, index, dsk, frames):
        cmd = DkeyRateCommand(index=dsk, rate=frames)
        self.connection.mixer.send_commands([cmd])

    def on_dsk_auto_clicked(self, widget, index, dsk):
        cmd = DkeyAutoCommand(index=dsk)
        self.connection.mixer.send_commands([cmd])

    def on_mixer_effect_config_change(self, data):
        if data.index > len(self.me) - 1:
            print("Got _MeC for non-existing M/E {}".format(data.index + 1))
            return

        self.me[data.index].set_config(data)

        from gtk_switcher.upstreamkey import UpstreamKeyer

        if data.keyers > self.usk_count:
            add = data.keyers - self.usk_count

            for i in range(0, add):
                self.usk_count += 1
                exp = Gtk.Expander()
                exp.get_style_context().add_class('bmdgroup')
                frame_label = Gtk.Label("Upstream keyer {}".format(self.usk_count))
                frame_label.get_style_context().add_class("heading")
                exp.set_label_widget(frame_label)
                exp.set_expanded(True)
                usk = UpstreamKeyer(index=0, keyer=self.usk_count - 1, connection=self.connection)
                self.usks[usk.index] = usk
                self.has_models.append(usk)
                exp.add(usk)
                self.apply_css(usk, self.provider)
                usk.set_fill_model(self.model_me1_fill)
                usk.set_key_model(self.model_key)
                self.upstream_keyers.pack_start(exp, False, True, 0)

            self.upstream_keyers.show_all()

    def on_ftb_state_change(self, data):
        if data.index > len(self.me) - 1:
            print("Got FTB state change for non-existing M/E {}".format(data.index + 1))
            return

        self.me[data.index].set_ftb_state(data.done, data.transitioning)

    def on_color_change(self, data):
        r, g, b = data.get_rgb()
        color = Gdk.RGBA()
        color.red = r
        color.green = g
        color.blue = b
        color.alpha = 1.0

        if data.index == 0:
            self.color1.set_rgba(color)
        else:
            self.color2.set_rgba(color)

    def on_key_on_air_change(self, data):
        if data.index > len(self.me) - 1:
            print("Got key-on-air for non-existant keyer {} M/E {}".format(data.keyer, data.index + 1))
            return
        self.me[data.index].set_key_on_air(data)
        self.layout[data.index].region_onair('Upstream key {}'.format(data.keyer + 1), data.enabled)

    def on_transition_preview_change(self, data):
        if data.index > len(self.me) - 1:
            print("Got transition preview change for non-existing M/E {}".format(data.index + 1))
            return
        self.me[data.index].set_preview_transition(data.enabled)

    def on_transition_settings_change(self, data):
        if data.index > len(self.me) - 1:
            print("Got transition settings change for non-existing M/E {}".format(data.index + 1))
            return
        self.me[data.index].set_transition_settings(data)

    def on_transition_position_change(self, data):
        if data.index > len(self.me) - 1:
            print("Got transition position change for non-existing M/E {}".format(data.index + 1))
            return
        self.me[data.index].set_transition_progress(data)

    def on_onair_clicked(self, widget, index, keyer, enabled):
        cmd = KeyOnAirCommand(index=index, keyer=keyer, enabled=enabled)
        self.connection.mixer.send_commands([cmd])

    def on_key_properties_base_change(self, data):
        if data.keyer not in self.usks:
            print("Got key-properties-base for non-existant keyer {} M/E {}".format(data.keyer, data.index + 1))
            return
        self.usks[data.index].on_key_properties_base_change(data)

    def on_key_properties_luma_change(self, data):
        if data.keyer not in self.usks:
            print("Got key-properties-luma for non-existant keyer {} M/E {}".format(data.keyer, data.index + 1))
            return
        self.usks[data.index].on_key_properties_luma_change(data)

    def on_key_properties_dve_change(self, data):
        if data.keyer not in self.usks:
            print("Got key-properties-dve for non-existant keyer {} M/E {}".format(data.keyer, data.index + 1))
            return
        self.usks[data.keyer].on_key_properties_dve_change(data)
        width = 16.0 * data.size_x / 1000
        height = 9.0 * data.size_y / 1000
        self.layout[data.index].update_region('Upstream key {}'.format(data.keyer + 1),
                                              data.pos_x / 1000, data.pos_y / 1000, width, height)

        self.layout[data.index].update_mask('Upstream key {}'.format(data.keyer + 1),
                                            data.mask_top, data.mask_bottom, data.mask_left, data.mask_right)

    def on_program_input_change(self, data):
        if data.index > len(self.me) - 1:
            print("Got program input change for non-existing M/E {}".format(data.index + 1))
            return
        self.me[data.index].program_input_change(data)

    def on_preview_input_change(self, data):
        if data.index > len(self.me) - 1:
            print("Got preview input change for non-existing M/E {}".format(data.index + 1))
            return
        self.me[data.index].preview_input_change(data)

    def on_dkey_properties_base_change(self, data):
        if data.index not in self.dsks:
            print("Got dkey-properties-base for non-existant keyer {}".format(data.index))
            return
        self.dsks[data.index].on_key_properties_base_change(data)

    def on_me_program_changed(self, widget, index, source):
        cmd = ProgramInputCommand(index=index, source=source)
        self.connection.mixer.send_commands([cmd])

    def on_me_preview_changed(self, widget, index, source):
        cmd = PreviewInputCommand(index=index, source=source)
        self.connection.mixer.send_commands([cmd])

    def on_stream_recording_setting_change(self, data):
        self.expander_stream_recorder.show()
        self.model_changing = True
        self.stream_recorder_filename.set_text(data.filename)
        self.stream_recorder_disk = [data.disk1, data.disk2]
        self.stream_recorder_disk1.set_active_id(str(data.disk1))
        self.stream_recorder_disk2.set_active_id(str(data.disk2))
        self.on_update_recording_buttons()
        self.model_changing = False

    def on_stream_recording_disks_change(self, data):
        self.model_changing = True
        if data.is_deleted:
            del self.disks[data.index]
        else:
            self.disks[data.index] = data
            for row in self.model_disks:
                if row[0] == str(data.index):
                    break
            else:
                self.model_disks.append([str(data.index), data.volumename])

        self.stream_recorder_disk1.set_active_id(str(self.stream_recorder_disk[0]))
        self.stream_recorder_disk2.set_active_id(str(self.stream_recorder_disk[0]))
        self.stream_recorder_disk1.set_sensitive(self.stream_recorder_disk[0] is not None)
        self.stream_recorder_disk2.set_sensitive(self.stream_recorder_disk[1] is not None)
        self.on_update_recording_buttons()
        self.model_changing = False

    def on_stream_recording_status_change(self, data):
        self.on_update_recording_buttons()

        status = 'STOP'
        active = False
        if data.has_dropped:
            status = 'DROP'
            active = True
        elif data.is_stopping:
            status = 'STOPPING'
        elif data.disk_full:
            status = 'DISK FULL'
        elif data.is_recording:
            status = 'REC'
            active = True

        self.stream_recorder_status.set_text(status)
        self.set_class(self.stream_recorder_status, 'program', active)
        self.set_class(self.stream_recorder_clock, 'program', active)

        print(data)

    def on_update_recording_buttons(self):
        has_usable_disks = False
        for index in self.disks:
            if self.disks[index].is_ready:
                has_usable_disks = True
        has_multi_ready_disks = self.stream_recorder_disk[0] is not None and self.stream_recorder_disk[1] is not None

        if 'recording-status' not in self.connection.mixer.mixerstate:
            return

        status = self.connection.mixer.mixerstate['recording-status']
        is_recording = status.is_recording

        self.stream_recorder_start.set_sensitive(has_usable_disks and not is_recording)
        self.stream_recorder_stop.set_sensitive(is_recording)
        self.stream_recorder_switch.set_sensitive(has_multi_ready_disks and is_recording)

        self.set_class(self.stream_recorder_disk1_label, 'program',
                       self.stream_recorder_disk[0] is not None
                       and self.stream_recorder_disk[0] in self.disks
                       and self.disks[self.stream_recorder_disk[0]].is_recording)
        self.set_class(self.stream_recorder_disk2_label, 'program',
                       self.stream_recorder_disk[1] is not None
                       and self.stream_recorder_disk[1] in self.disks
                       and self.disks[self.stream_recorder_disk[1]].is_recording)

    def on_stream_recorder_start_clicked(self, widget, *args):
        cmd = RecorderStatusCommand(recording=True)
        self.connection.mixer.send_commands([cmd])

    def on_stream_recorder_stop_clicked(self, widget, *args):
        cmd = RecorderStatusCommand(recording=False)
        self.connection.mixer.send_commands([cmd])

    def on_aux_output_source_change(self, source):
        if source.index not in self.aux:
            return

        self.aux[source.index].ignore_change = True
        self.aux[source.index].set_active_id(str(source.source))
        self.aux[source.index].ignore_change = False

        for me in self.me:
            if not hasattr(me, 'category'):
                continue
            if me.index == source.index:
                me.source_change(source.source)

    def on_input_layout_change(self, changed_input):
        inputs = self.connection.mixer.mixerstate['input-properties']
        external = []
        colors = []
        mp = []
        black = None
        bars = None

        # Clear the combobox models
        self.model_changing = True
        for i in self.has_models:
            i.model_changing = True
        self.model_me1_fill.clear()
        self.model_aux.clear()
        self.model_key.clear()

        for i in inputs.values():
            if i.port_type == InputPropertiesField.PORT_EXTERNAL:
                external.append(i)
            if i.port_type == InputPropertiesField.PORT_COLOR:
                colors.append(i)
            if i.port_type == InputPropertiesField.PORT_MEDIAPLAYER and i.available_me1:
                mp.append(i)
            if i.port_type == InputPropertiesField.PORT_BLACK:
                black = i
            if i.port_type == InputPropertiesField.PORT_BARS:
                bars = i

            if i.available_me1:
                self.model_me1_fill.append([str(i.index), i.name])
            if i.available_key_source:
                self.model_key.append([str(i.index), i.name])

            if i.available_aux:
                self.model_aux.append([str(i.index), i.name])

            if i.port_type == InputPropertiesField.PORT_AUX_OUTPUT:
                aux_id = i.index - 8001
                if aux_id not in self.aux:
                    self.aux[aux_id] = Gtk.ComboBox.new_with_model(self.model_aux)
                    self.aux[aux_id].set_entry_text_column(1)
                    self.aux[aux_id].set_id_column(0)
                    self.aux[aux_id].index = aux_id
                    self.aux[aux_id].connect('changed', self.on_aux_source_changed)
                    renderer = Gtk.CellRendererText()
                    self.aux[aux_id].pack_start(renderer, True)
                    self.aux[aux_id].add_attribute(renderer, "text", 1)
                    self.grid_aux.attach(self.aux[aux_id], 1, aux_id, 1, 1)

                    aux_me = Gtk.CheckButton()
                    aux_me.index = i.index
                    aux_me.connect('toggled', self.on_aux_me_enable_toggled)
                    self.grid_aux.attach(aux_me, 2, aux_id, 1, 1)

                    aux_label = Gtk.Label(label=i.name)
                    aux_label.get_style_context().add_class('dim-label')
                    self.grid_aux.attach(aux_label, 0, aux_id, 1, 1)
                    self.grid_aux.show_all()

        row1_ext = external
        row2_ext = [None] * len(external)
        if len(external) > 4:
            num = len(external) // 2
            row1_ext = external[0:num]
            row2_ext = external[num:] + [None] * ((2 * num) - len(external))

        row1 = row1_ext + [None, black, None] + colors
        row2 = row2_ext + [None, bars, None] + mp

        buttons = [row1, row2]

        for me in self.me:
            me.set_inputs(buttons)
            self.apply_css(me, self.provider)

        self.model_changing = False
        for i in self.has_models:
            i.model_changing = False

    def on_aux_me_enable_toggled(self, widget):
        from gtk_switcher.mixeffect_aux import AuxMixEffectBlock
        if widget.get_active():
            inputs = self.connection.mixer.mixerstate['input-properties']
            auxsrcs = self.connection.mixer.mixerstate['aux-output-source']
            auxsrc = auxsrcs[widget.index - 8001]
            external = []
            output = []
            passthrough = []
            special = []
            black = []
            bars = []
            for i in inputs.values():
                if i.available_aux:
                    if i.port_type == InputPropertiesField.PORT_EXTERNAL:
                        external.append(i)
                    elif i.port_type == InputPropertiesField.PORT_ME_OUTPUT:
                        output.append(i)
                    elif i.port_type == InputPropertiesField.PORT_PASSTHROUGH:
                        passthrough.append(i)
                    elif i.port_type == InputPropertiesField.PORT_BLACK:
                        black.append(None)
                        black.append(i)
                    elif i.port_type == InputPropertiesField.PORT_BARS:
                        bars.append(None)
                        bars.append(i)
                    else:
                        special.append(i)

            row1_ext = external
            row2_ext = [None] * len(external)
            if len(external) > 6:
                num = len(external) // 2
                row1_ext = external[0:num]
                row2_ext = external[num:] + [None] * ((2 * num) - len(external))

                row1 = row1_ext + black + [None] + output + passthrough
                row2 = row2_ext + bars + [None] + special
            else:
                row1 = row1_ext + [None] + passthrough + black + bars + [None] + output + special
                row2 = row2_ext

            name = inputs[widget.index].name
            aux_me = AuxMixEffectBlock(widget.index, name)
            aux_me.set_inputs([row1, row2])
            aux_me.source_change(auxsrc.source)
            aux_me.connect('source-changed', self.on_aux_me_source_changed)
            aux_me.index = widget.index - 8001
            aux_me.category = 'aux'
            self.apply_css(aux_me, self.provider)
            self.me.append(aux_me)
            self.main_blocks.add(aux_me)
        else:
            # Remove the UI for this M/E
            pass

    def on_aux_me_source_changed(self, widget, aux, source):
        cmd = AuxSourceCommand(aux, source=source)
        self.connection.mixer.send_commands([cmd])