Back to index

wims  3.65+svn20090927
DataSheetCache.java
Go to the documentation of this file.
00001 /*
00002     WIMSchem Elements: Chemistry molecular diagram drawing tool.
00003     
00004     (c) 2008 Dr. Alex M. Clark
00005     
00006     Released as GNUware, under the Gnu Public License (GPL)
00007     
00008     See www.gnu.org for details.
00009 */
00010 
00011 package WIMSchem.ds;
00012 
00013 import WIMSchem.*;
00014 
00015 import java.io.*;
00016 import java.util.*;
00017 
00018 /*
00019     Caching system for DataSheet instances, which is intended for undo/redo purposes.
00020     
00021     NOTE: current implementation is very inefficient, as it stores a copy of the datasheet for every undo/redo instance.
00022     At some point this should be rewritten to store differences.
00023 */
00024 
00025 public class DataSheetCache
00026 {
00027     private final int MAX_UNDO=10;
00028     private Stack<String> undo=new Stack<String>(),redo=new Stack<String>();
00029     
00030     public DataSheetCache()
00031     {
00032     }
00033         
00034     public boolean CanUndo() {return !undo.empty();}
00035     public boolean CanRedo() {return !redo.empty();}
00036     
00037     /* !! figure something out...
00038     public void NotifySaved() {saveidx=curidx;}
00039     public boolean IsSaved() {return curidx==saveidx;}*/
00040     
00041     public void CacheUndo(DataSheet DS)
00042     {
00043        String str=ToString(DS);
00044        undo.push(str);
00045        while (undo.size()>MAX_UNDO) undo.remove(0);
00046        redo.clear();
00047     }
00048     
00049     public DataSheet PerformUndo(DataSheet Cur)
00050     {
00051        if (undo.empty()) return null;
00052        redo.push(ToString(Cur));
00053        return FromString(undo.pop());
00054     }
00055     
00056     public DataSheet PerformRedo(DataSheet Cur)
00057     {
00058        if (redo.empty()) return null;
00059        undo.push(ToString(Cur));
00060        return FromString(redo.pop());
00061     }
00062     
00063     private String ToString(DataSheet DS)
00064     {
00065        StringWriter sw=new StringWriter();
00066        try {DataSheetStream.WriteXML(new BufferedWriter(sw),DS);}
00067        catch (IOException e) {return null;}
00068        return sw.toString();
00069     }
00070     
00071     private DataSheet FromString(String StrDS)
00072     {
00073        DataSheet ds=null;
00074        try
00075        {
00076            if (DataSheetStream.ExamineIsXMLDS(new BufferedReader(new StringReader(StrDS))))
00077               ds=DataSheetStream.ReadXML(new BufferedReader(new StringReader(StrDS)));
00078        }
00079        catch (IOException e) {e.printStackTrace();}
00080        return ds;
00081     }
00082 }