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