]> git.0d.be Git - jack_mixer.git/blob - jack_mixer.py
Fix crash on startup if not loading from config
[jack_mixer.git] / jack_mixer.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 #
4 # This file is part of jack_mixer
5 #
6 # Copyright (C) 2006-2009 Nedko Arnaudov <nedko@arnaudov.name>
7 # Copyright (C) 2009 Frederic Peters <fpeters@0d.be>
8 #
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; version 2 of the License
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21
22 import logging
23 import os
24 import signal
25 import sys
26 from argparse import ArgumentParser
27
28 import gi
29 gi.require_version('Gtk', '3.0')
30 from gi.repository import Gtk
31 from gi.repository import GObject
32 from gi.repository import GLib
33
34 # temporary change Python modules lookup path to look into installation
35 # directory ($prefix/share/jack_mixer/)
36 old_path = sys.path
37 sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..', 'share', 'jack_mixer'))
38
39 import jack_mixer_c
40
41 import gui
42 import scale
43 from channel import *
44 from nsmclient import NSMClient
45 from serialization_xml import XmlSerialization
46 from serialization import SerializedObject, Serializator
47 from preferences import PreferencesDialog
48
49 # restore Python modules lookup path
50 sys.path = old_path
51 log = logging.getLogger("jack_mixer")
52
53
54 class JackMixer(SerializedObject):
55
56     # scales suitable as meter scales
57     meter_scales = [scale.IEC268(), scale.Linear70dB(), scale.IEC268Minimalistic()]
58
59     # scales suitable as volume slider scales
60     slider_scales = [scale.Linear30dB(), scale.Linear70dB()]
61
62     # name of settngs file that is currently open
63     current_filename = None
64
65     _init_solo_channels = None
66
67     def __init__(self, client_name='jack_mixer'):
68         self.visible = False
69         self.nsm_client = None
70
71         if os.environ.get('NSM_URL'):
72             self.nsm_client = NSMClient(prettyName = "jack_mixer",
73                                         saveCallback = self.nsm_save_cb,
74                                         openOrNewCallback = self.nsm_open_cb,
75                                         supportsSaveStatus = False,
76                                         hideGUICallback = self.nsm_hide_cb,
77                                         showGUICallback = self.nsm_show_cb,
78                                         exitProgramCallback = self.nsm_exit_cb,
79                                         loggingLevel = "error",
80                                        )
81             self.nsm_client.announceGuiVisibility(self.visible)
82         else:
83
84             self.visible = True
85             self.create_mixer(client_name, with_nsm = False)
86
87     def create_mixer(self, client_name, with_nsm = True):
88         self.create_ui(with_nsm)
89         self.mixer = jack_mixer_c.Mixer(client_name)
90         if not self.mixer:
91             sys.exit(1)
92
93         self.window.set_title(client_name)
94
95         self.monitor_channel = self.mixer.add_output_channel("Monitor", True, True)
96         self.save = False
97
98         GLib.timeout_add(80, self.read_meters)
99         if with_nsm:
100             GLib.timeout_add(200, self.nsm_react)
101         GLib.timeout_add(50, self.midi_events_check)
102
103     def new_menu_item(self, title, callback=None, accel=None, enabled=True):
104         menuitem = Gtk.MenuItem.new_with_mnemonic(title)
105         menuitem.set_sensitive(enabled)
106         if callback:
107             menuitem.connect("activate", callback)
108         if accel:
109             key, mod = Gtk.accelerator_parse(accel)
110             menuitem.add_accelerator("activate", self.menu_accelgroup, key, mod,
111                                      Gtk.AccelFlags.VISIBLE)
112         return menuitem
113
114     def create_ui(self, with_nsm):
115         self.channels = []
116         self.output_channels = []
117         self.window = Gtk.Window(type=Gtk.WindowType.TOPLEVEL)
118         self.window.set_icon_name('jack_mixer')
119         self.gui_factory = gui.Factory(self.window, self.meter_scales, self.slider_scales)
120         self.gui_factory.connect('midi-behavior-mode-changed', self.on_midi_behavior_mode_changed)
121         self.vbox_top = Gtk.VBox()
122         self.window.add(self.vbox_top)
123
124         self.menu_accelgroup = Gtk.AccelGroup()
125         self.window.add_accel_group(self.menu_accelgroup)
126
127         self.menubar = Gtk.MenuBar()
128         self.vbox_top.pack_start(self.menubar, False, True, 0)
129
130         mixer_menu_item = Gtk.MenuItem.new_with_mnemonic("_Mixer")
131         self.menubar.append(mixer_menu_item)
132         edit_menu_item = Gtk.MenuItem.new_with_mnemonic('_Edit')
133         self.menubar.append(edit_menu_item)
134         help_menu_item = Gtk.MenuItem.new_with_mnemonic('_Help')
135         self.menubar.append(help_menu_item)
136
137         self.width = 420
138         self.height = 420
139         self.window.set_default_size(self.width, self.height)
140
141         self.mixer_menu = Gtk.Menu()
142         mixer_menu_item.set_submenu(self.mixer_menu)
143
144         self.mixer_menu.append(self.new_menu_item('New _Input Channel',
145                                                   self.on_add_input_channel, "<Control>N"))
146         self.mixer_menu.append(self.new_menu_item('New Output _Channel',
147                                                   self.on_add_output_channel, "<Shift><Control>N"))
148
149         self.mixer_menu.append(Gtk.SeparatorMenuItem())
150         if not with_nsm:
151             self.mixer_menu.append(self.new_menu_item('_Open...', self.on_open_cb, "<Control>O"))
152
153         self.mixer_menu.append(self.new_menu_item('_Save', self.on_save_cb, "<Control>S"))
154
155         if not with_nsm:
156             self.mixer_menu.append(self.new_menu_item('Save _As...', self.on_save_as_cb,
157                                                       "<Shift><Control>S"))
158
159         self.mixer_menu.append(Gtk.SeparatorMenuItem())
160         self.mixer_menu.append(self.new_menu_item('_Quit', self.on_quit_cb, "<Control>Q"))
161
162         edit_menu = Gtk.Menu()
163         edit_menu_item.set_submenu(edit_menu)
164
165         self.channel_edit_input_menu_item = self.new_menu_item('_Edit Input Channel',
166                                                                enabled=False)
167         edit_menu.append(self.channel_edit_input_menu_item)
168         self.channel_edit_input_menu = Gtk.Menu()
169         self.channel_edit_input_menu_item.set_submenu(self.channel_edit_input_menu)
170
171         self.channel_edit_output_menu_item = self.new_menu_item('E_dit Output Channel',
172                                                                 enabled=False)
173         edit_menu.append(self.channel_edit_output_menu_item)
174         self.channel_edit_output_menu = Gtk.Menu()
175         self.channel_edit_output_menu_item.set_submenu(self.channel_edit_output_menu)
176
177         self.channel_remove_input_menu_item = self.new_menu_item('_Remove Input Channel',
178                                                                  enabled=False)
179         edit_menu.append(self.channel_remove_input_menu_item)
180         self.channel_remove_input_menu = Gtk.Menu()
181         self.channel_remove_input_menu_item.set_submenu(self.channel_remove_input_menu)
182
183         self.channel_remove_output_menu_item = self.new_menu_item('Re_move Output Channel',
184                                                                   enabled=False)
185         edit_menu.append(self.channel_remove_output_menu_item)
186         self.channel_remove_output_menu = Gtk.Menu()
187         self.channel_remove_output_menu_item.set_submenu(self.channel_remove_output_menu)
188
189         edit_menu.append(self.new_menu_item('_Clear', self.on_channels_clear, "<Control>X"))
190         edit_menu.append(Gtk.SeparatorMenuItem())
191         edit_menu.append(self.new_menu_item('_Preferences', self.on_preferences_cb, "<Control>P"))
192
193         help_menu = Gtk.Menu()
194         help_menu_item.set_submenu(help_menu)
195
196         help_menu.append(self.new_menu_item('_About', self.on_about, "F1"))
197
198         self.hbox_top = Gtk.HBox()
199         self.vbox_top.pack_start(self.hbox_top, True, True, 0)
200
201         self.scrolled_window = Gtk.ScrolledWindow()
202         self.scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
203
204         self.hbox_inputs = Gtk.Box()
205         self.hbox_inputs.set_spacing(0)
206         self.hbox_inputs.set_border_width(0)
207         self.hbox_top.set_spacing(0)
208         self.hbox_top.set_border_width(0)
209         self.scrolled_window.add(self.hbox_inputs)
210         self.hbox_outputs = Gtk.Box()
211         self.hbox_outputs.set_spacing(0)
212         self.hbox_outputs.set_border_width(0)
213         self.scrolled_output = Gtk.ScrolledWindow()
214         self.scrolled_output.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
215         self.scrolled_output.add(self.hbox_outputs)
216         self.paned = Gtk.HPaned()
217         self.paned.set_wide_handle(True)
218         self.hbox_top.pack_start(self.paned, True, True, 0)
219         self.paned.pack1(self.scrolled_window, True, False)
220         self.paned.pack2(self.scrolled_output, True, False)
221
222         self.window.connect("destroy", Gtk.main_quit)
223
224         self.window.connect('delete-event', self.on_delete_event)
225
226     def nsm_react(self):
227         self.nsm_client.reactToMessage()
228         return True
229
230     def nsm_hide_cb(self):
231         self.window.hide()
232         self.visible = False
233         self.nsm_client.announceGuiVisibility(False)
234
235     def nsm_show_cb(self):
236         width, height = self.window.get_size()
237         self.window.show_all()
238         self.paned.set_position(self.paned_position/self.width*width)
239
240         self.visible = True
241         self.nsm_client.announceGuiVisibility(True)
242
243     def nsm_open_cb(self, path, session_name, client_name):
244         self.create_mixer(client_name, with_nsm = True)
245         self.current_filename = path + '.xml'
246         if os.path.isfile(self.current_filename):
247             f = open(self.current_filename, 'r')
248             self.load_from_xml(f, from_nsm=True)
249             f.close()
250         else:
251             f = open(self.current_filename, 'w')
252             f.close()
253
254     def nsm_save_cb(self, path, session_name, client_name):
255         self.current_filename = path + '.xml'
256         f = open(self.current_filename, 'w')
257         self.save_to_xml(f)
258         f.close()
259
260     def nsm_exit_cb(self, path, session_name, client_name):
261         Gtk.main_quit()
262
263     def on_midi_behavior_mode_changed(self, gui_factory, value):
264         self.mixer.midi_behavior_mode = value
265
266     def on_delete_event(self, widget, event):
267         return False
268
269     def sighandler(self, signum, frame):
270         log.debug("Signal %d received.", signum)
271         if signum == signal.SIGUSR1:
272             self.save = True
273         elif signum == signal.SIGTERM:
274             Gtk.main_quit()
275         elif signum == signal.SIGINT:
276             Gtk.main_quit()
277         else:
278             log.warning("Unknown signal %d received.", signum)
279
280     def cleanup(self):
281         log.debug("Cleaning jack_mixer.")
282         if not self.mixer:
283             return
284
285         for channel in self.channels:
286             channel.unrealize()
287
288         self.mixer.destroy()
289
290     def on_open_cb(self, *args):
291         dlg = Gtk.FileChooserDialog(title='Open', parent=self.window,
292                         action=Gtk.FileChooserAction.OPEN)
293         dlg.add_buttons(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
294                         Gtk.STOCK_OPEN, Gtk.ResponseType.OK)
295         dlg.set_default_response(Gtk.ResponseType.OK)
296         if dlg.run() == Gtk.ResponseType.OK:
297             filename = dlg.get_filename()
298             try:
299                 f = open(filename, 'r')
300                 self.load_from_xml(f)
301             except Exception as e:
302                 error_dialog(self.window, "Failed loading settings (%s)", e)
303             else:
304                 self.current_filename = filename
305             finally:
306                 f.close()
307         dlg.destroy()
308
309     def on_save_cb(self, *args):
310         if not self.current_filename:
311             return self.on_save_as_cb()
312         f = open(self.current_filename, 'w')
313         self.save_to_xml(f)
314         f.close()
315
316     def on_save_as_cb(self, *args):
317         dlg = Gtk.FileChooserDialog(title='Save', parent=self.window,
318                         action=Gtk.FileChooserAction.SAVE)
319         dlg.add_buttons(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
320                         Gtk.STOCK_SAVE, Gtk.ResponseType.OK)
321         dlg.set_default_response(Gtk.ResponseType.OK)
322         if dlg.run() == Gtk.ResponseType.OK:
323             self.current_filename = dlg.get_filename()
324             self.on_save_cb()
325         dlg.destroy()
326
327     def on_quit_cb(self, *args):
328         Gtk.main_quit()
329
330     preferences_dialog = None
331     def on_preferences_cb(self, widget):
332         if not self.preferences_dialog:
333             self.preferences_dialog = PreferencesDialog(self)
334         self.preferences_dialog.show()
335         self.preferences_dialog.present()
336
337     def on_add_input_channel(self, widget):
338         dialog = NewInputChannelDialog(app=self)
339         dialog.set_transient_for(self.window)
340         dialog.show()
341         ret = dialog.run()
342         dialog.hide()
343
344         if ret == Gtk.ResponseType.OK:
345             result = dialog.get_result()
346             channel = self.add_channel(**result)
347             if self.visible:
348                 self.window.show_all()
349
350     def on_add_output_channel(self, widget):
351         dialog = NewOutputChannelDialog(app=self)
352         dialog.set_transient_for(self.window)
353         dialog.show()
354         ret = dialog.run()
355         dialog.hide()
356
357         if ret == Gtk.ResponseType.OK:
358             result = dialog.get_result()
359             channel = self.add_output_channel(**result)
360             if self.visible:
361                 self.window.show_all()
362
363     def on_edit_input_channel(self, widget, channel):
364         log.debug('Editing input channel "%s".', channel.channel_name)
365         channel.on_channel_properties()
366
367     def remove_channel_edit_input_menuitem_by_label(self, widget, label):
368         if (widget.get_label() == label):
369             self.channel_edit_input_menu.remove(widget)
370
371     def on_remove_input_channel(self, widget, channel):
372         log.debug('Removing input channel "%s".', channel.channel_name)
373         self.channel_remove_input_menu.remove(widget)
374         self.channel_edit_input_menu.foreach(
375             self.remove_channel_edit_input_menuitem_by_label,
376             channel.channel_name);
377         if self.monitored_channel is channel:
378             channel.monitor_button.set_active(False)
379         for i in range(len(self.channels)):
380             if self.channels[i] is channel:
381                 channel.unrealize()
382                 del self.channels[i]
383                 self.hbox_inputs.remove(channel.get_parent())
384                 break
385         if not self.channels:
386             self.channel_edit_input_menu_item.set_sensitive(False)
387             self.channel_remove_input_menu_item.set_sensitive(False)
388
389     def on_edit_output_channel(self, widget, channel):
390         log.debug('Editing output channel "%s".', channel.channel_name)
391         channel.on_channel_properties()
392
393     def remove_channel_edit_output_menuitem_by_label(self, widget, label):
394         if (widget.get_label() == label):
395             self.channel_edit_output_menu.remove(widget)
396
397     def on_remove_output_channel(self, widget, channel):
398         log.debug('Removing output channel "%s".', channel.channel_name)
399         self.channel_remove_output_menu.remove(widget)
400         self.channel_edit_output_menu.foreach(
401             self.remove_channel_edit_output_menuitem_by_label,
402             channel.channel_name);
403         if self.monitored_channel is channel:
404             channel.monitor_button.set_active(False)
405         for i in range(len(self.channels)):
406             if self.output_channels[i] is channel:
407                 channel.unrealize()
408                 del self.output_channels[i]
409                 self.hbox_outputs.remove(channel.get_parent())
410                 break
411         if not self.output_channels:
412             self.channel_edit_output_menu_item.set_sensitive(False)
413             self.channel_remove_output_menu_item.set_sensitive(False)
414
415     def rename_channels(self, container, parameters):
416         if (container.get_label() == parameters['oldname']):
417             container.set_label(parameters['newname'])
418
419     def on_channel_rename(self, oldname, newname):
420         rename_parameters = { 'oldname' : oldname, 'newname' : newname }
421         self.channel_edit_input_menu.foreach(self.rename_channels,
422             rename_parameters)
423         self.channel_edit_output_menu.foreach(self.rename_channels,
424             rename_parameters)
425         self.channel_remove_input_menu.foreach(self.rename_channels,
426             rename_parameters)
427         self.channel_remove_output_menu.foreach(self.rename_channels,
428             rename_parameters)
429         log.debug('Renaming channel from "%s" to "%s".', oldname, newname)
430
431     def on_channels_clear(self, widget):
432         dlg = Gtk.MessageDialog(parent = self.window,
433                 modal = True,
434                 message_type = Gtk.MessageType.WARNING,
435                 text = "Are you sure you want to clear all channels?",
436                 buttons = Gtk.ButtonsType.OK_CANCEL)
437         if not widget or dlg.run() == Gtk.ResponseType.OK:
438             for channel in self.output_channels:
439                 channel.unrealize()
440                 self.hbox_outputs.remove(channel.get_parent())
441             for channel in self.channels:
442                 channel.unrealize()
443                 self.hbox_inputs.remove(channel.get_parent())
444             self.channels = []
445             self.output_channels = []
446             self.channel_edit_input_menu = Gtk.Menu()
447             self.channel_edit_input_menu_item.set_submenu(self.channel_edit_input_menu)
448             self.channel_edit_input_menu_item.set_sensitive(False)
449             self.channel_remove_input_menu = Gtk.Menu()
450             self.channel_remove_input_menu_item.set_submenu(self.channel_remove_input_menu)
451             self.channel_remove_input_menu_item.set_sensitive(False)
452             self.channel_edit_output_menu = Gtk.Menu()
453             self.channel_edit_output_menu_item.set_submenu(self.channel_edit_output_menu)
454             self.channel_edit_output_menu_item.set_sensitive(False)
455             self.channel_remove_output_menu = Gtk.Menu()
456             self.channel_remove_output_menu_item.set_submenu(self.channel_remove_output_menu)
457             self.channel_remove_output_menu_item.set_sensitive(False)
458         dlg.destroy()
459
460     def add_channel(self, name, stereo, volume_cc, balance_cc, mute_cc, solo_cc, value):
461         try:
462             channel = InputChannel(self, name, stereo, value)
463             self.add_channel_precreated(channel)
464         except Exception:
465             error_dialog(self.window, "Channel creation failed.")
466             return
467         if volume_cc != -1:
468             channel.channel.volume_midi_cc = volume_cc
469         else:
470             channel.channel.autoset_volume_midi_cc()
471         if balance_cc != -1:
472             channel.channel.balance_midi_cc = balance_cc
473         else:
474             channel.channel.autoset_balance_midi_cc()
475         if mute_cc != -1:
476             channel.channel.mute_midi_cc = mute_cc
477         else:
478             channel.channel.autoset_mute_midi_cc()
479         if solo_cc != -1:
480             channel.channel.solo_midi_cc = solo_cc
481         else:
482             channel.channel.autoset_solo_midi_cc()
483         return channel
484
485     def add_channel_precreated(self, channel):
486         frame = Gtk.Frame()
487         frame.add(channel)
488         self.hbox_inputs.pack_start(frame, False, True, 0)
489         channel.realize()
490
491         channel_edit_menu_item = Gtk.MenuItem(label=channel.channel_name)
492         self.channel_edit_input_menu.append(channel_edit_menu_item)
493         channel_edit_menu_item.connect("activate", self.on_edit_input_channel, channel)
494         self.channel_edit_input_menu_item.set_sensitive(True)
495
496         channel_remove_menu_item = Gtk.MenuItem(label=channel.channel_name)
497         self.channel_remove_input_menu.append(channel_remove_menu_item)
498         channel_remove_menu_item.connect("activate", self.on_remove_input_channel, channel)
499         self.channel_remove_input_menu_item.set_sensitive(True)
500
501         self.channels.append(channel)
502
503         for outputchannel in self.output_channels:
504             channel.add_control_group(outputchannel)
505
506         # create post fader output channel matching the input channel
507         channel.post_fader_output_channel = self.mixer.add_output_channel(
508                         channel.channel.name + ' Out', channel.channel.is_stereo, True)
509         channel.post_fader_output_channel.volume = 0
510         channel.post_fader_output_channel.set_solo(channel.channel, True)
511
512     def read_meters(self):
513         for channel in self.channels:
514             channel.read_meter()
515         for channel in self.output_channels:
516             channel.read_meter()
517         return True
518
519     def midi_events_check(self):
520         for channel in self.channels + self.output_channels:
521             channel.midi_events_check()
522         return True
523
524     def add_output_channel(self, name, stereo, volume_cc, balance_cc, mute_cc,
525             display_solo_buttons, color, value):
526         try:
527             channel = OutputChannel(self, name, stereo, value)
528             channel.display_solo_buttons = display_solo_buttons
529             channel.color = color
530             self.add_output_channel_precreated(channel)
531         except Exception:
532             error_dialog(self.window, "Channel creation failed")
533             return
534
535         if volume_cc != -1:
536             channel.channel.volume_midi_cc = volume_cc
537         else:
538             channel.channel.autoset_volume_midi_cc()
539         if balance_cc != -1:
540             channel.channel.balance_midi_cc = balance_cc
541         else:
542             channel.channel.autoset_balance_midi_cc()
543         if mute_cc != -1:
544             channel.channel.mute_midi_cc = mute_cc
545         else:
546             channel.channel.autoset_mute_midi_cc()
547
548         return channel
549
550     def add_output_channel_precreated(self, channel):
551         frame = Gtk.Frame()
552         frame.add(channel)
553         self.hbox_outputs.pack_end(frame, False, True, 0)
554         self.hbox_outputs.reorder_child(frame, 0)
555         channel.realize()
556
557         channel_edit_menu_item = Gtk.MenuItem(label=channel.channel_name)
558         self.channel_edit_output_menu.append(channel_edit_menu_item)
559         channel_edit_menu_item.connect("activate", self.on_edit_output_channel, channel)
560         self.channel_edit_output_menu_item.set_sensitive(True)
561
562         channel_remove_menu_item = Gtk.MenuItem(label=channel.channel_name)
563         self.channel_remove_output_menu.append(channel_remove_menu_item)
564         channel_remove_menu_item.connect("activate", self.on_remove_output_channel, channel)
565         self.channel_remove_output_menu_item.set_sensitive(True)
566
567         self.output_channels.append(channel)
568
569     _monitored_channel = None
570     def get_monitored_channel(self):
571         return self._monitored_channel
572
573     def set_monitored_channel(self, channel):
574         if self._monitored_channel:
575             if channel.channel.name == self._monitored_channel.channel.name:
576                 return
577         self._monitored_channel = channel
578         if type(channel) is InputChannel:
579             # reset all solo/mute settings
580             for in_channel in self.channels:
581                 self.monitor_channel.set_solo(in_channel.channel, False)
582                 self.monitor_channel.set_muted(in_channel.channel, False)
583             self.monitor_channel.set_solo(channel.channel, True)
584             self.monitor_channel.prefader = True
585         else:
586             self.monitor_channel.prefader = False
587         self.update_monitor(channel)
588     monitored_channel = property(get_monitored_channel, set_monitored_channel)
589
590     def update_monitor(self, channel):
591         if self.monitored_channel is not channel:
592             return
593         self.monitor_channel.volume = channel.channel.volume
594         self.monitor_channel.balance = channel.channel.balance
595         self.monitor_channel.out_mute = channel.channel.out_mute
596         if type(self.monitored_channel) is OutputChannel:
597             # sync solo/muted channels
598             for input_channel in self.channels:
599                 self.monitor_channel.set_solo(input_channel.channel,
600                                 channel.channel.is_solo(input_channel.channel))
601                 self.monitor_channel.set_muted(input_channel.channel,
602                                 channel.channel.is_muted(input_channel.channel))
603
604     def get_input_channel_by_name(self, name):
605         for input_channel in self.channels:
606             if input_channel.channel.name == name:
607                 return input_channel
608         return None
609
610     def on_about(self, *args):
611         about = Gtk.AboutDialog()
612         about.set_name('jack_mixer')
613         about.set_copyright('Copyright © 2006-2020\nNedko Arnaudov, Frédéric Péters, Arnout Engelen, Daniel Sheeler')
614         about.set_license('''\
615 jack_mixer is free software; you can redistribute it and/or modify it
616 under the terms of the GNU General Public License as published by the
617 Free Software Foundation; either version 2 of the License, or (at your
618 option) any later version.
619
620 jack_mixer is distributed in the hope that it will be useful, but
621 WITHOUT ANY WARRANTY; without even the implied warranty of
622 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
623 General Public License for more details.
624
625 You should have received a copy of the GNU General Public License along
626 with jack_mixer; if not, write to the Free Software Foundation, Inc., 51
627 Franklin Street, Fifth Floor, Boston, MA 02110-130159 USA''')
628         about.set_authors([
629             'Nedko Arnaudov <nedko@arnaudov.name>',
630             'Christopher Arndt <chris@chrisarndt.de>',
631             'Arnout Engelen <arnouten@bzzt.net>',
632             'John Hedges <john@drystone.co.uk>',
633             'Olivier Humbert <trebmuh@tuxfamily.org>',
634             'Sarah Mischke <sarah@spooky-online.de>',
635             'Frédéric Péters <fpeters@0d.be>',
636             'Daniel Sheeler <dsheeler@pobox.com>',
637             'Athanasios Silis <athanasios.silis@gmail.com>',
638         ])
639         about.set_logo_icon_name('jack_mixer')
640         about.set_website('https://rdio.space/jackmixer/')
641
642         about.run()
643         about.destroy()
644
645     def save_to_xml(self, file):
646         log.debug("Saving to XML...")
647         b = XmlSerialization()
648         s = Serializator()
649         s.serialize(self, b)
650         b.save(file)
651
652     def load_from_xml(self, file, silence_errors=False, from_nsm=False):
653         log.debug("Loading from XML...")
654         self.unserialized_channels = []
655         b = XmlSerialization()
656         try:
657             b.load(file)
658         except:
659             if silence_errors:
660                 return
661             raise
662         self.on_channels_clear(None)
663         s = Serializator()
664         s.unserialize(self, b)
665         for channel in self.unserialized_channels:
666             if isinstance(channel, InputChannel):
667                 if self._init_solo_channels and channel.channel_name in self._init_solo_channels:
668                     channel.solo = True
669                 self.add_channel_precreated(channel)
670         self._init_solo_channels = None
671         for channel in self.unserialized_channels:
672             if isinstance(channel, OutputChannel):
673                 self.add_output_channel_precreated(channel)
674         del self.unserialized_channels
675         width, height = self.window.get_size()
676         if self.visible or not from_nsm:
677             self.window.show_all()
678         self.paned.set_position(self.paned_position/self.width*width)
679         self.window.resize(self.width, self.height)
680  
681     def serialize(self, object_backend):
682         width, height = self.window.get_size()
683         object_backend.add_property('geometry',
684                         '%sx%s' % (width, height))
685         pos = self.paned.get_position()
686         object_backend.add_property('paned_position', '%s' % pos)
687         solo_channels = []
688         for input_channel in self.channels:
689             if input_channel.channel.solo:
690                 solo_channels.append(input_channel)
691         if solo_channels:
692             object_backend.add_property('solo_channels', '|'.join([x.channel.name for x in solo_channels]))
693         object_backend.add_property('visible', '%s' % str(self.visible))
694
695     def unserialize_property(self, name, value):
696         if name == 'geometry':
697             width, height = value.split('x')
698             self.width = int(width)
699             self.height = int(height)
700             return True
701         if name == 'solo_channels':
702             self._init_solo_channels = value.split('|')
703             return True
704         if name == 'visible':
705             self.visible = value == 'True'
706             return True
707         if name == 'paned_position':
708             self.paned_position = int(value)
709             return True
710         return False
711
712     def unserialize_child(self, name):
713         if name == InputChannel.serialization_name():
714             channel = InputChannel(self, "", True)
715             self.unserialized_channels.append(channel)
716             return channel
717
718         if name == OutputChannel.serialization_name():
719             channel = OutputChannel(self, "", True)
720             self.unserialized_channels.append(channel)
721             return channel
722
723         if name == gui.Factory.serialization_name():
724             return self.gui_factory
725
726     def serialization_get_childs(self):
727         '''Get child objects that required and support serialization'''
728         childs = self.channels[:] + self.output_channels[:] + [self.gui_factory]
729         return childs
730
731     def serialization_name(self):
732         return "jack_mixer"
733
734     def main(self):
735         if not self.mixer:
736             return
737
738         if self.visible or self.nsm_client == None:
739             width, height = self.window.get_size()
740             self.window.show_all()
741             if hasattr(self, 'paned_position'):
742                 self.paned.set_position(self.paned_position/self.width*width)
743
744         signal.signal(signal.SIGUSR1, self.sighandler)
745         signal.signal(signal.SIGTERM, self.sighandler)
746         signal.signal(signal.SIGINT, self.sighandler)
747         signal.signal(signal.SIGHUP, signal.SIG_IGN)
748
749         Gtk.main()
750
751 def error_dialog(parent, msg, *args):
752     log.exception(msg, *args)
753     err = Gtk.MessageDialog(parent=parent, modal=True, destroy_with_parent=True,
754         message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK, text=msg % args)
755     err.run()
756     err.destroy()
757
758 def main():
759     parser = ArgumentParser()
760     parser.add_argument('-c', '--config', metavar="FILE", help='load mixer project configuration from FILE')
761     parser.add_argument('-d', '--debug', action="store_true", help='enable debug logging messages')
762     parser.add_argument('client_name', metavar='NAME', nargs='?', default='jack_mixer',
763                         help='set JACK client name')
764     args = parser.parse_args()
765
766     logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO,
767                         format="%(levelname)s: %(message)s")
768
769     try:
770         mixer = JackMixer(args.client_name)
771     except Exception as e:
772         error_dialog(None, "Mixer creation failed (%s).", e)
773         sys.exit(1)
774
775     if not mixer.nsm_client and args.config:
776         f = open(args.config)
777         mixer.current_filename = args.config
778
779         try:
780             mixer.load_from_xml(f)
781         except Exception as e:
782             error_dialog(mixer.window, "Failed loading settings (%s).", e)
783
784         mixer.window.set_default_size(60*(1+len(mixer.channels)+len(mixer.output_channels)), 300)
785         f.close()
786
787     mixer.main()
788
789     mixer.cleanup()
790
791 if __name__ == "__main__":
792     main()