Warning: Can't use blame annotator:
svn blame failed on trunk/src/scriptbuilder/structures/SimulationScript.java: ("Can't find a temporary directory: Internal error", 20014)

source: tmcsimulator-scriptbuilder/trunk/src/scriptbuilder/structures/SimulationScript.java @ 169

Revision 169, 11.9 KB checked in by sdanthin, 6 years ago (diff)

SimulationScript?.java modified to use correct names for both imported and created I_AudioEvents

RevLine 
1package scriptbuilder.structures;
2
3import java.awt.Color;
4import java.io.BufferedWriter;
5import java.io.File;
6import java.io.FileWriter;
7import java.io.IOException;
8import java.util.ArrayList;
9import java.util.List;
10import java.util.Observable;
11import java.util.Vector;
12import javax.xml.parsers.SAXParserFactory;
13import scriptbuilder.structures.ScriptIncident.IncidentFocusedEvent;
14import scriptbuilder.structures.ScriptIncident.SliceChangedEvent;
15import scriptbuilder.structures.events.*;
16import scriptbuilder.structures.units.Unit;
17import java.nio.file.Path;
18import java.nio.file.Paths;
19import java.util.TreeMap;
20
21/**
22 * Representation of the script to be run by the TMC Simulator. Holds a list of
23 * incidents, which have start and end times and contain events.
24 *
25 * @author Greg Eddington <geddingt@calpoly.edu>
26 *
27 * @author Bryan McGuffin <bmcguffi@calpoly.edu>
28 * @author Sebastien Danthinne <sdanthin@calpoly.edu>
29 * @version 2017/06/22
30 */
31public class SimulationScript extends Observable implements I_XML_Writable
32{
33
34    /**
35     * All default options for GUI colorings of incidents.
36     */
37    public static final Color[] incidentColors =
38    {
39        Color.BLACK,
40        Color.BLUE,
41        Color.RED,
42        new Color(0x38, 0x5E, 0x0F),
43        new Color(128, 0, 128),
44        Color.MAGENTA,
45        new Color(0x23, 0x6B, 0x8E),
46        Color.ORANGE,
47        new Color(0x60, 0x33, 0x11),
48        Color.GRAY
49    };
50
51    /**
52     * The file to which this script will be saved.
53     */
54    public File saveFile = null;
55
56    /**
57     * The name of this script.
58     */
59    public String title = "";
60
61    /**
62     * The incidents displayed by the GUI.
63     */
64    public List<ScriptIncident> incidents;
65
66    /**
67     * The units which participate in Unit events.
68     */
69    public List<Unit> units; 
70
71    //Somewhere in the code, something assumes that the list of incidents
72    //contains exactly 10 items. Until I can find and un-break that, this will do.
73    //todo: this incident fill count error
74    private final int INCIDENT_FILL_COUNT = 10;
75
76    /**
77     * Number of incidents currently displayed.
78     */
79    public int numberOfIncidents;
80
81    /**
82     * Script handler for parsing incoming XML files.
83     */
84    private MyScriptHandler sh;
85   
86    public boolean saved;
87   
88    //TODO: Pretty much everything in this constructor is dummy data.
89    //Replace all of it.
90    /**
91     * Constructor. Backfill incident list with null objects, to be replaced
92     * later.
93     */
94    public SimulationScript()
95    {
96        sh = new MyScriptHandler(this);
97        incidents = new ArrayList<ScriptIncident>();
98        units = new ArrayList<Unit>();
99        numberOfIncidents = 0;
100        saved = true;
101
102        //Backfill with null incidents
103        for (int i = numberOfIncidents; i < INCIDENT_FILL_COUNT; i++)
104        {
105            incidents.add(null);
106        }
107    }
108   
109    /**
110     * checks and sees if this object has the unit passed.
111     * @param unitID
112     * @return does this SimulationScript have unitnum?
113     */
114    public boolean hasUnit(String unitID){
115        boolean indicator = false;
116        if(units.size()!=0){
117            for(Unit u : units){
118               if(unitID.equals(u.UnitNum)){
119                   indicator = true;
120               }
121            }
122        }
123           
124        return indicator;
125    }
126    /**
127     * creates a dummy unit that only has unit number
128     * @param unitNum
129     */
130    public void addDummyUnit(String unitNum){
131        Unit dummy = new Unit();
132        dummy.UnitNum = unitNum;
133        units.add(dummy);
134    }
135    /**
136     * Update the script's observers.
137     *
138     */
139    public void update()
140    {
141        // The script has changed, notify observers
142        //use to rewrite the save indicator
143        //System.out.println("Script changed");
144        setChanged();
145        notifyObservers(this);
146        saved = false;
147       
148       
149    }
150   
151
152    /**
153     * Tell this script's observers that there is a new slice event.
154     *
155     * @param e the slice focus event
156     */
157    public void broadcastEvent(SliceChangedEvent e)
158    {
159        // The slice focus has changed; pass the message
160        setChanged();
161        notifyObservers(e);
162    }
163
164    /**
165     * Tell this script's observers that there is a new slice event.
166     *
167     * @param e the incident focus event
168     */
169    public void broadcastEvent(IncidentFocusedEvent e)
170    {
171        // The slice focus has changed; pass the message
172        setChanged();
173        notifyObservers(e);
174    }
175
176    /**
177     * Load in an existing script from an XML file.
178     *
179     * @param f the file containing the script
180     */
181    public void loadScriptFromFile(File f)
182    {
183        try
184        {
185
186            SAXParserFactory.newInstance().newSAXParser().parse(f, sh);
187
188            Vector<ScriptIncident> inc = sh.getIncidents();
189            units = sh.getUnits();
190            for (ScriptIncident sci : inc)
191            {
192                addIncident(sci);
193            }
194        }
195        catch (Exception ex)
196        {
197            System.out.println("ERROR LOADING SCRIPT");
198            ex.printStackTrace();
199        }
200        System.out.println("H");
201        for(Unit testUnit : units){
202            System.out.println(testUnit.toXML());
203        }
204        this.update();
205    }
206   
207    /**
208     * Load in an existing list of units from an XML file.
209     * @param inStream the input stream for the file containing the units
210     */
211    public void loadUnitsFromFile(java.io.InputStream inStream){
212        try
213        {
214            SAXParserFactory.newInstance().newSAXParser().parse(inStream, sh);
215            units.addAll(sh.getUnits());
216        }
217        catch (Exception ex)
218        {
219            System.out.println("ERROR LOADING UNITS");
220            ex.printStackTrace();
221        }
222        this.update();
223    }
224
225    /**
226     * Add a new incident to the script.
227     *
228     * @param sci the incident to be added.
229     * @return true if there was enough room to add this incident.
230     */
231    public boolean addIncident(ScriptIncident sci)
232    {
233        if (numberOfIncidents < INCIDENT_FILL_COUNT)
234        {
235            incidents.set(numberOfIncidents++, sci);
236            return true;
237        }
238        return false;
239    }
240
241    /**
242     * Write this script, in proper XML format, to the file in question.
243     *
244     * @param f the destination savefile to be written.
245     */
246    public void saveScriptToFile(File f)
247    {
248        try
249        {
250            f.createNewFile();
251
252            BufferedWriter bw = new BufferedWriter(new FileWriter(f));
253            bw.write(this.toXML());
254            bw.flush();
255            bw.close();
256
257        }
258        catch (Exception ex)
259        {
260            System.out.println("ERROR SAVING SCRIPT");
261            ex.printStackTrace();
262        }
263        try
264        {
265            createAudioDirectory(Paths.get(f.getCanonicalPath()).getParent());
266        }
267        catch(IOException ex)
268        {
269            System.err.println("there was a problem creating the audio directories.");
270        }
271       
272       
273        saved = true;
274    }
275   
276    /**
277     * Creates the proper audio directory using the I_AudioEvent types.
278     * @param path of audio directory root
279     */
280    private void createAudioDirectory(Path path){
281        File f = new File(path.toString()+"/audio");
282        if(!f.exists())
283        {
284            f.mkdir();
285            //scan through to see what is already there and if there is no existing audio directory, create it.
286        }
287        for(ScriptIncident i : incidents)
288        {
289            if(i!=null)
290            {
291                String name = ((Integer) i.number).toString();
292                File incidentFolder = new File(path.toString()+"/audio/"+name);
293                if(!incidentFolder.exists())
294                {
295                    //create an incidentfolder since one does not already exist
296                    incidentFolder.mkdir();
297                }
298
299               
300                for(TimeSlice slice : i.getSlices())
301                {
302                    for(I_ScriptEvent event : slice.events)
303                    {
304                        if(event instanceof I_AudioEvent)
305                        {
306                            //if the event is a chp radio event
307                            //then add the dummy file to the subdirectory created
308                            //CURRENTLY this ONLY is implemented for CHPRadioEvent, so it will need to be changed later.
309                            CHPRadioEvent radioEvent = (CHPRadioEvent) event;
310
311                            String output = radioEvent.toScriptFile();
312                            //optimally, this line should use the ID, but to account for files being read in, it needs to be the radiofile name
313                            File newAudioScript = new File(path.toString()+"/audio/"+name+"/"+radioEvent.radioFile.replaceAll(".mp3","")+".txt");
314                           
315                            try
316                            {
317                                newAudioScript.createNewFile();
318                                BufferedWriter bw = new BufferedWriter(new FileWriter(newAudioScript));
319                                bw.write(output);
320                                bw.flush();
321                                bw.close();
322                            }catch(Exception e)
323                            {
324                                System.err.println("there was a problem creating your text files");
325                            }
326
327                        }
328                    }
329                }
330
331               
332            }
333
334           
335        }
336       
337       
338    }
339    @Override
340    public String toXML()
341    {
342        ArrayList<TimeSlice> slices = arrangeAllSlices();
343        String output = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
344        output += XMLWriter.internalDTD();
345        output += XMLWriter.openTag(ELEMENT.TMC_SCRIPT.tag + " title=\"" + this.title + "\"");
346
347        if (units.size() > 0)
348        {
349            output += XMLWriter.openTag(ELEMENT.SCRIPT_DATA.tag);
350            for (Unit unit : units)
351            {
352                output += unit.toXML();
353            }
354            output += XMLWriter.closeTag(ELEMENT.SCRIPT_DATA.tag);
355        }
356        for (TimeSlice slice : slices)
357        {
358            output += slice.toXML();
359        }
360        output += XMLWriter.closeTag(ELEMENT.TMC_SCRIPT.tag);
361        return output;
362    }
363
364    /**
365     * Arranges all timeslices in this script in chronological order, then by
366     * incident number.
367     *
368     * @return a list of all timeslices in the simulation script
369     */
370    public ArrayList<TimeSlice> arrangeAllSlices()
371    {
372        ArrayList<TimeSlice> list = new ArrayList<TimeSlice>();
373        int length = absoluteLength();
374
375        for (int i = 0; i < length; i++)
376        {
377            for (ScriptIncident inc : incidents)
378            {
379
380                if (inc != null && inc.slices.get(i) != null)
381                {
382                    list.add(inc.slices.get(i));
383                }
384            }
385        }
386        return list;
387    }
388
389    /**
390     * Gets the total length of the simulation in seconds.
391     *
392     * @return
393     */
394    public int absoluteLength()
395    {
396        int length = 0;
397        for (ScriptIncident inc : incidents)
398        {
399            if (inc != null)
400            {
401                inc.updateLength();
402                int currentLength = inc.length + inc.offset;
403                if (currentLength > length)
404                {
405                    length = currentLength;
406                }
407            }
408        }
409        return length;
410    }
411
412    /**
413     * Counts the number of incidents currently running.
414     *
415     * @return the number of non-null incidents currently in the script. A
416     * number between 0 and INCIDENT_FILL_COUNT, inclusive.
417     */
418    public int incidentCount()
419    {
420        int count = 0;
421        for (ScriptIncident inc : incidents)
422        {
423            if (inc != null)
424            {
425                count++;
426            }
427        }
428        return count;
429    }
430
431}
Note: See TracBrowser for help on using the repository browser.