]> git.0d.be Git - jack_mixer.git/blob - jack_mixer.py
Display an error on incorrect settings file
[jack_mixer.git] / jack_mixer.py
1 #!/usr/bin/env python
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 from optparse import OptionParser
23
24 import gtk
25 import gobject
26 import sys
27 import os
28
29 old_path = sys.path
30 sys.path.insert(0, os.path.dirname(sys.argv[0]) + os.sep + ".." + os.sep + "share"+ os.sep + "jack_mixer")
31
32 import jack_mixer_c
33 import scale
34
35 try:
36     import lash
37 except:
38     lash = None
39
40 from channel import *
41 import gui
42 from preferences import PreferencesDialog
43
44 sys.path = old_path
45
46 from serialization_xml import xml_serialization
47 from serialization import serialized_object, serializator
48
49 if lash is None:
50     print >> sys.stderr, "Cannot load LASH python bindings, you want them unless you enjoy manual jack plumbing each time you use this app"
51
52 class jack_mixer(serialized_object):
53
54     # scales suitable as meter scales
55     meter_scales = [scale.iec_268(), scale.linear_70dB(), scale.iec_268_minimalistic()]
56
57     # scales suitable as volume slider scales
58     slider_scales = [scale.linear_30dB(), scale.linear_70dB()]
59
60     # name of settngs file that is currently open
61     current_filename = None
62
63     def __init__(self, name, lash_client):
64         self.mixer = jack_mixer_c.Mixer(name)
65         if not self.mixer:
66             return
67         self.monitor_channel = self.mixer.add_output_channel("Monitor", True, True)
68
69         if lash_client:
70             # Send our client name to server
71             lash_event = lash.lash_event_new_with_type(lash.LASH_Client_Name)
72             lash.lash_event_set_string(lash_event, name)
73             lash.lash_send_event(lash_client, lash_event)
74
75             lash.lash_jack_client_name(lash_client, name)
76
77         gtk.window_set_default_icon_name('jack_mixer')
78
79         self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
80         self.window.set_title(name)
81
82         self.gui_factory = gui.factory(self.window, self.meter_scales, self.slider_scales)
83
84         self.vbox_top = gtk.VBox()
85         self.window.add(self.vbox_top)
86
87         self.menubar = gtk.MenuBar()
88         self.vbox_top.pack_start(self.menubar, False)
89
90         mixer_menu_item = gtk.MenuItem("_Mixer")
91         self.menubar.append(mixer_menu_item)
92         edit_menu_item = gtk.MenuItem('_Edit')
93         self.menubar.append(edit_menu_item)
94         help_menu_item = gtk.MenuItem('_Help')
95         self.menubar.append(help_menu_item)
96
97         self.window.set_default_size(120,300)
98
99         mixer_menu = gtk.Menu()
100         mixer_menu_item.set_submenu(mixer_menu)
101
102         add_input_channel = gtk.ImageMenuItem('New _Input Channel')
103         mixer_menu.append(add_input_channel)
104         add_input_channel.connect("activate", self.on_add_input_channel)
105
106         add_output_channel = gtk.ImageMenuItem('New _Output Channel')
107         mixer_menu.append(add_output_channel)
108         add_output_channel.connect("activate", self.on_add_output_channel)
109
110         if lash_client is None and xml_serialization is not None:
111             mixer_menu.append(gtk.SeparatorMenuItem())
112             open = gtk.ImageMenuItem(gtk.STOCK_OPEN)
113             mixer_menu.append(open)
114             open.connect('activate', self.on_open_cb)
115             save = gtk.ImageMenuItem(gtk.STOCK_SAVE)
116             mixer_menu.append(save)
117             save.connect('activate', self.on_save_cb)
118             save_as = gtk.ImageMenuItem(gtk.STOCK_SAVE_AS)
119             mixer_menu.append(save_as)
120             save_as.connect('activate', self.on_save_as_cb)
121
122         mixer_menu.append(gtk.SeparatorMenuItem())
123
124         quit = gtk.ImageMenuItem(gtk.STOCK_QUIT)
125         mixer_menu.append(quit)
126         quit.connect('activate', self.on_quit_cb)
127
128         edit_menu = gtk.Menu()
129         edit_menu_item.set_submenu(edit_menu)
130
131         self.channel_remove_menu_item = gtk.ImageMenuItem(gtk.STOCK_REMOVE)
132         edit_menu.append(self.channel_remove_menu_item)
133         self.channel_remove_menu = gtk.Menu()
134         self.channel_remove_menu_item.set_submenu(self.channel_remove_menu)
135
136         channel_remove_all_menu_item = gtk.ImageMenuItem(gtk.STOCK_CLEAR)
137         edit_menu.append(channel_remove_all_menu_item)
138         channel_remove_all_menu_item.connect("activate", self.on_channels_clear)
139
140         edit_menu.append(gtk.SeparatorMenuItem())
141
142         preferences = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
143         preferences.connect('activate', self.on_preferences_cb)
144         edit_menu.append(preferences)
145
146         help_menu = gtk.Menu()
147         help_menu_item.set_submenu(help_menu)
148
149         about = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
150         help_menu.append(about)
151         about.connect("activate", self.on_about)
152
153         self.hbox_top = gtk.HBox()
154         self.vbox_top.pack_start(self.hbox_top, True)
155
156         self.scrolled_window = gtk.ScrolledWindow()
157         self.hbox_top.pack_start(self.scrolled_window, True)
158
159         self.hbox_inputs = gtk.HBox()
160         self.hbox_inputs.set_spacing(0)
161         self.hbox_inputs.set_border_width(0)
162         self.hbox_top.set_spacing(0)
163         self.hbox_top.set_border_width(0)
164         self.channels = []
165         self.output_channels = []
166
167         self.scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
168         self.scrolled_window.add_with_viewport(self.hbox_inputs)
169
170         self.main_mix = main_mix(self)
171         self.hbox_outputs = gtk.HBox()
172         self.hbox_outputs.set_spacing(0)
173         self.hbox_outputs.set_border_width(0)
174         frame = gtk.Frame()
175         frame.add(self.main_mix)
176         self.hbox_outputs.pack_start(frame, False)
177         self.hbox_top.pack_start(self.hbox_outputs, False)
178
179         self.window.connect("destroy", gtk.main_quit)
180
181         gobject.timeout_add(80, self.read_meters)
182         self.lash_client = lash_client
183
184         if lash_client:
185             gobject.timeout_add(1000, self.lash_check_events)
186
187     def cleanup(self):
188         print "Cleaning jack_mixer"
189         if not self.mixer:
190             return
191
192         for channel in self.channels:
193             channel.unrealize()
194
195     def on_open_cb(self, *args):
196         dlg = gtk.FileChooserDialog(title='Open', parent=self.window,
197                         action=gtk.FILE_CHOOSER_ACTION_OPEN,
198                         buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
199                                  gtk.STOCK_OPEN, gtk.RESPONSE_OK))
200         dlg.set_default_response(gtk.RESPONSE_OK)
201         if dlg.run() == gtk.RESPONSE_OK:
202             filename = dlg.get_filename()
203             try:
204                 f = file(filename, 'r')
205                 self.load_from_xml(f)
206             except:
207                 err = gtk.MessageDialog(self.window,
208                             gtk.DIALOG_MODAL,
209                             gtk.MESSAGE_ERROR,
210                             gtk.BUTTONS_OK,
211                             "Failed loading settings.")
212                 err.run()
213                 err.destroy()
214             else:
215                 self.current_filename = filename
216             finally:
217                 f.close()
218         dlg.destroy()
219
220     def on_save_cb(self, *args):
221         if not self.current_filename:
222             return self.on_save_as_cb()
223         f = file(self.current_filename, 'w')
224         self.save_to_xml(f)
225         f.close()
226
227     def on_save_as_cb(self, *args):
228         dlg = gtk.FileChooserDialog(title='Save', parent=self.window,
229                         action=gtk.FILE_CHOOSER_ACTION_SAVE,
230                         buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
231                                  gtk.STOCK_SAVE, gtk.RESPONSE_OK))
232         dlg.set_default_response(gtk.RESPONSE_OK)
233         if dlg.run() == gtk.RESPONSE_OK:
234             self.current_filename = dlg.get_filename()
235             self.on_save_cb()
236         dlg.destroy()
237
238     def on_quit_cb(self, *args):
239         gtk.main_quit()
240
241     preferences_dialog = None
242     def on_preferences_cb(self, widget):
243         if not self.preferences_dialog:
244             self.preferences_dialog = PreferencesDialog(self)
245         self.preferences_dialog.show()
246         self.preferences_dialog.present()
247
248     def on_add_input_channel(self, widget):
249         dialog = NewChannelDialog(app=self)
250         dialog.set_transient_for(self.window)
251         dialog.show()
252         ret = dialog.run()
253         dialog.hide()
254
255         if ret == gtk.RESPONSE_OK:
256             result = dialog.get_result()
257             channel = self.add_channel(**result)
258             self.window.show_all()
259
260     def on_add_output_channel(self, widget):
261         dialog = NewOutputChannelDialog(app=self)
262         dialog.set_transient_for(self.window)
263         dialog.show()
264         ret = dialog.run()
265         dialog.hide()
266
267         if ret == gtk.RESPONSE_OK:
268             result = dialog.get_result()
269             channel = self.add_output_channel(**result)
270             self.window.show_all()
271
272     def on_remove_channel(self, widget, channel):
273         print 'Removing channel "%s"' % channel.channel_name
274         self.channel_remove_menu.remove(widget)
275         if self.monitored_channel is channel:
276             channel.monitor_button.set_active(False)
277         for i in range(len(self.channels)):
278             if self.channels[i] is channel:
279                 channel.unrealize()
280                 del self.channels[i]
281                 self.hbox_inputs.remove(channel.parent)
282                 break
283         if len(self.channels) == 0:
284             self.channel_remove_menu_item.set_sensitive(False)
285
286     def on_channels_clear(self, widget):
287         for channel in self.channels:
288             channel.unrealize()
289             self.hbox_inputs.remove(channel.parent)
290         self.channels = []
291         self.channel_remove_menu = gtk.Menu()
292         self.channel_remove_menu_item.set_submenu(self.channel_remove_menu)
293         self.channel_remove_menu_item.set_sensitive(False)
294
295     def add_channel(self, name, stereo, volume_cc, balance_cc):
296         try:
297             channel = input_channel(self, name, stereo)
298             self.add_channel_precreated(channel)
299         except Exception:
300             err = gtk.MessageDialog(self.window,
301                             gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
302                             gtk.MESSAGE_ERROR,
303                             gtk.BUTTONS_OK,
304                             "Channel creation failed")
305             err.run()
306             err.destroy()
307             return
308         if volume_cc:
309             channel.channel.volume_midi_cc = int(volume_cc)
310         if balance_cc:
311             channel.channel.balance_midi_cc = int(balance_cc)
312         if not (volume_cc or balance_cc):
313             channel.channel.autoset_midi_cc()
314         return channel
315
316     def add_channel_precreated(self, channel):
317         frame = gtk.Frame()
318         frame.add(channel)
319         self.hbox_inputs.pack_start(frame, False)
320         channel.realize()
321         channel_remove_menu_item = gtk.MenuItem(channel.channel_name)
322         self.channel_remove_menu.append(channel_remove_menu_item)
323         channel_remove_menu_item.connect("activate", self.on_remove_channel, channel)
324         self.channel_remove_menu_item.set_sensitive(True)
325         self.channels.append(channel)
326
327         for outputchannel in self.output_channels:
328             channel.add_control_group(outputchannel)
329
330     def read_meters(self):
331         for channel in self.channels:
332             channel.read_meter()
333         self.main_mix.read_meter()
334         for channel in self.output_channels:
335             channel.read_meter()
336         return True
337
338     def add_output_channel(self, name, stereo, volume_cc, balance_cc, display_solo_buttons):
339         try:
340             channel = output_channel(self, name, stereo)
341             channel.display_solo_buttons = display_solo_buttons
342             self.add_output_channel_precreated(channel)
343         except Exception:
344             raise
345             err = gtk.MessageDialog(self.window,
346                             gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
347                             gtk.MESSAGE_ERROR,
348                             gtk.BUTTONS_OK,
349                             "Channel creation failed")
350             err.run()
351             err.destroy()
352             return
353         if volume_cc:
354             channel.channel.volume_midi_cc = int(volume_cc)
355         if balance_cc:
356             channel.channel.balance_midi_cc = int(balance_cc)
357         return channel
358
359     def add_output_channel_precreated(self, channel):
360         frame = gtk.Frame()
361         frame.add(channel)
362         self.hbox_outputs.pack_start(frame, False)
363         channel.realize()
364         # XXX: handle deletion of output channels
365         #channel_remove_menu_item = gtk.MenuItem(channel.channel_name)
366         #self.channel_remove_menu.append(channel_remove_menu_item)
367         #channel_remove_menu_item.connect("activate", self.on_remove_channel, channel, channel_remove_menu_item)
368         #self.channel_remove_menu_item.set_sensitive(True)
369         self.output_channels.append(channel)
370
371     _monitored_channel = None
372     def get_monitored_channel(self):
373         return self._monitored_channel
374
375     def set_monitored_channel(self, channel):
376         if self._monitored_channel:
377             if channel.channel.name == self._monitored_channel.channel.name:
378                 return
379         self._monitored_channel = channel
380         if type(channel) is input_channel:
381             # reset all solo/mute settings
382             for in_channel in self.channels:
383                 self.monitor_channel.set_solo(in_channel.channel, False)
384                 self.monitor_channel.set_muted(in_channel.channel, False)
385             self.monitor_channel.set_solo(channel.channel, True)
386             self.monitor_channel.prefader = True
387         else:
388             self.monitor_channel.prefader = False
389         self.update_monitor(channel)
390     monitored_channel = property(get_monitored_channel, set_monitored_channel)
391
392     def update_monitor(self, channel):
393         if self.monitored_channel is not channel:
394             return
395         self.monitor_channel.volume = channel.channel.volume
396         self.monitor_channel.balance = channel.channel.balance
397         if type(self.monitored_channel) is output_channel:
398             # sync solo/muted channels
399             for input_channel in self.channels:
400                 self.monitor_channel.set_solo(input_channel.channel,
401                                 channel.channel.is_solo(input_channel.channel))
402                 self.monitor_channel.set_muted(input_channel.channel,
403                                 channel.channel.is_muted(input_channel.channel))
404         elif type(self.monitored_channel) is main_mix:
405             # sync solo/muted channels
406             for input_channel in self.channels:
407                 self.monitor_channel.set_solo(input_channel.channel,
408                                 input_channel.channel.solo)
409                 self.monitor_channel.set_muted(input_channel.channel,
410                                 input_channel.channel.mute)
411
412     def get_input_channel_by_name(self, name):
413         for input_channel in self.channels:
414             if input_channel.channel.name == name:
415                 return input_channel
416         return None
417
418     def on_about(self, *args):
419         about = gtk.AboutDialog()
420         about.set_name('jack_mixer')
421         about.set_copyright('Copyright © 2006-2009\nNedko Arnaudov, Frederic Peters')
422         about.set_license('''\
423 jack_mixer is free software; you can redistribute it and/or modify it
424 under the terms of the GNU General Public License as published by the
425 Free Software Foundation; either version 2 of the License, or (at your
426 option) any later version.
427
428 jack_mixer is distributed in the hope that it will be useful, but
429 WITHOUT ANY WARRANTY; without even the implied warranty of
430 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
431 General Public License for more details.
432
433 You should have received a copy of the GNU General Public License along
434 with jack_mixer; if not, write to the Free Software Foundation, Inc., 51
435 Franklin Street, Fifth Floor, Boston, MA 02110-130159 USA''')
436         about.set_authors(['Nedko Arnaudov <nedko@arnaudov.name>',
437                            'Frederic Peters <fpeters@0d.be>'])
438         about.set_logo_icon_name('jack_mixer')
439         about.set_website('http://home.gna.org/jackmixer/')
440
441         about.run()
442         about.destroy()
443
444     def lash_check_events(self):
445         while lash.lash_get_pending_event_count(self.lash_client):
446             event = lash.lash_get_event(self.lash_client)
447
448             #print repr(event)
449
450             event_type = lash.lash_event_get_type(event)
451             if event_type == lash.LASH_Quit:
452                 print "jack_mixer: LASH ordered quit."
453                 gtk.main_quit()
454                 return False
455             elif event_type == lash.LASH_Save_File:
456                 directory = lash.lash_event_get_string(event)
457                 print "jack_mixer: LASH ordered to save data in directory %s" % directory
458                 filename = directory + os.sep + "jack_mixer.xml"
459                 f = file(filename, "w")
460                 self.save_to_xml(f)
461                 f.close()
462                 lash.lash_send_event(self.lash_client, event) # we crash with double free
463             elif event_type == lash.LASH_Restore_File:
464                 directory = lash.lash_event_get_string(event)
465                 print "jack_mixer: LASH ordered to restore data from directory %s" % directory
466                 filename = directory + os.sep + "jack_mixer.xml"
467                 f = file(filename, "r")
468                 self.load_from_xml(f, silence_errors=True)
469                 f.close()
470                 lash.lash_send_event(self.lash_client, event)
471             else:
472                 print "jack_mixer: Got unhandled LASH event, type " + str(event_type)
473                 return True
474
475             #lash.lash_event_destroy(event)
476
477         return True
478
479     def save_to_xml(self, file):
480         #print "Saving to XML..."
481         b = xml_serialization()
482         s = serializator()
483         s.serialize(self, b)
484         b.save(file)
485
486     def load_from_xml(self, file, silence_errors=False):
487         #print "Loading from XML..."
488         self.on_channels_clear(None)
489         self.unserialized_channels = []
490         b = xml_serialization()
491         try:
492             b.load(file)
493         except:
494             if silence_errors:
495                 return
496             raise
497         s = serializator()
498         s.unserialize(self, b)
499         for channel in self.unserialized_channels:
500             if isinstance(channel, input_channel):
501                 self.add_channel_precreated(channel)
502         for channel in self.unserialized_channels:
503             if isinstance(channel, output_channel):
504                 self.add_output_channel_precreated(channel)
505         del self.unserialized_channels
506         self.window.show_all()
507
508     def serialize(self, object_backend):
509         object_backend.add_property('geometry',
510                         '%sx%s' % (self.window.allocation.width, self.window.allocation.height))
511
512     def unserialize_property(self, name, value):
513         if name == 'geometry':
514             width, height = value.split('x')
515             self.window.resize(int(width), int(height))
516             return True
517
518     def unserialize_child(self, name):
519         if name == main_mix_serialization_name():
520             return self.main_mix
521
522         if name == input_channel_serialization_name():
523             channel = input_channel(self, "", True)
524             self.unserialized_channels.append(channel)
525             return channel
526
527         if name == output_channel_serialization_name():
528             channel = output_channel(self, "", True)
529             self.unserialized_channels.append(channel)
530             return channel
531
532     def serialization_get_childs(self):
533         '''Get child objects tha required and support serialization'''
534         childs = self.channels[:] + self.output_channels[:]
535         childs.append(self.main_mix)
536         return childs
537
538     def serialization_name(self):
539         return "jack_mixer"
540
541     def main(self):
542         self.main_mix.realize()
543         self.main_mix.set_monitored()
544
545         if not self.mixer:
546             return
547
548         self.window.show_all()
549
550         gtk.main()
551
552         #f = file("/dev/stdout", "w")
553         #self.save_to_xml(f)
554         #f.close
555
556 def help():
557     print "Usage: %s [mixer_name]" % sys.argv[0]
558
559 def main():
560     if lash:                        # If LASH python bindings are available
561         # sys.argv is modified by this call
562         lash_client = lash.init(sys.argv, "jack_mixer", lash.LASH_Config_File)
563     else:
564         lash_client = None
565
566     parser = OptionParser()
567     parser.add_option('-c', '--config', dest='config')
568     options, args = parser.parse_args()
569
570     # Yeah , this sounds stupid, we connected earlier, but we dont want to show this if we got --help option
571     # This issue should be fixed in pylash, there is a reason for having two functions for initialization after all
572     if lash_client:
573         print "Successfully connected to LASH server at " +  lash.lash_get_server_name(lash_client)
574
575     if len(args) == 1:
576         name = args[0]
577     else:
578         name = None
579
580     if not name:
581         name = "jack_mixer-%u" % os.getpid()
582
583     gtk.gdk.threads_init()
584     try:
585         mixer = jack_mixer(name, lash_client)
586     except Exception, e:
587         err = gtk.MessageDialog(None,
588                             gtk.DIALOG_MODAL,
589                             gtk.MESSAGE_ERROR,
590                             gtk.BUTTONS_OK,
591                             "Mixer creation failed (%s)" % str(e))
592         err.run()
593         err.destroy()
594         sys.exit(1)
595
596     if options.config:
597         f = file(options.config)
598         mixer.current_filename = options.config
599         try:
600             mixer.load_from_xml(f)
601         except:
602             err = gtk.MessageDialog(mixer.window,
603                             gtk.DIALOG_MODAL,
604                             gtk.MESSAGE_ERROR,
605                             gtk.BUTTONS_OK,
606                             "Failed loading settings.")
607             err.run()
608             err.destroy()
609         mixer.window.set_default_size(60*(1+len(mixer.channels)+len(mixer.output_channels)),300)
610         f.close()
611
612     mixer.main()
613
614     mixer.cleanup()
615
616 if __name__ == "__main__":
617     main()