2 * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
3 * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
21 import jalview.bin.Cache;
22 import jalview.datamodel.AlignmentI;
23 import jalview.datamodel.ColumnSelection;
24 import jalview.datamodel.SequenceGroup;
25 import jalview.datamodel.SequenceI;
26 import jalview.io.VamsasAppDatastore;
27 import jalview.structure.SelectionListener;
28 import jalview.structure.SelectionSource;
29 import jalview.structure.StructureSelectionManager;
30 import jalview.structure.VamsasListener;
32 import java.beans.PropertyChangeEvent;
33 import java.beans.PropertyChangeListener;
35 import java.io.IOException;
36 import java.util.Enumeration;
37 import java.util.Hashtable;
38 import java.util.IdentityHashMap;
39 import java.util.Iterator;
41 import javax.swing.JInternalFrame;
42 import javax.swing.JOptionPane;
44 import uk.ac.vamsas.client.ClientHandle;
45 import uk.ac.vamsas.client.IClient;
46 import uk.ac.vamsas.client.IClientDocument;
47 import uk.ac.vamsas.client.InvalidSessionDocumentException;
48 import uk.ac.vamsas.client.NoDefaultSessionException;
49 import uk.ac.vamsas.client.UserHandle;
50 import uk.ac.vamsas.client.VorbaId;
51 import uk.ac.vamsas.client.picking.IMessageHandler;
52 import uk.ac.vamsas.client.picking.IPickManager;
53 import uk.ac.vamsas.client.picking.Message;
54 import uk.ac.vamsas.client.picking.MouseOverMessage;
55 import uk.ac.vamsas.client.picking.SelectionMessage;
56 import uk.ac.vamsas.objects.core.Entry;
57 import uk.ac.vamsas.objects.core.Input;
58 import uk.ac.vamsas.objects.core.Pos;
59 import uk.ac.vamsas.objects.core.Seg;
65 public class VamsasApplication implements SelectionSource
67 IClient vclient = null;
69 ClientHandle app = null;
71 UserHandle user = null;
73 Desktop jdesktop = null; // our jalview desktop reference
75 // Cache.preferences for vamsas client session arena
76 // preferences for check for default session at startup.
77 // user and organisation stuff.
78 public VamsasApplication(Desktop jdesktop, File sessionPath)
81 // we should create a session URI from the sessionPath and pass it to
82 // the clientFactory - but the vamsas api doesn't cope with that yet.
83 this.jdesktop = jdesktop;
84 initClientSession(null, sessionPath);
87 private static uk.ac.vamsas.client.IClientFactory getClientFactory()
90 return new uk.ac.vamsas.client.simpleclient.SimpleClientFactory();
94 * Start a new vamsas session
98 public VamsasApplication(Desktop jdesktop)
100 this.jdesktop = jdesktop;
101 initClientSession(null, null);
105 * init a connection to the session at the given url
110 public VamsasApplication(Desktop jdesktop, String sessionUrl)
112 this.jdesktop = jdesktop;
113 initClientSession(sessionUrl, null);
117 * @throws IOException
118 * or other if clientfactory instantiation failed.
119 * @return list of current sessions or null if no session exists.
121 public static String[] getSessionList() throws Exception
123 return getClientFactory().getCurrentSessions();
127 * initialise, possibly with either a valid session url or a file for a new
131 * null or a valid session url
132 * @param vamsasDocument
133 * null or a valid vamsas document file
134 * @return false if no vamsas connection was made
136 private boolean initClientSession(String sess, File vamsasDocument)
140 // Only need to tell the library what the application is here
141 app = getJalviewHandle();
142 uk.ac.vamsas.client.IClientFactory clientfactory = getClientFactory();
143 if (vamsasDocument != null)
148 "Implementation Error - cannot import existing vamsas document into an existing session, Yet!");
152 vclient = clientfactory.openAsNewSessionIClient(app,
154 } catch (InvalidSessionDocumentException e)
157 .showInternalMessageDialog(
160 "VAMSAS Document could not be opened as a new session - please choose another",
161 "VAMSAS Document Import Failed",
162 JOptionPane.ERROR_MESSAGE);
168 // join existing or create a new session
171 vclient = clientfactory.getNewSessionIClient(app);
175 vclient = clientfactory.getIClient(app, sess);
178 // set some properties for our VAMSAS interaction
180 user = vclient.getUserHandle();
182 } catch (Exception e)
184 jalview.bin.Cache.log
185 .error("Couldn't instantiate vamsas client !", e);
191 private void setVclientConfig()
199 if (vclient instanceof uk.ac.vamsas.client.simpleclient.SimpleClient)
201 uk.ac.vamsas.client.simpleclient.SimpleClientConfig cfg = ((uk.ac.vamsas.client.simpleclient.SimpleClient) vclient)
202 .getSimpleClientConfig();
203 cfg._validatemergedroots = false;
204 cfg._validateupdatedroots = true; // we may write rubbish otherwise.
210 "Probable SERIOUS VAMSAS client incompatibility - carrying on regardless",
212 } catch (Exception e)
216 "Probable VAMSAS client incompatibility - carrying on regardless",
222 * make the appHandle for Jalview
226 private ClientHandle getJalviewHandle()
228 return new ClientHandle("jalview.bin.Jalview", jalview.bin.Cache
229 .getProperty("VERSION"));
234 * @return true if we are registered in a vamsas session
236 public boolean inSession()
238 return (vclient != null);
242 * called to connect to session inits handlers, does an initial document
245 public void initial_update()
250 "Impementation error! Vamsas Operations when client not initialised and connected.");
252 addDocumentUpdateHandler();
253 addStoreDocumentHandler();
256 .debug("Jalview loading the Vamsas Session for the first time.");
257 dealWithDocumentUpdate(false); // we don't push an update out to the
259 Cache.log.debug("... finished update for the first time.");
263 * Update all windows after a vamsas datamodel change. this could go on the
267 protected void updateJalviewGui()
269 JInternalFrame[] frames = jdesktop.getAllFrames();
279 for (int i = frames.length - 1; i > -1; i--)
281 if (frames[i] instanceof AlignFrame)
283 AlignFrame af = (AlignFrame) frames[i];
284 af.alignPanel.alignmentChanged();
287 } catch (Exception e)
291 "Exception whilst refreshing jalview windows after a vamsas document update.",
296 public void push_update()
298 Thread udthread = new Thread(new Runnable()
303 Cache.log.info("Jalview updating to the Vamsas Session.");
305 dealWithDocumentUpdate(true);
306 Cache.log.info("Jalview finished updating to the Vamsas Session.");
314 * leave a session, prompting the user to save if necessary
316 public void end_session()
321 private boolean promptUser = true;
324 * leave a session, optionally prompting the user to save if necessary
327 * when true enable prompting by this application
330 public void end_session(boolean promptUser)
333 throw new Error("Jalview not connected to Vamsas session.");
334 Cache.log.info("Jalview disconnecting from the Vamsas Session.");
339 boolean ourprompt = this.promptUser;
340 this.promptUser = promptUser;
341 vclient.finalizeClient();
342 Cache.log.info("Jalview has left the session.");
343 this.promptUser = ourprompt; // restore default value
348 .warn("JV Client leaving a session that's its not joined yet.");
350 joinedSession = false;
356 } catch (Exception e)
358 Cache.log.error("Vamsas Session finalization threw exceptions!", e);
362 public void updateJalview(IClientDocument cdoc)
364 Cache.log.debug("Jalview updating from sesion document ..");
366 VamsasAppDatastore vds = new VamsasAppDatastore(cdoc, vobj2jv, jv2vobj,
367 baseProvEntry(), alRedoState);
370 vds.updateToJalview();
371 } catch (Exception e)
373 Cache.log.error("Failed to update Jalview from vamsas document.", e);
379 vds.updateJalviewFromAppdata();
380 // Comment this out to repeatedly read in data from JalviewAppData
381 // firstUpdate=false;
383 } catch (Exception e)
386 "Exception when updating Jalview settings from Appdata.", e);
388 Cache.log.debug(".. finished updating from sesion document.");
392 boolean firstUpdate = false;
394 private void ensureJvVamsas()
398 jv2vobj = new IdentityHashMap();
399 vobj2jv = new Hashtable();
400 alRedoState = new Hashtable();
406 * jalview object binding to VorbaIds
408 IdentityHashMap jv2vobj = null;
410 Hashtable vobj2jv = null;
412 Hashtable alRedoState = null;
414 boolean errorsDuringUpdate = false;
416 boolean errorsDuringAppUpdate = false;
419 * update the document accessed through doc. A backup of the current object
424 public void updateVamsasDocument(IClientDocument doc)
427 errorsDuringUpdate = false;
428 errorsDuringAppUpdate = false;
429 backup_objectMapping();
430 VamsasAppDatastore vds = new VamsasAppDatastore(doc, vobj2jv, jv2vobj,
431 baseProvEntry(), alRedoState);
432 // wander through frames
433 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
439 Hashtable skipList = new Hashtable();
440 Hashtable viewset = new Hashtable();
445 for (int i = frames.length - 1; i > -1; i--)
447 if (frames[i] instanceof AlignFrame)
449 AlignFrame af = (AlignFrame) frames[i];
450 if (!viewset.containsKey(af.getViewport().getSequenceSetId()))
452 // update alignment and root from frame.
453 boolean stored = false;
456 stored = vds.storeVAMSAS(af.getViewport(), af.getTitle());
457 } catch (Exception e)
459 errorsDuringUpdate = true;
460 Cache.log.error("Exception synchronizing "
463 + (af.getViewport().viewName == null ? "" : " view "
464 + af.getViewport().viewName)
465 + " to document.", e);
469 { // record skip in skipList
470 skipList.put(af.getViewport().getSequenceSetId(), af);
474 // could try to eliminate sequenceSetId from skiplist ..
475 // (skipList.containsKey(af.getViewport().getSequenceSetId()))
476 // remember sequenceSetId so we can skip all the other views on
478 viewset.put(af.getViewport().getSequenceSetId(), af);
484 // for (int i = frames.length - 1; i > -1; i--)
486 // if (frames[i] instanceof AlignFrame)
488 // AlignFrame af = (AlignFrame) frames[i];
489 Iterator aframes = viewset.values().iterator();
490 while (aframes.hasNext())
492 AlignFrame af = (AlignFrame) aframes.next();
493 // add any AlignedCodonFrame mappings on this alignment to any other.
494 vds.storeSequenceMappings(af.getViewport(), af.getTitle());
496 } catch (Exception e)
498 Cache.log.error("Exception synchronizing Views to Document :", e);
499 errorsDuringUpdate = true;
504 if (viewset.size() > 0)
506 // Alignment views were synchronized, so store their state in the
508 // The skipList ensures we don't write out any alignments not actually
510 vds.setSkipList(skipList);
511 vds.updateJalviewClientAppdata();
513 } catch (Exception e)
515 Cache.log.error("Client Appdata Write exception", e);
516 errorsDuringAppUpdate = true;
521 private Entry baseProvEntry()
523 uk.ac.vamsas.objects.core.Entry pentry = new uk.ac.vamsas.objects.core.Entry();
524 pentry.setUser(user.getFullName());
525 pentry.setApp(app.getClientUrn());
526 pentry.setDate(new java.util.Date());
527 pentry.setAction("created");
532 * do a vamsas document update or update jalview from the vamsas document
535 * true to update from jalview to the vamsas document
537 protected void dealWithDocumentUpdate(boolean fromJalview)
539 // called by update handler for document update.
540 Cache.log.debug("Updating jalview from changed vamsas document.");
544 long time = System.currentTimeMillis();
545 IClientDocument cdoc = vclient.getClientDocument();
546 if (Cache.log.isDebugEnabled())
548 Cache.log.debug("Time taken to get ClientDocument = "
549 + (System.currentTimeMillis() - time));
550 time = System.currentTimeMillis();
554 this.updateVamsasDocument(cdoc);
555 if (Cache.log.isDebugEnabled())
558 .debug("Time taken to update Vamsas Document from jalview\t= "
559 + (System.currentTimeMillis() - time));
560 time = System.currentTimeMillis();
562 cdoc.setVamsasRoots(cdoc.getVamsasRoots());
563 if (Cache.log.isDebugEnabled())
565 Cache.log.debug("Time taken to set Document Roots\t\t= "
566 + (System.currentTimeMillis() - time));
567 time = System.currentTimeMillis();
573 if (Cache.log.isDebugEnabled())
576 .debug("Time taken to update Jalview from vamsas document Roots\t= "
577 + (System.currentTimeMillis() - time));
578 time = System.currentTimeMillis();
582 vclient.updateDocument(cdoc);
583 if (Cache.log.isDebugEnabled())
585 Cache.log.debug("Time taken to update Session Document\t= "
586 + (System.currentTimeMillis() - time));
587 time = System.currentTimeMillis();
590 } catch (Exception ee)
592 System.err.println("Exception whilst updating :");
593 ee.printStackTrace(System.err);
594 // recover object map backup, since its probably corrupted with references
595 // to Vobjects that don't exist anymore.
596 this.recover_objectMappingBackup();
598 Cache.log.debug("Finished updating from document change.");
602 private void addDocumentUpdateHandler()
604 final VamsasApplication client = this;
605 vclient.addDocumentUpdateHandler(new PropertyChangeListener()
607 public void propertyChange(PropertyChangeEvent evt)
609 Cache.log.debug("Dealing with document update event.");
610 client.dealWithDocumentUpdate(false);
611 Cache.log.debug("finished dealing with event.");
614 Cache.log.debug("Added Jalview handler for vamsas document updates.");
617 private void addStoreDocumentHandler()
619 final VamsasApplication client = this;
620 vclient.addVorbaEventHandler(
621 uk.ac.vamsas.client.Events.DOCUMENT_REQUESTTOCLOSE,
622 new PropertyChangeListener()
624 public void propertyChange(PropertyChangeEvent evt)
626 if (client.promptUser)
629 .debug("Asking user if the vamsas session should be stored.");
630 int reply = JOptionPane
631 .showInternalConfirmDialog(
633 "The current VAMSAS session has unsaved data - do you want to save it ?",
634 "VAMSAS Session Shutdown",
635 JOptionPane.YES_NO_OPTION,
636 JOptionPane.QUESTION_MESSAGE);
638 if (reply == JOptionPane.YES_OPTION)
640 Cache.log.debug("Prompting for vamsas store filename.");
641 Desktop.instance.vamsasSave_actionPerformed(null);
643 .debug("Finished attempt at storing document.");
646 .debug("finished dealing with REQUESTTOCLOSE event.");
651 .debug("Ignoring store document request (promptUser==false)");
655 Cache.log.debug("Added Jalview handler for vamsas document updates.");
658 public void disableGui(boolean b)
660 Desktop.instance.setVamsasUpdate(b);
663 Hashtable _backup_vobj2jv;
665 IdentityHashMap _backup_jv2vobj;
668 * make a backup of the object mappings (vobj2jv and jv2vobj)
670 public void backup_objectMapping()
672 _backup_vobj2jv = new Hashtable(vobj2jv);
673 _backup_jv2vobj = new IdentityHashMap(jv2vobj);
677 * recover original object mappings from the object mapping backup if document
681 * if backup_objectMapping was not called.
683 public void recover_objectMappingBackup()
685 if (_backup_vobj2jv == null)
688 "IMPLEMENTATION ERROR: Cannot recover vamsas object mappings - no backup was made.");
691 Iterator el = _backup_jv2vobj.entrySet().iterator();
694 java.util.Map.Entry mp = (java.util.Map.Entry) el.next();
695 jv2vobj.put(mp.getKey(), mp.getValue());
697 el = _backup_vobj2jv.entrySet().iterator();
700 java.util.Map.Entry mp = (java.util.Map.Entry) el.next();
701 vobj2jv.put(mp.getKey(), mp.getValue());
705 private boolean joinedSession = false;
707 private VamsasListener picker = null;
709 private SelectionListener selecter;
711 private void startSession()
717 vclient.joinSession();
718 joinedSession = true;
719 } catch (Exception e)
722 Cache.log.error("Failed to join vamsas session.", e);
727 final IPickManager pm = vclient.getPickManager();
728 final StructureSelectionManager ssm = StructureSelectionManager
729 .getStructureSelectionManager();
730 final SelectionSource me = this;
731 pm.registerMessageHandler(new IMessageHandler()
735 public void handleMessage(Message message)
739 // we are not in a session yet.
742 if (message instanceof MouseOverMessage)
744 MouseOverMessage mm = (MouseOverMessage) message;
745 String mstring = mm.getVorbaID() + " " + mm.getPosition();
746 if (last != null && mstring.equals(last))
750 // if (Cache.log.isDebugEnabled())
752 // Cache.log.debug("Received MouseOverMessage "+mm.getVorbaID()+"
753 // "+mm.getPosition());
755 Object jvobj = vobj2jv.get(mm.getVorbaID());
756 if (jvobj != null && jvobj instanceof SequenceI)
759 // Cache.log.debug("Handling Mouse over "+mm.getVorbaID()+"
760 // bound to "+jvobj+" at "+mm.getPosition());
761 // position is character position in aligned sequence
762 ssm.mouseOverVamsasSequence((SequenceI) jvobj, mm
766 if (message instanceof uk.ac.vamsas.client.picking.SelectionMessage)
768 // we only care about AlignmentSequence selections
769 SelectionMessage sm = (SelectionMessage) message;
771 System.err.println("Received\n" + sm.getRawMessage());
772 Object[] jvobjs = sm.getVorbaIDs() == null ? null
773 : new Object[sm.getVorbaIDs().length];
776 // TODO: rationalise : can only clear a selection over a
777 // referred to object
778 ssm.sendSelection(null, null, me);
783 for (int o = 0; o < jvobjs.length; o++)
785 jvobjs[o] = vobj2jv.get(sm.getVorbaIDs()[o]);
786 if (jvobjs[o] == null)
788 // can't cope with selections for unmapped objects
793 type = jvobjs[o].getClass();
796 if (type != jvobjs[o].getClass())
799 // discard - can't cope with selections over mixed objects
803 SequenceGroup jselection = null;
804 ColumnSelection colsel = null;
805 if (type == jalview.datamodel.Alignment.class)
807 if (jvobjs.length == 1)
809 // TODO if (sm.isNone())// send a message to select the
810 // specified columns over the
817 if (type == jalview.datamodel.Sequence.class)
821 boolean aligned = ((jalview.datamodel.Sequence) jvobjs[0])
822 .getDatasetSequence() != null;
826 jselection = new SequenceGroup();
827 jselection.addSequence(
828 seq = (jalview.datamodel.Sequence) jvobjs[0],
830 maxWidth = seq.getLength();
832 for (int c = 1; aligned && jvobjs.length > 1
833 && c < jvobjs.length; c++)
835 if (((jalview.datamodel.Sequence) jvobjs[c])
836 .getDatasetSequence() == null)
843 jselection.addSequence(
844 seq = (jalview.datamodel.Sequence) jvobjs[c],
846 if (maxWidth < seq.getLength())
848 maxWidth = seq.getLength();
856 // if cardinality is greater than one then verify all
857 // sequences are alignment sequences.
858 if (jvobjs.length == 1)
860 // find all instances of this dataset sequence in the
861 // displayed alignments containing the associated range and
867 jselection.setStartRes(0);
868 jselection.setEndRes(maxWidth);
869 // locate the alignment containing the given sequences and
870 // select the associated ranges on them.
871 if (sm.getRanges() != null)
873 int[] prange = uk.ac.vamsas.objects.utils.Range
874 .getBounds(sm.getRanges());
875 boolean rangeset = false;
876 colsel = new ColumnSelection();
877 prange = uk.ac.vamsas.objects.utils.Range
878 .getIntervals(sm.getRanges());
879 for (int p = 0; p < prange.length; p += 2)
881 int d = (prange[p] <= prange[p + 1]) ? 1 : -1;
884 if (jselection != null)
886 // set the bounds of the selected area using the first
888 jselection.setStartRes(prange[p] - 1);
889 jselection.setEndRes(prange[p + 1] - 1);
895 // try to join up adjacent columns to make a larger
897 // lower and upper bounds
898 int l = (d < 0) ? 1 : 0;
899 int u = (d > 0) ? 1 : 0;
901 if (jselection.getStartRes() > 0
902 && prange[p + l] == jselection
905 jselection.setStartRes(prange[p + l] - 1);
907 if (jselection.getEndRes() <= maxWidth
908 && prange[p + u] == (jselection.getEndRes() + 2))
910 jselection.setEndRes(prange[p + u] - 1);
913 // mark all the columns in the range.
914 for (int sr = prange[p], er = prange[p + 1], de = er
915 + d; sr != de; sr += d)
917 colsel.addElement(sr - 1);
926 ssm.sendSelection(jselection, colsel, me);
929 for (int c = 0; c < jvobjs.length; c++)
939 picker = new VamsasListener()
941 SequenceI last = null;
945 public void mouseOver(SequenceI seq, int index)
949 if (seq != last || i != index)
951 VorbaId v = (VorbaId) jv2vobj.get(seq);
954 // this should really be a trace message.
955 // Cache.log.debug("Mouse over " + v.getId() + " bound to "
956 // + seq + " at " + index);
959 MouseOverMessage message = new MouseOverMessage(v.getId(),
961 pm.sendMessage(message);
966 selecter = new SelectionListener()
969 public void selection(SequenceGroup seqsel,
970 ColumnSelection colsel, SelectionSource source)
975 .warn("Selection listener still active for dead session.");
981 AlignmentI visal = null;
982 if (source instanceof AlignViewport)
984 visal = ((AlignViewport) source).getAlignment();
986 SelectionMessage sm = null;
987 if ((seqsel == null || seqsel.getSize() == 0)
988 && (colsel == null || colsel.getSelected() == null || colsel
989 .getSelected().size() == 0))
991 if (source instanceof AlignViewport)
993 // the empty selection.
994 sm = new SelectionMessage("jalview", new String[]
995 { ((AlignViewport) source).getSequenceSetId() }, null,
1000 // the empty selection.
1001 sm = new SelectionMessage("jalview", null, null, true);
1006 String[] vobj = new String[seqsel.getSize()];
1008 Enumeration sels = seqsel.getSequences(null).elements();
1009 while (sels.hasMoreElements())
1011 SequenceI sel = (SequenceI) sels.nextElement();
1012 VorbaId v = (VorbaId) jv2vobj.get(sel);
1015 vobj[o++] = v.toString();
1018 if (o < vobj.length)
1021 vobj = new String[o];
1022 System.arraycopy(t, 0, vobj, 0, o);
1026 if (seqsel != null && colsel != null)
1028 // deparse the colsel into positions on the vamsas alignment
1030 range = new Input();
1031 if (colsel.getSelected() != null
1032 && colsel.getSelected().size() > 0
1034 && seqsel.getSize() == visal.getHeight())
1036 // gather selected columns outwith the sequence positions
1038 Enumeration cols = colsel.getSelected().elements();
1039 while (cols.hasMoreElements())
1041 int ival = ((Integer) cols.nextElement()).intValue();
1049 int[] intervals = colsel.getVisibleContigs(seqsel
1050 .getStartRes(), seqsel.getEndRes() + 1);
1051 for (int iv = 0; iv < intervals.length; iv += 2)
1054 s.setStart(intervals[iv] + 1); // vamsas indices begin at
1056 s.setEnd(intervals[iv + 1] + 1);
1057 s.setInclusive(true);
1062 if (vobj.length > 0)
1064 sm = new SelectionMessage("jalview", vobj, range);
1073 sm.validate(); // debug
1074 Cache.log.debug("Selection Message\n" + sm.getRawMessage());
1081 ssm.addStructureViewerListener(picker); // better method here
1082 ssm.addSelectionListener(selecter);
1083 } catch (Exception e)
1085 Cache.log.error("Failed to init Vamsas Picking", e);
1090 public String getCurrentSession()
1092 if (vclient != null)
1094 return (vclient.getSessionUrn());