/[svn]/jsampler/trunk/src/org/jsampler/CC.java
ViewVC logotype

Contents of /jsampler/trunk/src/org/jsampler/CC.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1567 - (show annotations) (download)
Thu Dec 6 19:37:41 2007 UTC (16 years, 3 months ago) by iliev
File size: 34420 byte(s)
* added confirmation dialog on exit
* some minor gui enhancements
* preparations for release 0.8a

1 /*
2 * JSampler - a java front-end for LinuxSampler
3 *
4 * Copyright (C) 2005-2007 Grigor Iliev <grigor@grigoriliev.com>
5 *
6 * This file is part of JSampler.
7 *
8 * JSampler is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 2
10 * as published by the Free Software Foundation.
11 *
12 * JSampler is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with JSampler; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
20 * MA 02111-1307 USA
21 */
22
23 package org.jsampler;
24
25 import java.awt.event.ActionEvent;
26 import java.awt.event.ActionListener;
27
28 import java.io.ByteArrayInputStream;
29 import java.io.ByteArrayOutputStream;
30 import java.io.File;
31 import java.io.FileInputStream;
32 import java.io.FileOutputStream;
33 import java.io.InputStream;
34
35 import java.util.Vector;
36
37 import java.util.logging.Handler;
38 import java.util.logging.Level;
39 import java.util.logging.Logger;
40 import java.util.logging.SimpleFormatter;
41 import java.util.logging.StreamHandler;
42
43 import javax.swing.Timer;
44
45 import net.sf.juife.Task;
46 import net.sf.juife.TaskQueue;
47
48 import net.sf.juife.event.TaskEvent;
49 import net.sf.juife.event.TaskListener;
50 import net.sf.juife.event.TaskQueueEvent;
51 import net.sf.juife.event.TaskQueueListener;
52
53 import org.jsampler.event.ListEvent;
54 import org.jsampler.event.ListListener;
55 import org.jsampler.event.OrchestraEvent;
56 import org.jsampler.event.OrchestraListener;
57
58 import org.jsampler.task.*;
59
60 import org.jsampler.view.JSMainFrame;
61 import org.jsampler.view.JSProgress;
62 import org.jsampler.view.JSViewConfig;
63 import org.jsampler.view.InstrumentsDbTreeModel;
64
65 import org.linuxsampler.lscp.AudioOutputChannel;
66 import org.linuxsampler.lscp.AudioOutputDevice;
67 import org.linuxsampler.lscp.Client;
68 import org.linuxsampler.lscp.FxSend;
69 import org.linuxsampler.lscp.MidiInputDevice;
70 import org.linuxsampler.lscp.MidiPort;
71 import org.linuxsampler.lscp.Parameter;
72 import org.linuxsampler.lscp.SamplerChannel;
73
74 import org.linuxsampler.lscp.event.*;
75
76 import org.w3c.dom.Document;
77 import org.w3c.dom.Node;
78
79 import static org.jsampler.JSI18n.i18n;
80
81
82 /**
83 * This class serves as a 'Control Center' of the application.
84 * It also provides some fundamental routines and access to most used objects.
85 * @author Grigor Iliev
86 */
87 public class CC {
88 private static Handler handler;
89 private static FileOutputStream fos;
90
91 private static JSViewConfig viewConfig = null;
92 private static JSMainFrame mainFrame = null;
93 private static JSProgress progress = null;
94
95 private final static Client lsClient = new Client();
96
97 private static String jSamplerHome = null;
98
99 private final static TaskQueue taskQueue = new TaskQueue();
100 private final static Timer timer = new Timer(2000, null);
101
102 /** Forbits the instantiation of this class. */
103 private
104 CC() { }
105
106 /**
107 * Returns the logger to be used for logging events.
108 * @return The logger to be used for logging events.
109 */
110 public static Logger
111 getLogger() {
112 return Logger.getLogger (
113 "org.jsampler",
114 "org.jsampler.langprops.LogsBundle"
115 );
116 }
117
118 /**
119 * Returns the task queue to be used for scheduling tasks
120 * for execution out of the event-dispatching thread.
121 * @return The task queue to be used for scheduling tasks
122 * for execution out of the event-dispatching thread.
123 */
124 public static TaskQueue
125 getTaskQueue() { return taskQueue; }
126
127 /**
128 * Adds the specified task to the task queue. All task in the
129 * queue equal to the specified task are removed from the queue.
130 */
131 public static void
132 scheduleTask(Task t) {
133 while(getTaskQueue().removeTask(t)) { }
134
135 if(getTaskQueue().getPendingTaskCount() == 0) {
136 if(t.equals(getTaskQueue().getRunningTask())) return;
137 }
138
139 getTaskQueue().add(t);
140 }
141
142 /**
143 * Gets the configuration of the current view.
144 */
145 public static JSViewConfig
146 getViewConfig() { return viewConfig; }
147
148 /**
149 * Sets the configuration of the current view.
150 */
151 public static void
152 setViewConfig(JSViewConfig viewConfig) { CC.viewConfig = viewConfig; }
153
154 /**
155 * Returns the main window of this application.
156 * @return The main window of this application.
157 */
158 public static JSMainFrame
159 getMainFrame() { return mainFrame; }
160
161 /**
162 * Sets the main window of this application.
163 * @param mainFrame The main window of this application.
164 */
165 public static void
166 setMainFrame(JSMainFrame mainFrame) { CC.mainFrame = mainFrame; }
167
168 /**
169 * Gets the progress indicator of this application.
170 * @return The progress indicator of this application.
171 */
172 public static JSProgress
173 getProgressIndicator() { return progress; }
174
175 /**
176 * Sets the progress indicator to be used by this application.
177 * @param progress The progress indicator to be used by this application.
178 */
179 public static void
180 setProgressIndicator(JSProgress progress) { CC.progress = progress; }
181
182 /**
183 * Gets the absolute path to the JSampler's home location.
184 * @return The absolute path to the JSampler's home location
185 * or <code>null</code> if the JSampler's home location is not specified yet.
186 */
187 public static String
188 getJSamplerHome() { return jSamplerHome; }
189
190 /**
191 * Sets the location of the JSampler's home.
192 * @param path The new absolute path to the JSampler's home location.
193 */
194 public static void
195 setJSamplerHome(String path) {
196 jSamplerHome = path;
197 Prefs.setJSamplerHome(jSamplerHome);
198 }
199
200 /**
201 * This method does the initial preparation of the application.
202 */
203 protected static void
204 initJSampler() {
205 fos = null;
206 setJSamplerHome(Prefs.getJSamplerHome());
207 String s = getJSamplerHome();
208 try {
209 if(s != null) {
210 s += File.separator + "jsampler.log";
211 File f = new File(s);
212 if(f.isFile()) HF.createBackup("jsampler.log", "jsampler.log.0");
213 fos = new FileOutputStream(s);
214 }
215 } catch(Exception x) { x.printStackTrace(); }
216
217 if(fos == null) handler = new StreamHandler(System.out, new SimpleFormatter());
218 else handler = new StreamHandler(fos, new SimpleFormatter());
219
220 handler.setLevel(Level.FINE);
221 getLogger().addHandler(handler);
222 getLogger().setLevel(Level.FINE);
223 Logger.getLogger("org.linuxsampler.lscp").setLevel(Level.FINE);
224 Logger.getLogger("org.linuxsampler.lscp").addHandler(handler);
225
226 // Flushing logs on every second
227 new java.util.Timer().schedule(new java.util.TimerTask() {
228 public void
229 run() { if(handler != null) handler.flush(); }
230 }, 1000, 1000);
231
232 CC.getLogger().fine("CC.jsStarted");
233
234 HF.setUIDefaultFont(Prefs.getInterfaceFont());
235
236 getClient().setServerAddress(Prefs.getLSAddress());
237 getClient().setServerPort(Prefs.getLSPort());
238
239 timer.setRepeats(false);
240
241 timer.addActionListener(new ActionListener() {
242 public void
243 actionPerformed(ActionEvent e) { CC.getProgressIndicator().start(); }
244 });
245
246 taskQueue.addTaskQueueListener(getHandler());
247
248 taskQueue.start();
249
250 getClient().removeChannelCountListener(getHandler());
251 getClient().addChannelCountListener(getHandler());
252
253 getClient().removeChannelInfoListener(getHandler());
254 getClient().addChannelInfoListener(getHandler());
255
256 getClient().removeFxSendCountListener(getHandler());
257 getClient().addFxSendCountListener(getHandler());
258
259 getClient().removeFxSendInfoListener(getHandler());
260 getClient().addFxSendInfoListener(getHandler());
261
262 getClient().removeStreamCountListener(getHandler());
263 getClient().addStreamCountListener(getHandler());
264
265 getClient().removeVoiceCountListener(getHandler());
266 getClient().addVoiceCountListener(getHandler());
267
268 getClient().removeTotalStreamCountListener(getHandler());
269 getClient().addTotalStreamCountListener(getHandler());
270
271 getClient().removeTotalVoiceCountListener(getHandler());
272 getClient().addTotalVoiceCountListener(getHandler());
273
274 getClient().removeAudioDeviceCountListener(audioDeviceCountListener);
275 getClient().addAudioDeviceCountListener(audioDeviceCountListener);
276
277 getClient().removeAudioDeviceInfoListener(audioDeviceInfoListener);
278 getClient().addAudioDeviceInfoListener(audioDeviceInfoListener);
279
280 getClient().removeMidiDeviceCountListener(midiDeviceCountListener);
281 getClient().addMidiDeviceCountListener(midiDeviceCountListener);
282
283 getClient().removeMidiDeviceInfoListener(midiDeviceInfoListener);
284 getClient().addMidiDeviceInfoListener(midiDeviceInfoListener);
285
286 getClient().removeMidiInstrumentMapCountListener(midiInstrMapCountListener);
287 getClient().addMidiInstrumentMapCountListener(midiInstrMapCountListener);
288
289 getClient().removeMidiInstrumentMapInfoListener(midiInstrMapInfoListener);
290 getClient().addMidiInstrumentMapInfoListener(midiInstrMapInfoListener);
291
292 getClient().removeMidiInstrumentCountListener(getHandler());
293 getClient().addMidiInstrumentCountListener(getHandler());
294
295 getClient().removeMidiInstrumentInfoListener(getHandler());
296 getClient().addMidiInstrumentInfoListener(getHandler());
297
298 getClient().removeGlobalInfoListener(getHandler());
299 getClient().addGlobalInfoListener(getHandler());
300 }
301
302 /**
303 * Checks whether the JSampler home directory is specified and exist.
304 * If the JSampler home directory is not specifed, or is specified
305 * but doesn't exist, a procedure of specifying a JSampler home
306 * directory is initiated.
307 * @see org.jsampler.view.JSMainFrame#installJSamplerHome
308 */
309 public static void
310 checkJSamplerHome() {
311 if(getJSamplerHome() != null) {
312 File f = new File(getJSamplerHome());
313 if(f.exists() && f.isDirectory()) {
314 return;
315 }
316 }
317
318 CC.getMainFrame().installJSamplerHome();
319 }
320
321 /**
322 * Changes the JSampler's home directory and moves all files from
323 * the old JSampler's home directory to the new one. If all files are
324 * moved succesfully, the old directory is deleted.
325 * @param path The location of the new JSampler's home directory. If
326 * the last directory in the path doesn't exist, it is created.
327 */
328 public static void
329 changeJSamplerHome(String path) {
330 File fNew = new File(path);
331 if(fNew.exists() && fNew.isFile()) {
332 HF.showErrorMessage(i18n.getError("CC.JSamplerHomeIsNotDir!"));
333 return;
334 }
335
336 if(!fNew.exists()) {
337 if(!fNew.mkdir()) {
338 String s = fNew.getAbsolutePath();
339 HF.showErrorMessage(i18n.getError("CC.mkdirFailed", s));
340 return;
341 }
342 }
343
344 if(getJSamplerHome() == null || path.equals(getJSamplerHome())) {
345 setJSamplerHome(fNew.getAbsolutePath());
346 return;
347 }
348
349 File fOld = new File(getJSamplerHome());
350 if(!fOld.exists() || !fOld.isDirectory()) {
351 setJSamplerHome(fNew.getAbsolutePath());
352 return;
353 }
354
355 File[] files = fOld.listFiles();
356 boolean b = true;
357 if(files != null) {
358 String s = fNew.getAbsolutePath() + File.separator;
359 for(File f : files) if(!f.renameTo(new File(s + f.getName()))) b = false;
360 }
361
362 if(b) fOld.delete();
363 setJSamplerHome(fNew.getAbsolutePath());
364 }
365
366 private final static OrchestraListModel orchestras = new DefaultOrchestraListModel();
367
368 /**
369 * Returns a list containing all available orchestras.
370 * @return A list containing all available orchestras.
371 */
372 public static OrchestraListModel
373 getOrchestras() { return orchestras; }
374
375 private static InstrumentsDbTreeModel instrumentsDbTreeModel = null;
376 /**
377 * Gets the tree model of the instruments database.
378 * If the currently used view doesn't have instruments
379 * database support the tree model is initialized on first use.
380 * @return The tree model of the instruments database or
381 * <code>null</code> if the backend doesn't have instruments database support.
382 * @see org.jsampler.view.JSViewConfig#getInstrumentsDbSupport
383 */
384 public static InstrumentsDbTreeModel
385 getInstrumentsDbTreeModel() {
386 if(!CC.getSamplerModel().getServerInfo().hasInstrumentsDbSupport()) return null;
387
388 if(instrumentsDbTreeModel == null) {
389 instrumentsDbTreeModel = new InstrumentsDbTreeModel();
390 }
391
392 return instrumentsDbTreeModel;
393 }
394
395 /**
396 * Loads the orchestras described in <code>&lt;jsampler_home&gt;/orchestras.xml</code>.
397 * If file with name <code>orchestras.xml.bkp</code> exist in the JSampler's home
398 * directory, this means that the last save has failed. In that case a recovery file
399 * <code>orchestras.xml.rec</code> is created and a recovery procedure
400 * will be initiated.
401 */
402 public static void
403 loadOrchestras() {
404 if(getJSamplerHome() == null) return;
405
406 try {
407 String s = getJSamplerHome();
408 if(s == null) return;
409 getOrchestras().addOrchestraListListener(getHandler());
410
411 File f = new File(s + File.separator + "orchestras.xml.bkp");
412 if(f.isFile()) HF.createBackup("orchestras.xml.bkp", "orchestras.xml.rec");
413
414 FileInputStream fis;
415 fis = new FileInputStream(s + File.separator + "orchestras.xml");
416
417 loadOrchestras(fis);
418 fis.close();
419 } catch(Exception x) {
420 getLogger().log(Level.INFO, HF.getErrorMessage(x), x);
421 }
422 }
423
424
425 private static void
426 loadOrchestras(InputStream in) {
427 Document doc = DOMUtils.readObject(in);
428
429 try { getOrchestras().readObject(doc.getDocumentElement()); }
430 catch(Exception x) {
431 HF.showErrorMessage(x, "Loading orchestras: ");
432 return;
433 }
434
435 for(int i = 0; i < getOrchestras().getOrchestraCount(); i++) {
436 getOrchestras().getOrchestra(i).addOrchestraListener(getHandler());
437 }
438 }
439
440 private static void
441 saveOrchestras() {
442 try {
443 String s = getJSamplerHome();
444 if(s == null) return;
445
446 HF.createBackup("orchestras.xml", "orchestras.xml.bkp");
447
448 FileOutputStream fos;
449 fos = new FileOutputStream(s + File.separator + "orchestras.xml", false);
450
451 Document doc = DOMUtils.createEmptyDocument();
452
453 Node node = doc.createElement("temp");
454 doc.appendChild(node);
455
456 getOrchestras().writeObject(doc, doc.getDocumentElement());
457
458 doc.replaceChild(node.getFirstChild(), node);
459
460 DOMUtils.writeObject(doc, fos);
461
462 fos.close();
463
464 HF.deleteFile("orchestras.xml.bkp");
465 } catch(Exception x) {
466 HF.showErrorMessage(x, "Saving orchestras: ");
467 return;
468 }
469 }
470
471 /**
472 * The exit point of the application which ensures clean exit with default exit status 0.
473 * @see #cleanExit(int i)
474 */
475 public static void
476 cleanExit() { cleanExit(0); }
477
478 /**
479 * The exit point of the application which ensures clean exit.
480 * @param i The exit status.
481 */
482 public static void
483 cleanExit(int i) {
484 CC.getLogger().fine("CC.jsEnded");
485 System.exit(i);
486 }
487
488 /**
489 * Gets the <code>Client</code> object that is used to communicate with the backend.
490 * @return The <code>Client</code> object that is used to communicate with the backend.
491 */
492 public static Client
493 getClient() { return lsClient; }
494
495 private static final Vector<ActionListener> listeners = new Vector<ActionListener>();
496
497 /**
498 * Registers the specified listener to be notified when reconnecting to LinuxSampler.
499 * @param l The <code>ActionListener</code> to register.
500 */
501 public static void
502 addReconnectListener(ActionListener l) { listeners.add(l); }
503
504 /**
505 * Removes the specified listener.
506 * @param l The <code>ActionListener</code> to remove.
507 */
508 public static void
509 removeReconnectListener(ActionListener l) { listeners.remove(l); }
510
511 private static void
512 fireReconnectEvent() {
513 ActionEvent e = new ActionEvent(CC.class, ActionEvent.ACTION_PERFORMED, null);
514 for(ActionListener l : listeners) l.actionPerformed(e);
515 }
516
517 private static final SamplerModel samplerModel = new DefaultSamplerModel();
518
519 /**
520 * Gets the sampler model.
521 * @return The sampler model.
522 */
523 public static SamplerModel
524 getSamplerModel() { return samplerModel; }
525
526 /**
527 * Reconnects to LinuxSampler.
528 */
529 public static void
530 reconnect() {
531 initSamplerModel();
532 fireReconnectEvent();
533 }
534
535 /**
536 * This method updates the information about the backend state.
537 */
538 public static void
539 initSamplerModel() {
540 final DefaultSamplerModel model = (DefaultSamplerModel)getSamplerModel();
541
542 final Global.GetServerInfo gsi = new Global.GetServerInfo();
543 gsi.addTaskListener(new TaskListener() {
544 public void
545 taskPerformed(TaskEvent e) {
546 if(gsi.doneWithErrors()) return;
547
548 model.setServerInfo(gsi.getResult());
549
550 if(CC.getViewConfig().getInstrumentsDbSupport()) {
551 getInstrumentsDbTreeModel();
552 }
553 }
554 });
555
556 final Audio.GetDrivers gaod = new Audio.GetDrivers();
557 gaod.addTaskListener(new TaskListener() {
558 public void
559 taskPerformed(TaskEvent e) {
560 if(!gaod.doneWithErrors())
561 model.setAudioOutputDrivers(gaod.getResult());
562 }
563 });
564
565 final GetEngines ge = new GetEngines();
566 ge.addTaskListener(new TaskListener() {
567 public void
568 taskPerformed(TaskEvent e) {
569 if(!ge.doneWithErrors()) model.setEngines(ge.getResult());
570 }
571 });
572
573 final Midi.GetDrivers gmid = new Midi.GetDrivers();
574 gmid.addTaskListener(new TaskListener() {
575 public void
576 taskPerformed(TaskEvent e) {
577 if(!gmid.doneWithErrors())
578 model.setMidiInputDrivers(gmid.getResult());
579 }
580 });
581
582 final Global.GetVolume gv = new Global.GetVolume();
583 gv.addTaskListener(new TaskListener() {
584 public void
585 taskPerformed(TaskEvent e) {
586 if(!gv.doneWithErrors())
587 model.setVolume(gv.getResult());
588 }
589 });
590
591 final Midi.GetInstrumentMaps mgim = new Midi.GetInstrumentMaps();
592 mgim.addTaskListener(new TaskListener() {
593 public void
594 taskPerformed(TaskEvent e) {
595 if(mgim.doneWithErrors()) return;
596 model.removeAllMidiInstrumentMaps();
597
598 for(MidiInstrumentMap map : mgim.getResult()) {
599 model.addMidiInstrumentMap(map);
600 }
601 }
602 });
603
604 final UpdateChannels uc = new UpdateChannels();
605 uc.addTaskListener(new TaskListener() {
606 public void
607 taskPerformed(TaskEvent e) {
608 for(SamplerChannelModel c : model.getChannels()) {
609 if(c.getChannelInfo().getEngine() == null) continue;
610
611 Channel.GetFxSends gfs = new Channel.GetFxSends();
612 gfs.setChannel(c.getChannelId());
613 gfs.addTaskListener(new GetFxSendsListener());
614 getTaskQueue().add(gfs);
615 }
616
617 // TODO: This should be done after the fx sends are set
618 //CC.getSamplerModel().setModified(false);
619 }
620 });
621
622
623 final Connect cnt = new Connect();
624 cnt.addTaskListener(new TaskListener() {
625 public void
626 taskPerformed(TaskEvent e) {
627 if(cnt.doneWithErrors()) return;
628
629 getTaskQueue().add(gsi);
630 getTaskQueue().add(gaod);
631 getTaskQueue().add(gmid);
632 getTaskQueue().add(ge);
633 getTaskQueue().add(gv);
634 getTaskQueue().add(mgim);
635 getTaskQueue().add(new Midi.UpdateDevices());
636 getTaskQueue().add(new Audio.UpdateDevices());
637 getTaskQueue().add(uc);
638 }
639 });
640 getTaskQueue().add(cnt);
641 }
642
643 private static class GetFxSendsListener implements TaskListener {
644 public void
645 taskPerformed(TaskEvent e) {
646 Channel.GetFxSends gfs = (Channel.GetFxSends)e.getSource();
647 if(gfs.doneWithErrors()) return;
648 SamplerChannelModel m = getSamplerModel().getChannelById(gfs.getChannel());
649 m.removeAllFxSends();
650
651 for(FxSend fxs : gfs.getResult()) m.addFxSend(fxs);
652 }
653 }
654
655 public static String
656 exportInstrMapsToLscpScript() {
657 StringBuffer sb = new StringBuffer("# Exported by: ");
658 sb.append("JSampler - a java front-end for LinuxSampler\r\n# Version: ");
659 sb.append(JSampler.VERSION).append("\r\n");
660 sb.append("# Date: ").append(new java.util.Date().toString()).append("\r\n\r\n");
661
662 Client lscpClient = new Client(true);
663 ByteArrayOutputStream out = new ByteArrayOutputStream();
664 lscpClient.setPrintOnlyModeOutputStream(out);
665
666 exportInstrMapsToLscpScript(lscpClient);
667 sb.append(out.toString());
668 out.reset();
669
670 return sb.toString();
671 }
672
673 private static void
674 exportInstrMapsToLscpScript(Client lscpClient) {
675 try {
676 lscpClient.removeAllMidiInstrumentMaps();
677 MidiInstrumentMap[] maps = CC.getSamplerModel().getMidiInstrumentMaps();
678 for(int i = 0; i < maps.length; i++) {
679 lscpClient.addMidiInstrumentMap(maps[i].getName());
680 exportInstrumentsToLscpScript(i, maps[i], lscpClient);
681 }
682 } catch(Exception e) {
683 CC.getLogger().log(Level.FINE, HF.getErrorMessage(e), e);
684 HF.showErrorMessage(e);
685 }
686 }
687
688 private static void
689 exportInstrumentsToLscpScript(int mapId, MidiInstrumentMap map, Client lscpClient)
690 throws Exception {
691
692 for(MidiInstrument i : map.getAllMidiInstruments()) {
693 lscpClient.mapMidiInstrument(mapId, i.getInfo().getEntry(), i.getInfo());
694 }
695 }
696
697 public static String
698 exportSessionToLscpScript() {
699 CC.getSamplerModel().setModified(false);
700
701 StringBuffer sb = new StringBuffer("# Exported by: ");
702 sb.append("JSampler - a java front-end for LinuxSampler\r\n# Version: ");
703 sb.append(JSampler.VERSION).append("\r\n");
704 sb.append("# Date: ").append(new java.util.Date().toString()).append("\r\n\r\n");
705
706 Client lscpClient = new Client(true);
707 ByteArrayOutputStream out = new ByteArrayOutputStream();
708 lscpClient.setPrintOnlyModeOutputStream(out);
709
710 try {
711 lscpClient.resetSampler();
712 sb.append(out.toString());
713 out.reset();
714 sb.append("\r\n");
715 lscpClient.setVolume(CC.getSamplerModel().getVolume());
716 sb.append(out.toString());
717 out.reset();
718 sb.append("\r\n");
719 } catch(Exception e) { CC.getLogger().log(Level.FINE, HF.getErrorMessage(e), e); }
720
721 MidiDeviceModel[] mDevs = getSamplerModel().getMidiDevices();
722 for(int i = 0; i < mDevs.length; i++) {
723 exportMidiDeviceToLscpScript(mDevs[i].getDeviceInfo(), i, lscpClient);
724 sb.append(out.toString());
725 out.reset();
726 sb.append("\r\n");
727 }
728
729 AudioDeviceModel[] aDevs = getSamplerModel().getAudioDevices();
730 for(int i = 0; i < aDevs.length; i++) {
731 exportAudioDeviceToLscpScript(aDevs[i].getDeviceInfo(), i, lscpClient);
732 sb.append(out.toString());
733 out.reset();
734 sb.append("\r\n");
735 }
736
737 SamplerChannelModel[] channels = getSamplerModel().getChannels();
738
739 for(int i = 0; i < channels.length; i++) {
740 SamplerChannelModel scm = channels[i];
741 exportChannelToLscpScript(scm.getChannelInfo(), i, lscpClient);
742 sb.append(out.toString());
743 out.reset();
744
745 sb.append("\r\n");
746
747 exportFxSendsToLscpScript(scm, i, lscpClient);
748 sb.append(out.toString());
749 out.reset();
750
751 sb.append("\r\n");
752 }
753
754 exportInstrMapsToLscpScript(lscpClient);
755 sb.append(out.toString());
756 out.reset();
757
758 return sb.toString();
759 }
760
761 private static void
762 exportMidiDeviceToLscpScript(MidiInputDevice mid, int devId, Client lscpCLient) {
763 try {
764 String s = mid.getDriverName();
765 lscpCLient.createMidiInputDevice(s, mid.getAdditionalParameters());
766
767 MidiPort[] mPorts = mid.getMidiPorts();
768 int l = mPorts.length;
769 if(l != 1) lscpCLient.setMidiInputPortCount(devId, l);
770
771 for(int i = 0; i < l; i++) {
772 Parameter[] prms = mPorts[i].getAllParameters();
773 for(Parameter p : prms) {
774 if(!p.isFixed() && p.getStringValue().length() > 0)
775 lscpCLient.setMidiInputPortParameter(devId, i, p);
776 }
777 }
778 } catch(Exception e) {
779 CC.getLogger().log(Level.FINE, HF.getErrorMessage(e), e);
780 }
781 }
782
783 private static void
784 exportAudioDeviceToLscpScript(AudioOutputDevice aod, int devId, Client lscpCLient) {
785 try {
786 String s = aod.getDriverName();
787 lscpCLient.createAudioOutputDevice(s, aod.getAllParameters());
788
789 AudioOutputChannel[] chns = aod.getAudioChannels();
790
791 for(int i = 0; i < chns.length; i++) {
792 Parameter[] prms = chns[i].getAllParameters();
793 for(Parameter p : prms) {
794 if(p.isFixed() || p.getStringValue().length() == 0);
795 else lscpCLient.setAudioOutputChannelParameter(devId, i, p);
796 }
797 }
798 } catch(Exception e) {
799 CC.getLogger().log(Level.FINE, HF.getErrorMessage(e), e);
800 }
801 }
802
803 private static void
804 exportChannelToLscpScript(SamplerChannel chn, int chnId, Client lscpCLient) {
805 try {
806 lscpCLient.addSamplerChannel();
807
808 SamplerModel sm = CC.getSamplerModel();
809 int id = chn.getMidiInputDevice();
810 if(id != -1) {
811 for(int i = 0; i < sm.getMidiDeviceCount(); i++) {
812 if(sm.getMidiDevice(i).getDeviceId() == id) {
813 lscpCLient.setChannelMidiInputDevice(chnId, i);
814 break;
815 }
816 }
817 lscpCLient.setChannelMidiInputPort(chnId, chn.getMidiInputPort());
818 lscpCLient.setChannelMidiInputChannel(chnId, chn.getMidiInputChannel());
819 }
820
821 id = chn.getAudioOutputDevice();
822 if(id != -1) {
823 for(int i = 0; i < sm.getAudioDeviceCount(); i++) {
824 if(sm.getAudioDevice(i).getDeviceId() == id) {
825 lscpCLient.setChannelAudioOutputDevice(chnId, i);
826 break;
827 }
828 }
829
830 Integer[] routing = chn.getAudioOutputRouting();
831
832 for(int j = 0; j < routing.length; j++) {
833 int k = routing[j];
834 if(k == j) continue;
835
836 lscpCLient.setChannelAudioOutputChannel(chnId, j, k);
837 }
838 }
839
840 if(chn.getEngine() != null) {
841 lscpCLient.loadSamplerEngine(chn.getEngine().getName(), chnId);
842 lscpCLient.setChannelVolume(chnId, chn.getVolume());
843 }
844
845 String s = chn.getInstrumentFile();
846 int i = chn.getInstrumentIndex();
847 if(s != null) lscpCLient.loadInstrument(s, i, chnId, true);
848
849 if(chn.isMuted()) lscpCLient.setChannelMute(chnId, true);
850 if(chn.isSoloChannel()) lscpCLient.setChannelSolo(chnId, true);
851 } catch(Exception e) {
852 CC.getLogger().log(Level.FINE, HF.getErrorMessage(e), e);
853 }
854 }
855
856 private static void
857 exportFxSendsToLscpScript(SamplerChannelModel scm, int chnId, Client lscpClient) {
858 try {
859 FxSend[] fxSends = scm.getFxSends();
860
861 for(int i = 0; i < fxSends.length; i++) {
862 FxSend f = fxSends[i];
863 lscpClient.createFxSend(chnId, f.getMidiController(), f.getName());
864
865 Integer[] r = f.getAudioOutputRouting();
866 for(int j = 0; j < r.length; j++) {
867 lscpClient.setFxSendAudioOutputChannel(chnId, i, j, r[j]);
868 }
869 }
870 } catch(Exception e) {
871 CC.getLogger().log(Level.FINE, HF.getErrorMessage(e), e);
872 }
873 }
874
875
876 private final static EventHandler eventHandler = new EventHandler();
877
878 private static EventHandler
879 getHandler() { return eventHandler; }
880
881 private static class EventHandler implements ChannelCountListener, ChannelInfoListener,
882 FxSendCountListener, FxSendInfoListener, StreamCountListener, VoiceCountListener,
883 TotalStreamCountListener, TotalVoiceCountListener, TaskQueueListener,
884 OrchestraListener, ListListener<OrchestraModel>, MidiInstrumentCountListener,
885 MidiInstrumentInfoListener, GlobalInfoListener {
886
887 /** Invoked when the number of channels has changed. */
888 public void
889 channelCountChanged( ChannelCountEvent e) {
890 getTaskQueue().add(new UpdateChannels());
891 }
892
893 /** Invoked when changes to the sampler channel has occured. */
894 public void
895 channelInfoChanged(ChannelInfoEvent e) {
896 /*
897 * Because of the rapid notification flow when instrument is loaded
898 * we need to do some optimization to decrease the traffic.
899 */
900 boolean b = true;
901 Task[] tS = getTaskQueue().getPendingTasks();
902
903 for(int i = tS.length - 1; i >= 0; i--) {
904 Task t = tS[i];
905
906 if(t instanceof Channel.UpdateInfo) {
907 Channel.UpdateInfo cui = (Channel.UpdateInfo)t;
908 if(cui.getChannelId() == e.getSamplerChannel()) return;
909 } else {
910 b = false;
911 break;
912 }
913 }
914
915 if(b) {
916 Task t = getTaskQueue().getRunningTask();
917 if(t instanceof Channel.UpdateInfo) {
918 Channel.UpdateInfo cui = (Channel.UpdateInfo)t;
919 if(cui.getChannelId() == e.getSamplerChannel()) return;
920 }
921 }
922
923
924 getTaskQueue().add(new Channel.UpdateInfo(e.getSamplerChannel()));
925 }
926
927 /**
928 * Invoked when the number of effect sends
929 * on a particular sampler channel has changed.
930 */
931 public void
932 fxSendCountChanged(FxSendCountEvent e) {
933 getTaskQueue().add(new Channel.UpdateFxSends(e.getChannel()));
934 }
935
936 /**
937 * Invoked when the settings of an effect sends are changed.
938 */
939 public void
940 fxSendInfoChanged(FxSendInfoEvent e) {
941 Task t = new Channel.UpdateFxSendInfo(e.getChannel(), e.getFxSend());
942 getTaskQueue().add(t);
943 }
944
945 /**
946 * Invoked when the number of active disk
947 * streams in a specific sampler channel has changed.
948 */
949 public void
950 streamCountChanged(StreamCountEvent e) {
951 SamplerChannelModel scm =
952 getSamplerModel().getChannelById(e.getSamplerChannel());
953
954 if(scm == null) {
955 CC.getLogger().log (
956 Level.WARNING,
957 "CC.unknownChannel!",
958 e.getSamplerChannel()
959 );
960
961 return;
962 }
963
964 scm.setStreamCount(e.getStreamCount());
965 }
966
967 /**
968 * Invoked when the number of active voices
969 * in a specific sampler channel has changed.
970 */
971 public void
972 voiceCountChanged(VoiceCountEvent e) {
973 SamplerChannelModel scm =
974 getSamplerModel().getChannelById(e.getSamplerChannel());
975
976 if(scm == null) {
977 CC.getLogger().log (
978 Level.WARNING,
979 "CC.unknownChannel!",
980 e.getSamplerChannel()
981 );
982
983 return;
984 }
985
986 scm.setVoiceCount(e.getVoiceCount());
987 }
988
989 /** Invoked when the total number of active streams has changed. */
990 public void
991 totalStreamCountChanged(TotalStreamCountEvent e) {
992 getSamplerModel().updateActiveStreamsInfo(e.getTotalStreamCount());
993 }
994
995 /** Invoked when the total number of active voices has changed. */
996 public void
997 totalVoiceCountChanged(TotalVoiceCountEvent e) {
998 getTaskQueue().add(new UpdateTotalVoiceCount());
999 }
1000
1001 /** Invoked when the number of MIDI instruments in a MIDI instrument map is changed. */
1002 public void
1003 instrumentCountChanged(MidiInstrumentCountEvent e) {
1004 getTaskQueue().add(new Midi.UpdateInstruments(e.getMapId()));
1005 }
1006
1007 /** Invoked when a MIDI instrument in a MIDI instrument map is changed. */
1008 public void
1009 instrumentInfoChanged(MidiInstrumentInfoEvent e) {
1010 Task t = new Midi.UpdateInstrumentInfo (
1011 e.getMapId(), e.getMidiBank(), e.getMidiProgram()
1012 );
1013 getTaskQueue().add(t);
1014
1015 }
1016
1017 /** Invoked when the global volume of the sampler is changed. */
1018 public void
1019 volumeChanged(GlobalInfoEvent e) {
1020 getSamplerModel().setVolume(e.getVolume());
1021 }
1022
1023 /**
1024 * Invoked to indicate that the state of a task queue is changed.
1025 * This method is invoked only from the event-dispatching thread.
1026 */
1027 public void
1028 stateChanged(TaskQueueEvent e) {
1029 switch(e.getEventID()) {
1030 case TASK_FETCHED:
1031 getProgressIndicator().setString (
1032 ((Task)e.getSource()).getDescription()
1033 );
1034 break;
1035 case TASK_DONE:
1036 EnhancedTask t = (EnhancedTask)e.getSource();
1037 if(t.doneWithErrors() && !t.isStopped()) {
1038 showError(t);
1039 }
1040 break;
1041 case NOT_IDLE:
1042 timer.start();
1043 break;
1044 case IDLE:
1045 timer.stop();
1046 getProgressIndicator().stop();
1047 break;
1048 }
1049 }
1050
1051 private void
1052 showError(final Task t) {
1053 javax.swing.SwingUtilities.invokeLater(new Runnable() {
1054 public void
1055 run() {
1056 if(t.getErrorDetails() == null) {
1057 HF.showErrorMessage(t.getErrorMessage());
1058 } else {
1059 getMainFrame().showDetailedErrorMessage (
1060 getMainFrame(),
1061 t.getErrorMessage(),
1062 t.getErrorDetails()
1063 );
1064 }
1065 }
1066 });
1067 }
1068
1069 /** Invoked when the name of orchestra is changed. */
1070 public void
1071 nameChanged(OrchestraEvent e) { saveOrchestras(); }
1072
1073 /** Invoked when the description of orchestra is changed. */
1074 public void
1075 descriptionChanged(OrchestraEvent e) { saveOrchestras(); }
1076
1077 /** Invoked when an instrument is added to the orchestra. */
1078 public void
1079 instrumentAdded(OrchestraEvent e) { saveOrchestras(); }
1080
1081 /** Invoked when an instrument is removed from the orchestra. */
1082 public void
1083 instrumentRemoved(OrchestraEvent e) { saveOrchestras(); }
1084
1085 /** Invoked when the settings of an instrument are changed. */
1086 public void
1087 instrumentChanged(OrchestraEvent e) { saveOrchestras(); }
1088
1089 /** Invoked when an orchestra is added to the orchestra list. */
1090 public void
1091 entryAdded(ListEvent<OrchestraModel> e) {
1092 e.getEntry().addOrchestraListener(getHandler());
1093 saveOrchestras();
1094 }
1095
1096 /** Invoked when an orchestra is removed from the orchestra list. */
1097 public void
1098 entryRemoved(ListEvent<OrchestraModel> e) {
1099 e.getEntry().removeOrchestraListener(getHandler());
1100 saveOrchestras();
1101 }
1102 }
1103
1104 private static final AudioDeviceCountListener audioDeviceCountListener =
1105 new AudioDeviceCountListener();
1106
1107 private static class AudioDeviceCountListener implements ItemCountListener {
1108 /** Invoked when the number of audio output devices has changed. */
1109 public void
1110 itemCountChanged(ItemCountEvent e) {
1111 getTaskQueue().add(new Audio.UpdateDevices());
1112 }
1113 }
1114
1115 private static final AudioDeviceInfoListener audioDeviceInfoListener =
1116 new AudioDeviceInfoListener();
1117
1118 private static class AudioDeviceInfoListener implements ItemInfoListener {
1119 /** Invoked when the audio output device's settings are changed. */
1120 public void
1121 itemInfoChanged(ItemInfoEvent e) {
1122 getTaskQueue().add(new Audio.UpdateDeviceInfo(e.getItemID()));
1123 }
1124 }
1125
1126 private static final MidiDeviceCountListener midiDeviceCountListener =
1127 new MidiDeviceCountListener();
1128
1129 private static class MidiDeviceCountListener implements ItemCountListener {
1130 /** Invoked when the number of MIDI input devices has changed. */
1131 public void
1132 itemCountChanged(ItemCountEvent e) {
1133 getTaskQueue().add(new Midi.UpdateDevices());
1134 }
1135 }
1136
1137 private static final MidiDeviceInfoListener midiDeviceInfoListener =
1138 new MidiDeviceInfoListener();
1139
1140 private static class MidiDeviceInfoListener implements ItemInfoListener {
1141 /** Invoked when the MIDI input device's settings are changed. */
1142 public void
1143 itemInfoChanged(ItemInfoEvent e) {
1144 getTaskQueue().add(new Midi.UpdateDeviceInfo(e.getItemID()));
1145 }
1146 }
1147
1148 private static final MidiInstrMapCountListener midiInstrMapCountListener =
1149 new MidiInstrMapCountListener();
1150
1151 private static class MidiInstrMapCountListener implements ItemCountListener {
1152 /** Invoked when the number of MIDI instrument maps is changed. */
1153 public void
1154 itemCountChanged(ItemCountEvent e) {
1155 getTaskQueue().add(new Midi.UpdateInstrumentMaps());
1156 }
1157 }
1158
1159 private static final MidiInstrMapInfoListener midiInstrMapInfoListener =
1160 new MidiInstrMapInfoListener();
1161
1162 private static class MidiInstrMapInfoListener implements ItemInfoListener {
1163 /** Invoked when the MIDI instrument map's settings are changed. */
1164 public void
1165 itemInfoChanged(ItemInfoEvent e) {
1166 getTaskQueue().add(new Midi.UpdateInstrumentMapInfo(e.getItemID()));
1167 }
1168 }
1169 }

  ViewVC Help
Powered by ViewVC