source: trunk/src/org/expeditee/actions/Simple.java@ 74

Last change on this file since 74 was 74, checked in by ra33, 16 years ago

Fixed bugs... added some more features!!

File size: 78.2 KB
Line 
1package org.expeditee.actions;
2
3import java.awt.Color;
4import java.awt.Point;
5import java.awt.event.InputEvent;
6import java.io.BufferedReader;
7import java.io.InputStreamReader;
8import java.util.ArrayList;
9import java.util.Collection;
10import java.util.LinkedList;
11import java.util.List;
12import java.util.Random;
13
14import org.expeditee.agents.DisplayTree;
15import org.expeditee.agents.WriteTree;
16import org.expeditee.gui.AttributeUtils;
17import org.expeditee.gui.DisplayIO;
18import org.expeditee.gui.Frame;
19import org.expeditee.gui.FrameGraphics;
20import org.expeditee.gui.FrameIO;
21import org.expeditee.gui.FrameKeyboardActions;
22import org.expeditee.gui.FrameMouseActions;
23import org.expeditee.gui.FrameUtils;
24import org.expeditee.io.Conversion;
25import org.expeditee.items.Dot;
26import org.expeditee.items.Item;
27import org.expeditee.items.ItemUtils;
28import org.expeditee.items.Line;
29import org.expeditee.items.Text;
30import org.expeditee.items.Item.SelectedMode;
31import org.expeditee.simple.BelowMinParametreCountException;
32import org.expeditee.simple.Context;
33import org.expeditee.simple.IncorrectParametreCountException;
34import org.expeditee.simple.IncorrectTypeException;
35import org.expeditee.simple.Pointers;
36import org.expeditee.simple.Primitives;
37import org.expeditee.simple.SBoolean;
38import org.expeditee.simple.SCharacter;
39import org.expeditee.simple.SInteger;
40import org.expeditee.simple.SPointer;
41import org.expeditee.simple.SPrimitive;
42import org.expeditee.simple.SReal;
43import org.expeditee.simple.SString;
44import org.expeditee.simple.SVariable;
45import org.expeditee.simple.UnitTestFailedException;
46import org.expeditee.stats.AgentStats;
47import org.expeditee.stats.SessionStats;
48
49public class Simple {
50
51 private static final String DEFAULT_STRING = "$s.";
52
53 private static final String DEFAULT_BOOLEAN = "$b.";
54
55 private static final String DEFAULT_CHAR = "$c.";
56
57 private static final String DEFAULT_INTEGER = "$i.";
58
59 private static final String DEFAULT_REAL = "$r.";
60
61 private static final String DEFAULT_ITEM = "$ip.";
62
63 private static final String DEFAULT_FRAME = "$fp.";
64
65 private static final String EXIT_TEXT = "exitall";
66
67 private static enum Status {
68 Exit, OK, Break, Continue, Return, TrueIf, FalseIf;
69 };
70
71 private static final String BREAK2_TEXT = "exitrepeat";
72
73 private static final String BREAK_TEXT = "break";
74
75 private static final String CONTINUE2_TEXT = "nextrepeat";
76
77 private static final String CONTINUE_TEXT = "continue";
78
79 private static final String RETURN_TEXT = "return";
80
81 private static final String LOOP_TEXT = "repeat";
82
83 private static final String TOKEN_SEPARATOR = " +";
84
85 private static final String RUN_FRAME_ACTION = "RunFrame";
86
87 /**
88 * Keeps track of how many simple programs are running. Used to check if
89 * simple should read in keyboard input. Or if the keyboard input should be
90 * handled normally by Expeditee.
91 */
92 private static int _programsRunning = 0;
93
94 /**
95 * This flag is set to true if Simple should hijack keyboard input from
96 * Expeditee
97 */
98 private static boolean _acceptKeyboardInput = false;
99
100 public static void ProgramFinished() {
101 _programsRunning--;
102 }
103
104 private static LinkedList<Character> _KeyStrokes = new LinkedList<Character>();
105
106 public static void KeyStroke(char c) {
107 _KeyStrokes.add(c);
108 }
109
110 public static boolean isProgramRunning() {
111 return _programsRunning > 0;
112 }
113
114 public static boolean acceptKeyboardInput() {
115 return _acceptKeyboardInput && _programsRunning > 0;
116 }
117
118 public static void NewSimpleTest() {
119 Frame newSimpleTest = FrameIO.CreateFrame(DisplayIO.getCurrentFrame()
120 .getFramesetName(), "Test", null);
121 List<String> actions = new ArrayList<String>();
122 actions.add(RUN_FRAME_ACTION);
123 newSimpleTest.getTitle().setActions(actions);
124 FrameUtils.DisplayFrame(newSimpleTest, true);
125 FrameGraphics.DisplayMessage("New test created");
126 }
127
128 public static void NextTest() {
129 Frame next = DisplayIO.getCurrentFrame();
130 do {
131 next = FrameIO.LoadNext(next);
132 } while (next != null
133 && (next.getTitle() == null || !RUN_FRAME_ACTION
134 .equalsIgnoreCase(next.getTitle().getFirstAction())));
135 FrameUtils.DisplayFrame(next, true);
136 }
137
138 public static void PreviousTest() {
139 Frame prev = DisplayIO.getCurrentFrame();
140 do {
141 prev = FrameIO.LoadPrevious(prev);
142 } while (prev != null
143 && (prev.getTitle() == null || !RUN_FRAME_ACTION
144 .equalsIgnoreCase(prev.getTitle().getFirstAction())));
145
146 FrameUtils.DisplayFrame(prev, true);
147 }
148
149 public static void LastTest() {
150 Frame next = FrameIO.LoadLast();
151 Frame lastTest = null;
152 do {
153 // check if its a test frame
154 if (next != null
155 && next.getTitle() != null
156 && RUN_FRAME_ACTION.equalsIgnoreCase(next.getTitle()
157 .getFirstAction())) {
158 lastTest = next;
159 break;
160 }
161
162 next = FrameIO.LoadPrevious(next);
163 } while (next != null);
164
165 FrameUtils.DisplayFrame(lastTest, true);
166 }
167
168 public static void RunSimpleTests(String frameset) {
169 RunSimpleTests(frameset, false);
170 }
171
172 public static void RunSimpleTestsVerbose(String frameset) {
173 RunSimpleTests(frameset, true);
174 }
175
176 public static void RunSimpleTests(String frameset, boolean verbose) {
177 int testsPassed = 0;
178 int testsFailed = 0;
179
180 FrameIO.SaveFrame(DisplayIO.getCurrentFrame(), false);
181 FrameGraphics.DisplayMessage("Starting test suite: " + frameset,
182 Color.CYAN);
183
184 // Get the next number in the inf file for the frameset
185 int lastFrameNo = FrameIO.getLastNumber(frameset);
186
187 // Loop through all the valid frames in the frameset
188 for (int i = 1; i <= lastFrameNo; i++) {
189 String nextFrameName = frameset + i;
190 Frame nextFrame = FrameIO.LoadFrame(nextFrameName);
191 if (nextFrame == null)
192 continue;
193 Text frameTitle = nextFrame.getTitle();
194 if (frameTitle == null)
195 continue;
196 // Run the frames with the RunFrame action on the title
197 Text title = frameTitle.copy();
198 List<String> actions = title.getAction();
199 if (actions == null || title.isAnnotation())
200 continue;
201 if (actions.get(0).toLowerCase().equals("runframe")) {
202 try {
203 title.setLink(nextFrameName);
204 // TODO add the ability to run a setup frame
205 // which sets up variables to be used in all
206 // tests
207 AgentStats.reset();
208 _KeyStrokes.clear();
209 _programsRunning++;
210 RunFrameAndReportError(title, new Context());
211 _programsRunning--;
212 if (verbose)
213 FrameGraphics.DisplayMessage("Test passed: "
214 + title.toString(), Item.GREEN);
215 testsPassed++;
216 } catch (Exception e) {
217 testsFailed++;
218 _programsRunning--;
219 // Print out the reason for failed tests
220 FrameGraphics.LinkedErrorMessage(e.getMessage());
221 }
222 }
223 }
224 // The statement below assumes there are no other programs running at
225 // the same time
226 assert (_programsRunning == 0);
227 // Report the number of test passed and failed
228 FrameGraphics.DisplayMessage("Total tests: "
229 + (testsPassed + testsFailed), Color.CYAN);
230 if (testsPassed > 0)
231 FrameGraphics.DisplayMessage("Passed: " + testsPassed, Item.GREEN);
232 if (testsFailed > 0)
233 FrameGraphics.DisplayMessage("Failed: " + testsFailed, Color.RED);
234 // Remove items from the cursor...
235 Frame.FreeItems.clear();
236 }
237
238 public static void RunFrame(Item current) {
239 RunFrame(current, false);
240 }
241
242 public static void RunFrame(Item current, boolean acceptKeyboardInput) {
243 try {
244 _acceptKeyboardInput = acceptKeyboardInput;
245 FrameIO.SaveFrame(DisplayIO.getCurrentFrame(), true);
246
247 // an item without a link signals to run the current frame
248 if (current.getLink() == null) {
249 current = current.copy();
250 current.setLink(DisplayIO.getCurrentFrame().getFrameName());
251 }
252
253 _KeyStrokes.clear();
254
255 _programsRunning++;
256 Thread t = new Thread(current);
257 t.setPriority(Thread.MIN_PRIORITY);
258 t.start();
259 // _programsRunning--;
260 } catch (Exception e) {
261 // _programsRunning--;
262 }
263 }
264
265 private static void FlagError(Item item) {
266 FrameUtils.DisplayFrame(item.getParent().getFrameName(), true);
267 item.setSelectedMode(SelectedMode.Normal);
268 item.setSelectionColor(Color.CYAN);
269 FrameIO.SaveFrame(item.getParent());
270 }
271
272 /**
273 * Runs a simple code begining on a frame linked to by the specified item
274 * parametre.
275 *
276 * @param current
277 * the item that is linked to the frame to be run.
278 */
279 public static Status RunFrameAndReportError(Item current, Context context)
280 throws Exception {
281 // the item must link to a frame
282 if (current.getLink() == null) {
283 throw new Exception("Could not run unlinked item: "
284 + current.toString());
285 }
286
287 Frame child = FrameIO.LoadFrame(current.getAbsoluteLink());
288 AgentStats.FrameExecuted();
289
290 // if the frame could not be loaded
291 if (child == null) {
292 throw new Exception("Could not load item link: "
293 + current.toString());
294 }
295
296 // loop through non-title, non-name, non-annotation text items
297 List<Item> body = child.getItems();
298 Text item = null;
299 Status lastItemStatus = Status.OK;
300 for (Item i : body)
301 // Ignore items that arent statements
302 if (isStatement(i)) {
303 item = (Text) i;
304 AgentStats.ItemExecuted();
305 try {
306
307 lastItemStatus = RunItem(item, context, lastItemStatus);
308
309 if (lastItemStatus != Status.OK) {
310 if (lastItemStatus != Status.TrueIf
311 && lastItemStatus != Status.FalseIf) {
312 return lastItemStatus;
313 }
314 }
315 } catch (ArrayIndexOutOfBoundsException e) {
316 FlagError(item);
317 throw new Exception("Too few parametres: "
318 + item.toString());
319 } catch (NullPointerException e) {
320 FlagError(item);
321 throw new Exception("Null pointer exception: "
322 + item.toString());
323 } catch (RuntimeException e) {
324 FlagError(item);
325 throw new Exception(e.getMessage() + " " + item.toString());
326 } catch (Exception e) {
327 throw new Exception(e.getMessage());
328 }
329 }
330
331 // if no item was found
332 if (item == null)
333 throw new Exception("No code to be executed: " + current.toString());
334
335 return Status.OK;
336 }
337
338 private static boolean isStatement(Item i) {
339 if (!(i instanceof Text))
340 return false;
341
342 Frame frame = i.getParent();
343
344 if (i == frame.getTitle() || i == frame.getFrameNameItem()
345 || i.isAnnotation()) {
346 return false;
347 }
348
349 return true;
350 }
351
352 /**
353 * This method should be modified to parse strings correctly
354 *
355 * @param statement
356 * @return
357 */
358 private static String[] parseStatement(Text code) throws Exception {
359 String statement = code.getTextNoList();
360 ArrayList<String> tokens = new ArrayList<String>();
361
362 for (int i = 0; i < statement.length(); i++) {
363 char c = statement.charAt(i);
364 // ignore spaces
365 if (c != ' ') {
366 int startOfToken = i;
367 if (c == '\"') {
368 int endOfToken = statement.length() - 1;
369 // find the end of the string literal
370 while (statement.charAt(endOfToken) != '\"')
371 endOfToken--;
372 if (endOfToken > startOfToken) {
373 tokens.add(statement.substring(startOfToken,
374 endOfToken + 1));
375 } else {
376 throw new RuntimeException("Expected matching \" ");
377 }
378 break;
379 } else if (c == '#' || c == '/') {
380 break;
381 } else {
382 // read in a normal token
383 while (++i < statement.length()
384 && statement.charAt(i) != ' ')
385 ;
386 tokens.add(statement.substring(startOfToken, i)
387 .toLowerCase());
388 }
389 }
390 }
391
392 String[] a = new String[tokens.size()];
393 a = tokens.toArray(a);
394 code.setProcessedCode(a);
395 return a;
396 }
397
398 /**
399 * Runs a SIMPLE procedure statement.
400 *
401 * @param tokens
402 * the parsed Call statement.
403 * @param code
404 * the expeditee item containing the procedure call and the link
405 * to the frame with the procedure code.
406 * @param context
407 * the current context from which the procedure call is being
408 * made.
409 * @throws Exception
410 * when errors occur in running the procedure.
411 */
412 private static Status Call(String[] tokens, Text code, Context context)
413 throws Exception {
414 // Check that the call statement is linked
415 if (code.getLink() == null)
416 throw new Exception("Unlinked call statement: " + code.toString());
417
418 Frame procedure = FrameIO.LoadFrame(code.getAbsoluteLink());
419
420 // Add call to the start of the title if it doesnt exist
421 // This makes the call and signature tokens counts match
422 String procedureTitle = procedure.getTitle().getFirstLine();
423 if (!procedureTitle.toLowerCase().startsWith("call "))
424 procedureTitle = "call " + procedureTitle;
425
426 // Check that the calling statement matches the procedure
427 // signature
428 String[] procedureSignature = procedureTitle.split(TOKEN_SEPARATOR);
429
430 // Check for the right amount of parametres
431 if (procedureSignature.length < tokens.length)
432 throw new Exception("Call statement has too many parametres: "
433 + code.toString());
434 else if (procedureSignature.length > tokens.length)
435 throw new Exception("Call statement has too few parametres: "
436 + code.toString());
437 // else if (procedureSignature[1].equals(tokens[1]))
438 // throw new Exception("Call statement and procedure name dont match: "
439 // + code.toString());
440
441 // create the new context for the sub procedure
442 Context newContext = new Context();
443 // Check that the types/prefixes match
444 for (int i = 2; i < tokens.length; i++) {
445 // TODO allow for auto casting of primitives
446 if (tokens[i].substring(1, 2).equals(
447 procedureSignature[i].substring(1, 2))) {
448 // Add the variables to the new context
449 if (Primitives.isPrimitive(tokens[i])) {
450 try {
451 // try and get the value for the variable
452 SPrimitive p = context.getPrimitives().getVariable(
453 tokens[i]);
454 newContext.getPrimitives()
455 .add(procedureSignature[i], p);
456 } catch (Exception e) {
457 // If an exception occurs the variable doesnt
458 // exist in the current context
459 // So the variable must be added to both context
460 context.getPrimitives().add(tokens[i], new SString(""));
461 newContext.getPrimitives().add(procedureSignature[i],
462 new SString(""));
463 }
464 } else if (Pointers.isPointer(tokens[i])) {
465 try {
466 // try and get the value for the variable
467 SPointer p = context.getPointers().getVariable(
468 tokens[i]);
469 newContext.getPointers().add(procedureSignature[i], p);
470 } catch (Exception e) {
471 // If an exception occurs the variable doesnt
472 // exist in the current context
473 // So the variable must be added to both context
474 context.getPointers().setObject(tokens[i], null);
475 newContext.getPointers().setObject(
476 procedureSignature[i], null);
477 }
478 } else
479 throw new Exception("Unrecognised variable type: "
480 + tokens[i] + " in " + code.toString());
481 } else
482 throw new IncorrectTypeException(procedureSignature[i], i);
483 }
484
485 // Follow the link and Run the code for the procedure
486 Status result = RunFrameAndReportError(code, newContext);
487 // If a return statement ends the procedure then we accept this as
488 // normal execution
489 switch (result) {
490 case Return:
491 result = Status.OK;
492 break;
493 case Break:
494 throw new Exception(BREAK_TEXT + " statement without matching "
495 + LOOP_TEXT + " in " + code.toString());
496 case Continue:
497 throw new Exception("");
498 }
499
500 // Now copy the values from the procedure context into the
501 // current context
502 for (int i = 2; i < tokens.length; i++) {
503 try {
504 if (Primitives.isPrimitive(tokens[i])) {
505 // try and get the value for the variable
506 SVariable p = context.getPrimitives()
507 .getVariable(tokens[i]);
508 SVariable newP = newContext.getPrimitives().getVariable(
509 procedureSignature[i]);
510 p.setValue(newP);
511 } else {
512 // try and get the value for the variable
513 SVariable p = context.getPointers().getVariable(tokens[i]);
514 SVariable newP = newContext.getPointers().getVariable(
515 procedureSignature[i]);
516 p.setValue(newP);
517 }
518 } catch (Exception e) {
519 assert (false);
520 }
521 }
522
523 return result;
524 }
525
526 /**
527 * Runs a text item on a frame as a SIMPLE statement. The statement is
528 * parsed and if it is a recognised SIMPLE keyword or procedure the code is
529 * executed.
530 *
531 * @param code
532 * the item containing the code to be executed.
533 * @param context
534 * @return
535 * @throws Exception
536 */
537 private static Status RunItem(Text code, Context context,
538 Status lastItemStatus) throws Exception {
539
540 String[] tokens = code.getProcessedCode();
541
542 if (tokens == null) {
543 tokens = parseStatement(code);
544 }
545
546 // Comments without links are a no-op
547 if (tokens.length == 0) {
548 if (code.getLink() == null)
549 return Status.OK;
550 else
551 return RunFrameAndReportError(code, context);
552 }
553
554 // At present only set statements can have literals so they
555 // are the only statements that we have to worry about string
556 // literals
557 if (tokens[0].equals("call") && tokens.length >= 2) {
558 return Call(tokens, code, context);
559 // Check if the user wants to display a message
560 // Check for set statements
561 } else if (tokens[0].startsWith("set")) {
562 if (tokens[0].equals("set")) {
563 try {
564 // Check if we are setting variable to variable
565 if (tokens[2].startsWith(SVariable.prefix)
566 && tokens.length == 3) {
567 context.getPrimitives().set(tokens[1], tokens[2]);
568 return Status.OK;
569 }
570 // Otherwise we are setting a variable with a literal
571 else {
572 // check for strings enclosed in quotes
573 if (tokens[2].startsWith("\"")) {
574 context.getPrimitives().setValue(
575 tokens[1],
576 new SString(tokens[2].substring(1,
577 tokens[2].length() - 1)));
578 return Status.OK;
579
580 // set a literal
581 } else if (tokens.length == 3) {
582 context.getPrimitives().setValue(tokens[1],
583 tokens[2]);
584 return Status.OK;
585 }
586 }
587 } catch (Exception e) {
588 throw new RuntimeException(e.getMessage());
589 }
590 } else if (tokens[0].equals("setframevalue")) {
591 assertMinParametreCount(tokens, 3);
592 assertVariableType(tokens[1], 1, SPointer.framePrefix);
593
594 // Get the attribute to be searched for on the target frame
595 Frame targetFrame = (Frame) context.getPointers().getVariable(
596 tokens[1]).getValue();
597 String targetAttribute = context.getPrimitives()
598 .getStringValue(tokens[2]).toLowerCase()
599 + ":";
600 String value = context.getPrimitives()
601 .getStringValue(tokens[3]);
602 Boolean found = false;
603 Text attributeItem = null;
604 Text valueItem = null;
605 // Begin the search
606 for (Text text : targetFrame.getBodyTextItems(true)) {
607 String s = text.getTextNoList().toLowerCase();
608
609 if (s.startsWith(targetAttribute)) {
610 attributeItem = text;
611 AttributeUtils.setSingleValue(attributeItem, value);
612 found = true;
613 break;
614 }
615 }
616 // Keep looking for a matching value nearby if we found an
617 // attribute without the value in the same item
618 if (!found && attributeItem != null) {
619 Point endPoint = attributeItem.getEndParagraphPosition();
620
621 for (Text text : targetFrame.getBodyTextItems(true)) {
622 Point startPoint = text.getPosition();
623 if (Math.abs(startPoint.y - endPoint.y) < 10
624 && Math.abs(startPoint.x - endPoint.x) < 20) {
625 found = true;
626 valueItem = text;
627 text.setText(value);
628 break;
629 }
630 }
631 }
632
633 // Set the values of the output parametres
634 if (tokens.length > 4) {
635 context.getPrimitives().setValue(tokens[4],
636 new SBoolean(found));
637 if (tokens.length > 5) {
638 context.getPointers().setObject(tokens[5],
639 attributeItem);
640 if (tokens.length > 6) {
641 context.getPointers().setObject(tokens[6],
642 valueItem);
643 }
644 }
645 }
646
647 return Status.OK;
648 } else if (tokens[0].startsWith("setitem")) {
649 if (tokens[0].equals("setitemposition")) {
650 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
651 // assertPrimitiveType(tokens[2], 2);
652 // assertPrimitiveType(tokens[3], 3);
653 Item item = (Item) context.getPointers().getVariable(
654 tokens[1]).getValue();
655 item.setPosition(context.getPrimitives().getVariable(
656 tokens[2]).integerValue().intValue(), context
657 .getPrimitives().getVariable(tokens[3])
658 .integerValue().intValue());
659 } else if (tokens[0].equals("setitemthickness")) {
660 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
661 // assertPrimitiveType(tokens[2], 2);
662 Item item = (Item) context.getPointers().getVariable(
663 tokens[1]).getValue();
664 item.setThickness(context.getPrimitives().getVariable(
665 tokens[2]).integerValue().intValue());
666 } else if (tokens[0].equals("setitemwidth")) {
667 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
668 // assertPrimitiveType(tokens[2], 2);
669 Item item = (Item) context.getPointers().getVariable(
670 tokens[1]).getValue();
671 item.setWidth(context.getPrimitives()
672 .getVariable(tokens[2]).integerValue().intValue());
673 } else if (tokens[0].equals("setitemsize")) {
674 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
675 // assertPrimitiveType(tokens[2], 2);
676 Item item = (Item) context.getPointers().getVariable(
677 tokens[1]).getValue();
678 item.setSize(context.getPrimitives().getVariable(tokens[2])
679 .integerValue().intValue());
680 } else if (tokens[0].equals("setitemlink")) {
681 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
682 // assertPrimitiveType(tokens[2], 2);
683 Item item = (Item) context.getPointers().getVariable(
684 tokens[1]).getValue();
685 item.setLink(context.getPrimitives().getVariable(tokens[2])
686 .stringValue());
687 } else if (tokens[0].equals("setitemdata")) {
688 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
689 // assertPrimitiveType(tokens[2], 2);
690 Item item = (Item) context.getPointers().getVariable(
691 tokens[1]).getValue();
692 item.setData(context.getPrimitives().getVariable(tokens[2])
693 .stringValue());
694 } else if (tokens[0].equals("setitemaction")) {
695 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
696 // assertPrimitiveType(tokens[2], 2);
697 Item item = (Item) context.getPointers().getVariable(
698 tokens[1]).getValue();
699 item.setAction(context.getPrimitives().getVariable(tokens[2])
700 .stringValue());
701 } else if (tokens[0].equals("setitemfillcolor")) {
702 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
703 // assertPrimitiveType(tokens[2], 2);
704 Item item = (Item) context.getPointers().getVariable(
705 tokens[1]).getValue();
706 String stringColor = context.getPrimitives().getVariable(
707 tokens[2]).stringValue();
708 item.setBackgroundColor((Color) Conversion.Convert(
709 Color.class, stringColor));
710 } else if (tokens[0].equals("setitemcolor")) {
711 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
712 // assertPrimitiveType(tokens[2], 2);
713 Item item = (Item) context.getPointers().getVariable(
714 tokens[1]).getValue();
715 String stringColor = context.getPrimitives().getVariable(
716 tokens[2]).stringValue();
717 item.setColor((Color) Conversion.Convert(Color.class,
718 stringColor));
719 } else if (tokens[0].equals("setitemtext")) {
720 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
721 // assertPrimitiveType(tokens[2], 2);
722 String newText = context.getPrimitives().getVariable(
723 tokens[2]).stringValue();
724 Text textItem = (Text) context.getPointers().getVariable(
725 tokens[1]).getValue();
726 textItem.setText(newText);
727 } else
728 throw new Exception("Unsupported setItem command: "
729 + code.toString());
730 return Status.OK;
731 } else if (tokens[0].equals("setstrchar")) {
732 assertExactParametreCount(tokens, 3);
733 StringBuffer s = new StringBuffer(context.getPrimitives()
734 .getStringValue(tokens[1]));
735 int pos = (int) context.getPrimitives().getIntegerValue(
736 tokens[2]);
737 char newChar = context.getPrimitives().getCharacterValue(
738 tokens[3]);
739 while (pos > s.length()) {
740 s.append(newChar);
741 }
742 s.setCharAt(pos - 1, newChar);
743
744 context.getPrimitives().setValue(tokens[1],
745 new SString(s.toString()));
746 return Status.OK;
747 } else if (tokens[0].equals("setcharinitem")) {
748 assertExactParametreCount(tokens, 4);
749 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
750
751 int row = (int) context.getPrimitives().getIntegerValue(
752 tokens[3]) - 1;
753 int col = (int) context.getPrimitives().getIntegerValue(
754 tokens[4]) - 1;
755 char newChar = context.getPrimitives().getCharacterValue(
756 tokens[2]);
757 Text item = (Text) context.getPointers().getVariable(tokens[1])
758 .getValue();
759 List<String> itemText = item.getText();
760
761 while (row >= itemText.size()) {
762 StringBuffer sb = new StringBuffer();
763 for (int i = 0; i <= col; i++)
764 sb.append(newChar);
765 itemText.add(sb.toString());
766 }
767 StringBuffer sb = new StringBuffer(itemText.get(row));
768 while (sb.length() <= col)
769 sb.append(newChar);
770 sb.setCharAt(col, newChar);
771
772 // set the modified string
773 itemText.set(row, sb.toString());
774 item.setTextList(itemText);
775
776 return Status.OK;
777 }
778 } else if (tokens[0].startsWith("assert")) {
779 if (tokens[0].equals("asserttrue")) {
780 assertExactParametreCount(tokens, 1);
781 if (!context.getPrimitives().getBooleanValue(tokens[1]))
782 throw new UnitTestFailedException("true", "false");
783 return Status.OK;
784 } else if (tokens[0].equals("assertfalse")) {
785 assertExactParametreCount(tokens, 1);
786 if (context.getPrimitives().getBooleanValue(tokens[1]))
787 throw new UnitTestFailedException("false", "true");
788 return Status.OK;
789 }
790 if (tokens[0].equals("assertfail")) {
791 assertExactParametreCount(tokens, 0);
792 throw new UnitTestFailedException("pass", "fail");
793 } else if (tokens[0].equals("assertnull")) {
794 assertExactParametreCount(tokens, 1);
795 Object value = context.getPrimitives().getVariable(tokens[1])
796 .getValue();
797 if (value != null)
798 throw new UnitTestFailedException("null", value.toString());
799 return Status.OK;
800 } else if (tokens[0].equals("assertnotnull")) {
801 assertExactParametreCount(tokens, 1);
802 Object value = context.getPrimitives().getVariable(tokens[1])
803 .getValue();
804 if (value == null)
805 throw new UnitTestFailedException("not null", "null");
806 return Status.OK;
807 } else if (tokens[0].equals("assertdefined")) {
808 assertExactParametreCount(tokens, 1);
809 if (!context.isDefined(tokens[1]))
810 throw new UnitTestFailedException("defined", "not defined");
811 return Status.OK;
812 } else if (tokens[0].equals("assertnotdefined")) {
813 assertExactParametreCount(tokens, 1);
814 if (context.isDefined(tokens[1]))
815 throw new UnitTestFailedException("defined", "not defined");
816 return Status.OK;
817 } else if (tokens[0].equals("assertequals")) {
818 assertExactParametreCount(tokens, 2);
819 if (!context.getPrimitives().equalValues(tokens[1], tokens[2]))
820 throw new UnitTestFailedException(context.getPrimitives()
821 .getStringValue(tokens[1]), context.getPrimitives()
822 .getStringValue(tokens[2]));
823 return Status.OK;
824 } else if (tokens[0].equals("assertdefined")) {
825 assertExactParametreCount(tokens, 1);
826 if (!context.isDefined(tokens[1])) {
827 throw new UnitTestFailedException(tokens[1] + " exists",
828 "not defined");
829 }
830 return Status.OK;
831 }
832 } else if (tokens[0].startsWith("goto")) {
833 String frameNameVar = DEFAULT_STRING;
834 if (tokens.length > 1) {
835 assertExactParametreCount(tokens, 1);
836 frameNameVar = tokens[1];
837 }
838 String frameName = context.getPrimitives().getStringValue(
839 frameNameVar);
840 NavigationActions.Goto(frameName);
841 return Status.OK;
842 } else if (tokens[0].startsWith("get")) {
843 if (tokens[0].startsWith("getframe")) {
844 if (tokens[0].equals("getframevalue")) {
845 assertMinParametreCount(tokens, 3);
846 assertVariableType(tokens[1], 1, SPointer.framePrefix);
847
848 // Get the attribute to be searched for on the target frame
849 Frame targetFrame = (Frame) context.getPointers()
850 .getVariable(tokens[1]).getValue();
851 String targetAttribute = context.getPrimitives()
852 .getStringValue(tokens[2]).toLowerCase()
853 + ":";
854 Boolean found = false;
855 String value = "";
856 Text attributeItem = null;
857 Text valueItem = null;
858 // Begin the search
859 for (Text text : targetFrame.getBodyTextItems(true)) {
860 String s = text.getTextNoList().toLowerCase();
861 if (s.startsWith(targetAttribute)) {
862 attributeItem = text;
863 value = AttributeUtils.stripValue(s);
864 if (value.length() > 0) {
865 found = true;
866 }
867 break;
868 }
869 }
870 // Keep looking for a matching value nearby if we found an
871 // attribute without the value in the same item
872 if (!found && attributeItem != null) {
873 Point endPoint = attributeItem
874 .getEndParagraphPosition();
875
876 for (Text text : targetFrame.getBodyTextItems(true)) {
877 Point startPoint = text.getPosition();
878 if (Math.abs(startPoint.y - endPoint.y) < 10
879 && Math.abs(startPoint.x - endPoint.x) < 20) {
880 found = true;
881 valueItem = text;
882 value = text.getTextNoList();
883 break;
884 }
885 }
886 }
887
888 // Set the values of the output parametres
889 context.getPrimitives().setValue(tokens[3],
890 new SString(value));
891 if (tokens.length > 4) {
892 context.getPrimitives().setValue(tokens[4],
893 new SBoolean(found));
894 if (tokens.length > 5) {
895 context.getPointers().setObject(tokens[5],
896 attributeItem);
897 if (tokens.length > 6) {
898 context.getPointers().setObject(tokens[6],
899 valueItem);
900 }
901 }
902 }
903 return Status.OK;
904 } else if (tokens[0].startsWith("getframename")) {
905 String frameNameVar = DEFAULT_STRING;
906 String frameVar = DEFAULT_FRAME;
907
908 if (tokens.length > 1) {
909 assertExactParametreCount(tokens, 2);
910 assertVariableType(tokens[1], 1, SPointer.framePrefix);
911 frameNameVar = tokens[2];
912 frameVar = tokens[1];
913 }
914 Frame frame = (Frame) context.getPointers().getVariable(
915 frameVar).getValue();
916 context.getPrimitives().setValue(frameNameVar,
917 frame.getFrameName());
918 return Status.OK;
919 } else if (tokens[0].startsWith("getframefilepath")) {
920 assertExactParametreCount(tokens, 2);
921 String frameName = context.getPrimitives().getStringValue(
922 tokens[1]);
923 String path = FrameIO.LoadFrame(frameName).path;
924 String filePath = FrameIO.getFrameFullPathName(path,
925 frameName);
926 context.getPrimitives().setValue(tokens[2], filePath);
927 return Status.OK;
928 } else if (tokens[0].equals("getframelog")) {
929 assertExactParametreCount(tokens, 1);
930 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
931
932 String log = SessionStats.getFrameEventList();
933 Text t;
934 // try {
935 t = (Text) context.getPointers().getVariable(tokens[1])
936 .getValue();
937 t.setText(log);
938 // } catch (Exception e) {
939 // t = new Text(-1, log);
940 // context.getPointers().setObject(tokens[1], t);
941 // }
942
943 return Status.OK;
944 }
945 } else if (tokens[0].startsWith("getcurrent")) {
946 if (tokens[0].equals("getcurrentframe")) {
947 assertMinParametreCount(tokens, 1);
948 assertVariableType(tokens[1], 1, SPointer.framePrefix);
949
950 Frame currentFrame = DisplayIO.getCurrentFrame();
951 context.getPointers().setObject(tokens[1], currentFrame);
952
953 // check if the user is also after the frameName
954 if (tokens.length > 2) {
955 context.getPrimitives().setValue(tokens[2],
956 new SString(currentFrame.getFrameName()));
957 }
958 return Status.OK;
959 }
960 } else if (tokens[0].startsWith("getitem")) {
961 if (tokens[0].equals("getitemposition")) {
962 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
963 // assertPrimitiveType(tokens[2], 2);
964 // assertPrimitiveType(tokens[3], 3);
965 Point pos = ((Item) context.getPointers().getVariable(
966 tokens[1]).getValue()).getPosition();
967 Integer x = pos.x;
968 Integer y = pos.y;
969 context.getPrimitives()
970 .setValue(tokens[2], new SInteger(x));
971 context.getPrimitives()
972 .setValue(tokens[3], new SInteger(y));
973 } else if (tokens[0].equals("getitemthickness")) {
974 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
975 // assertPrimitiveType(tokens[2], 2);
976 Float thickness = ((Item) context.getPointers()
977 .getVariable(tokens[1]).getValue()).getThickness();
978 context.getPrimitives().setValue(tokens[2],
979 new SReal(thickness));
980 } else if (tokens[0].equals("getitemwidth")) {
981 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
982 // assertPrimitiveType(tokens[2], 2);
983 Integer width = ((Item) context.getPointers().getVariable(
984 tokens[1]).getValue()).getWidth();
985 context.getPrimitives().setValue(tokens[2],
986 new SInteger(width));
987 } else if (tokens[0].equals("getitemsize")) {
988 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
989 // assertPrimitiveType(tokens[2], 2);
990 Integer size = ((Item) context.getPointers().getVariable(
991 tokens[1]).getValue()).getSize();
992 context.getPrimitives().setValue(tokens[2],
993 new SInteger(size));
994 } else if (tokens[0].equals("getitemlink")) {
995 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
996 // assertPrimitiveType(tokens[2], 2);
997 String link = ((Item) context.getPointers().getVariable(
998 tokens[1]).getValue()).getLink();
999 context.getPrimitives().setValue(tokens[2],
1000 new SString(link));
1001 } else if (tokens[0].equals("getitemdata")) {
1002 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1003 Collection<String> dataList = ((Item) context.getPointers()
1004 .getVariable(tokens[1]).getValue()).getData();
1005 String data = "";
1006 if (dataList.size() > 0)
1007 data = dataList.iterator().next();
1008 context.getPrimitives().setValue(tokens[2],
1009 new SString(data));
1010 } else if (tokens[0].equals("getitemaction")) {
1011 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1012 Collection<String> dataList = ((Item) context.getPointers()
1013 .getVariable(tokens[1]).getValue()).getAction();
1014 String action = "";
1015 if (dataList.size() > 0)
1016 action = dataList.iterator().next();
1017 context.getPrimitives().setValue(tokens[2],
1018 new SString(action));
1019 }else if (tokens[0].equals("getitemfillcolor")) {
1020 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1021 // assertPrimitiveType(tokens[2], 2);
1022 Color itemColor = ((Item) context.getPointers()
1023 .getVariable(tokens[1]).getValue())
1024 .getPaintBackgroundColor();
1025 String color = itemColor.getRed() + " "
1026 + itemColor.getGreen() + " " + itemColor.getBlue();
1027 context.getPrimitives().setValue(tokens[2],
1028 new SString(color));
1029 } else if (tokens[0].equals("getitemcolor")) {
1030 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1031 // assertPrimitiveType(tokens[2], 2);
1032 Color itemColor = ((Item) context.getPointers()
1033 .getVariable(tokens[1]).getValue()).getPaintColor();
1034 String color = itemColor.getRed() + " "
1035 + itemColor.getGreen() + " " + itemColor.getBlue();
1036 context.getPrimitives().setValue(tokens[2],
1037 new SString(color));
1038 } else if (tokens[0].equals("getitemtext")) {
1039 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1040 Item item = ((Item) context.getPointers().getVariable(
1041 tokens[1]).getValue());
1042 context.getPrimitives().setValue(
1043 tokens[2],
1044 new SString((item instanceof Text) ? ((Text) item)
1045 .getTextNoList() : ""));
1046 } else
1047 throw new Exception("Unsupported getItem command: "
1048 + code.toString());
1049
1050 return Status.OK;
1051 } else if (tokens[0].equals("getstrchar")) {
1052 assertExactParametreCount(tokens, 3);
1053 String s = context.getPrimitives().getStringValue(tokens[1]);
1054 int pos = (int) context.getPrimitives().getIntegerValue(
1055 tokens[2]);
1056
1057 context.getPrimitives().setValue(tokens[3],
1058 new SCharacter(s.charAt(pos - 1)));
1059 return Status.OK;
1060 } else if (tokens[0].equals("getstrlength")) {
1061 assertExactParametreCount(tokens, 2);
1062 String s = context.getPrimitives().getStringValue(tokens[1]);
1063
1064 context.getPrimitives().setValue(tokens[2],
1065 new SInteger(s.length()));
1066 return Status.OK;
1067 } else if (tokens[0].equals("getelapsedtime")) {
1068 assertExactParametreCount(tokens, 1);
1069 context.getPrimitives().setValue(tokens[1],
1070 new SInteger(AgentStats.getMilliSecondsElapsed()));
1071 return Status.OK;
1072 } else if (tokens[0].equals("getlastnumberinframeset")) {
1073 String framesetNameVar = DEFAULT_STRING;
1074 String countVar = DEFAULT_INTEGER;
1075 if (tokens.length > 1) {
1076 assertMinParametreCount(tokens, 2);
1077 framesetNameVar = tokens[1];
1078 countVar = tokens[2];
1079 }
1080 String frameset = context.getPrimitives().getStringValue(
1081 framesetNameVar);
1082 long count = FrameIO.getLastNumber(frameset);
1083 context.getPrimitives().setValue(countVar, new SInteger(count));
1084 return Status.OK;
1085 } else if (tokens[0].equals("getlistofframesets")) {
1086 String stringVar = DEFAULT_ITEM;
1087 if (tokens.length > 1) {
1088 assertMinParametreCount(tokens, 1);
1089 stringVar = tokens[1];
1090 }
1091 context.getPrimitives().setValue(stringVar,
1092 FrameIO.getFramesetList());
1093 return Status.OK;
1094 } else if (tokens[0].equals("getsessionstats")) {
1095 assertExactParametreCount(tokens, 1);
1096 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1097
1098 String stats = SessionStats.getCurrentStats();
1099 Text t;
1100 // try {
1101 t = (Text) context.getPointers().getVariable(tokens[1])
1102 .getValue();
1103 t.setText(stats);
1104 // } catch (Exception e) {
1105 // t = new Text(-1, stats);
1106 // context.getPointers().setObject(tokens[1], t);
1107 // }
1108
1109 return Status.OK;
1110 } else if (tokens[0].equals("getrandominteger")) {
1111 assertExactParametreCount(tokens, 3);
1112 int lowerBound = (int) context.getPrimitives().getIntegerValue(
1113 tokens[1]);
1114 int upperBound = (int) context.getPrimitives().getIntegerValue(
1115 tokens[2]);
1116 Random random = new Random();
1117 long result = Math.abs(random.nextInt())
1118 % (upperBound - lowerBound) + lowerBound;
1119 context.getPrimitives().setValue(tokens[3],
1120 new SInteger(result));
1121 return Status.OK;
1122 } else if (tokens[0].equals("getrandomreal")) {
1123 assertExactParametreCount(tokens, 3);
1124 double lowerBound = context.getPrimitives().getDoubleValue(
1125 tokens[1]);
1126 double upperBound = context.getPrimitives().getDoubleValue(
1127 tokens[2]);
1128 Random random = new Random();
1129 double result = random.nextDouble() * (upperBound - lowerBound)
1130 + lowerBound;
1131 context.getPrimitives().setValue(tokens[3], new SReal(result));
1132 return Status.OK;
1133 } else if (tokens[0].equals("getrandomtextitem")) {
1134 assertExactParametreCount(tokens, 2);
1135 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1136 assertVariableType(tokens[2], 2, SPointer.itemPrefix);
1137 List<Text> items = ((Frame) context.getPointers().getVariable(
1138 tokens[1]).getValue()).getBodyTextItems(false);
1139 Random random = new Random();
1140 int itemIndex = random.nextInt(items.size());
1141 context.getPointers()
1142 .setObject(tokens[2], items.get(itemIndex));
1143 return Status.OK;
1144 }
1145 } else if (tokens[0].equals("or")) {
1146 for (int i = 1; i < tokens.length - 1; i++) {
1147 if (Primitives.isPrimitive(tokens[i])) {
1148 if (context.getPrimitives().getBooleanValue(tokens[i])) {
1149 context.getPrimitives().setValue(
1150 tokens[tokens.length - 1], new SBoolean(true));
1151 return Status.OK;
1152 }
1153 }
1154 }
1155 context.getPrimitives().setValue(tokens[tokens.length - 1],
1156 new SBoolean(false));
1157 return Status.OK;
1158 } else if (tokens[0].equals("and")) {
1159 for (int i = 1; i < tokens.length - 1; i++) {
1160 if (Primitives.isPrimitive(tokens[i])) {
1161 if (!context.getPrimitives().getBooleanValue(tokens[i])) {
1162 context.getPrimitives().setValue(
1163 tokens[tokens.length - 1], new SBoolean(false));
1164 return Status.OK;
1165 }
1166 }
1167 }
1168 context.getPrimitives().setValue(tokens[tokens.length - 1],
1169 new SBoolean(true));
1170 return Status.OK;
1171 } else if (tokens[0].equals("messagelnitem")
1172 || tokens[0].equals("messagelineitem")) {
1173 String itemVar = DEFAULT_ITEM;
1174
1175 if (tokens.length > 1) {
1176 assertExactParametreCount(tokens, 1);
1177 itemVar = tokens[1];
1178 assertVariableType(itemVar, 1, SPointer.itemPrefix);
1179 }
1180 Item message = (Item) context.getPointers().getVariable(itemVar)
1181 .getValue();
1182 try {
1183 FrameGraphics.DisplayMessage(((Text) message).copy());
1184 } catch (NullPointerException e) {
1185 FrameGraphics.DisplayMessage("null");
1186 } catch (ClassCastException e) {
1187 // Just ignore not text items!
1188 FrameGraphics.DisplayMessage(message.toString());
1189 } catch (Exception e) {
1190 // Just ignore other errors
1191 }
1192 return Status.OK;
1193 } else if (tokens[0].equals("messageln")
1194 || tokens[0].equals("messageline")
1195 || tokens[0].equals("messagelnnospaces")
1196 || tokens[0].equals("messagelinenospaces")
1197 || tokens[0].equals("errorln") || tokens[0].equals("errorline")) {
1198 String message = getMessage(tokens, context, code.toString(),
1199 tokens[0].endsWith("nospaces") ? "" : " ", 1);
1200
1201 if (tokens[0].equals("errorln") || tokens[0].equals("errorline"))
1202 FrameGraphics.ErrorMessage(message);
1203 else
1204 FrameGraphics.DisplayMessageAlways(message);
1205 return Status.OK;
1206 } else if (tokens[0].equals("typeatrate")) {
1207 assertMinParametreCount(tokens, 1);
1208 double delay = context.getPrimitives().getDoubleValue(tokens[1]);
1209 String s = getMessage(tokens, context, code.toString(), " ", 2);
1210 for (int i = 0; i < s.length(); i++) {
1211 FrameKeyboardActions.processChar(s.charAt(i));
1212 Thread.sleep((int) (delay * 1000));
1213 }
1214 return Status.OK;
1215 } else if (tokens[0].equals("type") || tokens[0].equals("typenospaces")) {
1216
1217 String s = getMessage(tokens, context, code.toString(), tokens[0]
1218 .equals("type") ? " " : "", 1);
1219 for (int i = 0; i < s.length(); i++) {
1220 FrameKeyboardActions.processChar(s.charAt(i));
1221 Thread.sleep(25);
1222 }
1223 return Status.OK;
1224 } else if (tokens[0].equals("runstring")) {
1225 String codeText = getMessage(tokens, context, code.toString(), " ",
1226 1);
1227 Text dynamicCode = new Text(1, codeText);
1228 RunItem(dynamicCode, context, Status.OK);
1229 return Status.OK;
1230 } else if (tokens[0].equals("runoscommand")) {
1231 String command = getMessage(tokens, context, code.toString(), " ",
1232 1);
1233 Runtime.getRuntime().exec(command);
1234 return Status.OK;
1235 } else if (tokens[0].equals("executeoscommand")) {
1236 String command = getMessage(tokens, context, code.toString(), " ",
1237 1);
1238 try {
1239 Process p = Runtime.getRuntime().exec(command);
1240 FrameGraphics.DisplayMessage(command, Color.darkGray);
1241
1242 BufferedReader stdInput = new BufferedReader(
1243 new InputStreamReader(p.getInputStream()));
1244 BufferedReader stdError = new BufferedReader(
1245 new InputStreamReader(p.getErrorStream()));
1246 String message = "";
1247 while ((message = stdInput.readLine()) != null) {
1248 FrameGraphics.DisplayMessage(message);
1249 }
1250 while ((message = stdError.readLine()) != null) {
1251 FrameGraphics.ErrorMessage(message);
1252 }
1253 } catch (Exception e) {
1254 throw new RuntimeException(e.getMessage());
1255 }
1256 return Status.OK;
1257 } else if (tokens[0].startsWith("else")) {
1258 // if the if statement was false then run the else statement
1259 if (lastItemStatus == Status.FalseIf) {
1260 // check if it is a one line if statment
1261 if (tokens.length > 1) {
1262 // put together the one line statement
1263 StringBuilder statement = new StringBuilder();
1264 for (int i = 1; i < tokens.length; i++)
1265 statement.append(tokens[i]).append(' ');
1266 // create a copy of the code item to run
1267 Text copiedCode = code.copy();
1268 copiedCode.setText(statement.toString());
1269 return RunItem(copiedCode, context, Status.OK);
1270 } else {
1271 return RunFrameAndReportError(code, context);
1272 }
1273 } else if (lastItemStatus == Status.TrueIf) {
1274 return Status.OK;
1275 }
1276 throw new RuntimeException("Else without matching If statement");
1277 } else if (tokens[0].startsWith("if")) {
1278 Boolean result = null;
1279 int parametres = 1;
1280 String variable = DEFAULT_ITEM;
1281 String ifStatement = tokens[0];
1282 // Set the default variable
1283 if (tokens.length == 1) {
1284 if (ifStatement.equals("if") || ifStatement.equals("ifnot"))
1285 variable = DEFAULT_STRING;
1286 else if (ifStatement.equals("ifzero")
1287 || ifStatement.equals("ifnotzero"))
1288 variable = DEFAULT_INTEGER;
1289 } else {
1290 variable = tokens[1];
1291 }
1292
1293 if (ifStatement.equals("if")) {
1294 result = context.getPrimitives().getBooleanValue(variable);
1295 } else if (ifStatement.equals("ifnot")) {
1296 result = !context.getPrimitives().getBooleanValue(variable);
1297 } else if (ifStatement.equals("ifdefined")) {
1298 result = context.isDefined(tokens[1]);
1299 } else if (ifStatement.equals("ifnotdef")) {
1300 result = !context.isDefined(tokens[1]);
1301 } else if (ifStatement.equals("ifzero")) {
1302 result = context.getPrimitives().getIntegerValue(variable) == 0;
1303 } else if (ifStatement.equals("ifnotzero")) {
1304 result = context.getPrimitives().getIntegerValue(variable) != 0;
1305 } else if (tokens[0].equals("ifeq")) {
1306 result = context.equalValues(tokens[1], tokens[2]);
1307 parametres = 2;
1308 } else if (tokens[0].equals("ifeqnocase")) {
1309 result = context.getPrimitives().equalValuesNoCase(tokens[1],
1310 tokens[2]);
1311 parametres = 2;
1312 } else if (tokens[0].equals("ifnoteqnocase")) {
1313 result = !context.getPrimitives().equalValuesNoCase(tokens[1],
1314 tokens[2]);
1315 parametres = 2;
1316 } else if (tokens[0].equals("ifnoteq")) {
1317 result = !context.equalValues(tokens[1], tokens[2]);
1318 parametres = 2;
1319 } else if (tokens[0].equals("ifless")) {
1320 result = context.getPrimitives().compareValues(tokens[1],
1321 tokens[2]) < 0;
1322 parametres = 2;
1323 } else if (tokens[0].equals("ifgtr")) {
1324 result = context.getPrimitives().compareValues(tokens[1],
1325 tokens[2]) > 0;
1326 parametres = 2;
1327 } else if (tokens[0].equals("ifgeq")) {
1328 result = context.getPrimitives().compareValues(tokens[1],
1329 tokens[2]) >= 0;
1330 parametres = 2;
1331 } else if (tokens[0].equals("ifleq")) {
1332 result = context.getPrimitives().compareValues(tokens[1],
1333 tokens[2]) <= 0;
1334 parametres = 2;
1335 } else if (tokens[0].equals("ifexistingframe")) {
1336 result = FrameIO.DoesFrameExist(context.getPrimitives()
1337 .getStringValue(tokens[1]));
1338 } else if (tokens[0].equals("ifexistingframeset")) {
1339 String framesetName = context.getPrimitives().getStringValue(
1340 tokens[1]);
1341 result = FrameIO.DoesFramesetExist(framesetName);
1342 } else {
1343 // assertVariableType(variable, 1, SPointer.itemPrefix);
1344 if (ifStatement.equals("ifannotation")) {
1345 result = ((Item) context.getPointers()
1346 .getVariable(variable).getValue()).isAnnotation();
1347 } else if (ifStatement.equals("iflinked")) {
1348 result = ((Item) context.getPointers()
1349 .getVariable(variable).getValue()).getLink() != null;
1350 } else if (ifStatement.equals("ifactioned")) {
1351 result = ((Item) context.getPointers()
1352 .getVariable(variable).getValue()).getAction() != null;
1353 } else if (ifStatement.equals("ifnotactioned")) {
1354 result = ((Item) context.getPointers()
1355 .getVariable(variable).getValue()).getAction() == null;
1356 } else if (ifStatement.equals("ifbodytext")) {
1357 Item i = (Item) context.getPointers().getVariable(variable)
1358 .getValue();
1359 result = i instanceof Text && !i.isFrameName()
1360 && !i.isFrameTitle();
1361 } else if (ifStatement.equals("ifnotannotation")) {
1362 result = !((Item) context.getPointers().getVariable(
1363 variable).getValue()).isAnnotation();
1364 } else if (ifStatement.equals("ifnotlinked")) {
1365 result = ((Item) context.getPointers()
1366 .getVariable(variable).getValue()).getLink() == null;
1367 } else if (ifStatement.equals("ifnotbodytext")) {
1368 Item i = (Item) context.getPointers().getVariable(variable)
1369 .getValue();
1370 result = !(i instanceof Text) || i.isFrameName()
1371 || i.isFrameTitle();
1372 }
1373 }
1374
1375 if (result == null)
1376 throw new RuntimeException("Invalid If statement");
1377 // Now check if we need to run the code
1378 else if (result) {
1379 Status status;
1380 // check if it is a one line if statment
1381 if (tokens.length > parametres + 1) {
1382 // put together the one line statement
1383 StringBuilder statement = new StringBuilder();
1384 for (int i = parametres + 1; i < tokens.length; i++)
1385 statement.append(tokens[i]).append(' ');
1386 // create a copy of the code item to run
1387 Text copiedCode = code.copy();
1388 copiedCode.setText(statement.toString());
1389 status = RunItem(copiedCode, context, Status.OK);
1390 } else {
1391 status = RunFrameAndReportError(code, context);
1392 }
1393 if (status == Status.OK) {
1394 return Status.TrueIf;
1395 } else {
1396 return status;
1397 }
1398 }
1399 return Status.FalseIf;
1400
1401 } // Look for variable length methods
1402 else if (tokens[0].equals("attachitemtocursor")) {
1403 String itemVar = DEFAULT_ITEM;
1404
1405 if (tokens.length > 1) {
1406 assertExactParametreCount(tokens, 1);
1407 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1408 itemVar = tokens[1];
1409 }
1410 Item item = (Item) context.getPointers().getVariable(itemVar)
1411 .getValue();
1412 item
1413 .setPosition(FrameMouseActions.MouseX,
1414 FrameMouseActions.MouseY);
1415 FrameMouseActions.pickup(item);
1416 return Status.OK;
1417 } else if (tokens[0].equals("attachstrtocursor")) {
1418 String stringVar = DEFAULT_STRING;
1419
1420 if (tokens.length > 1) {
1421 assertExactParametreCount(tokens, 1);
1422 stringVar = tokens[1];
1423 }
1424 String s = context.getPrimitives().getStringValue(stringVar);
1425 Frame frame = DisplayIO.getCurrentFrame();
1426 Text item = frame.createNewText(s);
1427 item
1428 .setPosition(FrameMouseActions.MouseX,
1429 FrameMouseActions.MouseY);
1430 FrameMouseActions.pickup(item);
1431 // DisplayIO.repaint();
1432 return Status.OK;
1433 } else if (tokens[0].equals("additemtoframe")) {
1434 String itemVar = DEFAULT_ITEM;
1435 String frameVar = DEFAULT_FRAME;
1436
1437 if (tokens.length > 1) {
1438 assertExactParametreCount(tokens, 2);
1439 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1440 assertVariableType(tokens[2], 2, SPointer.itemPrefix);
1441 itemVar = tokens[2];
1442 frameVar = tokens[1];
1443 }
1444 Frame frame = (Frame) context.getPointers().getVariable(frameVar)
1445 .getValue();
1446 Item item = (Item) context.getPointers().getVariable(itemVar)
1447 .getValue();
1448 frame.addItem(item);
1449
1450 return Status.OK;
1451 } else if (tokens[0].equals("connectdots")) {
1452 assertMinParametreCount(tokens, 2);
1453 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1454 assertVariableType(tokens[2], 2, SPointer.itemPrefix);
1455 Item dot1 = null;
1456 Item dot2 = null;
1457 try {
1458 dot1 = (Item) context.getPointers().getVariable(tokens[1])
1459 .getValue();
1460 } catch (Exception e) {
1461 throw new IncorrectTypeException("Dot", 1);
1462 }
1463 try {
1464 dot2 = (Item) context.getPointers().getVariable(tokens[2])
1465 .getValue();
1466 } catch (Exception e) {
1467 throw new IncorrectTypeException("Dot", 2);
1468 }
1469 Frame frame = dot1.getParent();
1470 frame.addItem(new Line(dot1, dot2, frame.getNextItemID()));
1471 return Status.OK;
1472 } else if (tokens[0].equals("createitem")
1473 || tokens[0].equals("createtext")) {
1474 assertMinParametreCount(tokens, 4);
1475 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1476 assertVariableType(tokens[4], 4, SPointer.itemPrefix);
1477 Frame frame = (Frame) context.getPointers().getVariable(tokens[1])
1478 .getValue();
1479 Item newItem;
1480 int x = (int) context.getPrimitives().getIntegerValue(tokens[2]);
1481 int y = (int) context.getPrimitives().getIntegerValue(tokens[3]);
1482 // check for the option text and action for the new item
1483 if (tokens.length > 5) {
1484 String newText = context.getPrimitives().getStringValue(
1485 tokens[5]);
1486 String newAction = null;
1487 if (tokens.length > 6) {
1488 newAction = context.getPrimitives().getStringValue(
1489 tokens[6]);
1490 }
1491 newItem = frame.addText(x, y, newText, newAction);
1492 } else {
1493 if (tokens[0].equals("createtext")) {
1494 newItem = frame.createNewText();
1495 newItem.setPosition(x, y);
1496 } else {
1497 // create a point if the optional params are not provided
1498 newItem = frame.addDot(x, y);
1499 }
1500 }
1501 context.getPointers().setObject(tokens[4], newItem);
1502
1503 return Status.OK;
1504 } else if (tokens[0].equals("deleteitem")) {
1505 assertMinParametreCount(tokens, 1);
1506 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1507 Item item = (Item) context.getPointers().getVariable(tokens[1])
1508 .getValue();
1509 item.delete();
1510 return Status.OK;
1511 } else if (tokens[0].equals("deleteframe")) {
1512 assertMinParametreCount(tokens, 1);
1513 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1514 Frame frame = (Frame) context.getPointers().getVariable(tokens[1])
1515 .getValue();
1516 boolean success = FrameIO.DeleteFrame(frame);
1517
1518 if (tokens.length > 2) {
1519 context.getPrimitives().setValue(tokens[2],
1520 new SBoolean(success));
1521 }
1522
1523 return Status.OK;
1524 } else if (tokens[0].equals("deleteframeset")) {
1525 assertMinParametreCount(tokens, 1);
1526 String framesetName = context.getPrimitives().getStringValue(
1527 tokens[1]);
1528 boolean success = FrameIO.DeleteFrameset(framesetName);
1529
1530 if (tokens.length > 2) {
1531 context.getPrimitives().setValue(tokens[2],
1532 new SBoolean(success));
1533 }
1534
1535 return Status.OK;
1536 } else if (tokens[0].equals("copyitem")) {
1537 assertMinParametreCount(tokens, 2);
1538 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1539 assertVariableType(tokens[2], 2, SPointer.itemPrefix);
1540 Item item = (Item) context.getPointers().getVariable(tokens[1])
1541 .getValue();
1542 Item copy = item.copy();
1543 context.getPointers().setObject(tokens[2], copy);
1544
1545 return Status.OK;
1546 } else if (tokens[0].equals("copyframeset")) {
1547 assertMinParametreCount(tokens, 2);
1548 String framesetToCopy = context.getPrimitives().getStringValue(
1549 tokens[1]);
1550 String copiedFrameset = context.getPrimitives().getStringValue(
1551 tokens[2]);
1552 boolean success = FrameIO.CopyFrameset(framesetToCopy,
1553 copiedFrameset);
1554
1555 if (tokens.length > 3) {
1556 context.getPrimitives().setValue(tokens[3],
1557 new SBoolean(success));
1558 }
1559
1560 return Status.OK;
1561 } else if (tokens[0].equals("copyframe")) {
1562 assertMinParametreCount(tokens, 2);
1563 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1564 assertVariableType(tokens[2], 2, SPointer.framePrefix);
1565 Frame frameToCopy = (Frame) context.getPointers().getVariable(
1566 tokens[1]).getValue();
1567 FrameIO.SuspendCache();
1568 Frame freshCopy = FrameIO.LoadFrame(frameToCopy.getFrameName());
1569 // Change the frameset if one was provided
1570 if (tokens.length > 3) {
1571 String destinationFrameset = context.getPrimitives()
1572 .getStringValue(tokens[3]);
1573 freshCopy.setFrameset(destinationFrameset);
1574 }// Otherwise add it to the end of this frameset
1575 freshCopy.setFrameNumber(FrameIO.getLastNumber(freshCopy
1576 .getFramesetName()) + 1);
1577 context.getPointers().setObject(tokens[2], freshCopy);
1578 String fileContents = FrameIO.ForceSaveFrame(freshCopy);
1579 boolean success = fileContents != null;
1580 FrameIO.ResumeCache();
1581 if (tokens.length > 4) {
1582 context.getPrimitives().setValue(tokens[4],
1583 new SBoolean(success));
1584 }
1585 return Status.OK;
1586 } else if (tokens[0].equals("createframe")) {
1587
1588 String framesetName = DEFAULT_STRING;
1589 String frameVar = DEFAULT_FRAME;
1590
1591 if (tokens.length > 1) {
1592 assertMinParametreCount(tokens, 2);
1593 assertVariableType(tokens[2], 2, SPointer.framePrefix);
1594 framesetName = tokens[1];
1595 frameVar = tokens[2];
1596 }
1597
1598 if (tokens.length > 3) {
1599 context.createFrame(framesetName, frameVar, tokens[3]);
1600 } else
1601 context.createFrame(framesetName, frameVar, null);
1602
1603 return Status.OK;
1604 } else if (tokens[0].equals("closeframe")) {
1605 String frameVar = DEFAULT_FRAME;
1606
1607 if (tokens.length > 1) {
1608 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1609 frameVar = tokens[1];
1610 }
1611
1612 if (tokens.length > 2) {
1613 // assertPrimitiveType(tokens[3], 3);
1614 context.closeFrame(frameVar, tokens[3]);
1615 } else
1616 context.closeFrame(frameVar, null);
1617
1618 return Status.OK;
1619 } else if (tokens[0].equals("readframe")
1620 || tokens[0].equals("openframe")) {
1621
1622 String frameName = DEFAULT_STRING;
1623 String frameVar = DEFAULT_FRAME;
1624
1625 if (tokens.length > 1) {
1626 assertMinParametreCount(tokens, 2);
1627 assertVariableType(tokens[2], 2, SPointer.framePrefix);
1628 frameName = tokens[1];
1629 frameVar = tokens[2];
1630 // assertPrimitiveType(frameName, 1);
1631 }
1632
1633 if (tokens.length > 3) {
1634 // assertPrimitiveType(tokens[3], 3);
1635 context.readFrame(frameName, frameVar, tokens[3]);
1636 } else
1637 context.readFrame(frameName, frameVar, null);
1638
1639 return Status.OK;
1640 } else if (tokens[0].equals("readkbdcond")) {
1641
1642 String nextCharVarName = DEFAULT_CHAR;
1643 String wasCharVarName = DEFAULT_BOOLEAN;
1644
1645 if (tokens.length > 1) {
1646 assertMinParametreCount(tokens, 2);
1647 assertVariableType(tokens[2], 2, SPointer.framePrefix);
1648 nextCharVarName = tokens[1];
1649 wasCharVarName = tokens[2];
1650 }
1651
1652 Character nextChar = _KeyStrokes.poll();
1653 boolean hasChar = nextChar != null;
1654 context.getPrimitives().setValue(wasCharVarName,
1655 new SBoolean(hasChar));
1656 if (hasChar)
1657 context.getPrimitives().setValue(nextCharVarName,
1658 new SCharacter(nextChar));
1659
1660 return Status.OK;
1661 } else if (tokens[0].equals("openreadfile")) {
1662 assertVariableType(tokens[1], 1, SString.prefix);
1663 assertVariableType(tokens[2], 2, SPointer.filePrefix);
1664
1665 if (tokens.length > 3) {
1666 assertVariableType(tokens[3], 3, SBoolean.prefix);
1667 context.openReadFile(tokens[1], tokens[2], tokens[3]);
1668 } else
1669 context.openReadFile(tokens[1], tokens[2]);
1670
1671 return Status.OK;
1672 } else if (tokens[0].equals("readlinefile")
1673 || tokens[0].equals("readlnfile")) {
1674 assertVariableType(tokens[1], 1, SPointer.filePrefix);
1675
1676 if (tokens.length > 3) {
1677 assertVariableType(tokens[3], 3, SBoolean.prefix);
1678 context.readLineFile(tokens[1], tokens[2], tokens[3]);
1679 } else
1680 context.readLineFile(tokens[1], tokens[2]);
1681
1682 return Status.OK;
1683 } else if (tokens[0].equals("readitemfile")) {
1684 assertVariableType(tokens[1], 1, SPointer.filePrefix);
1685 assertVariableType(tokens[2], 1, SPointer.itemPrefix);
1686
1687 if (tokens.length > 3) {
1688 assertVariableType(tokens[3], 3, SBoolean.prefix);
1689 context.readItemFile(tokens[1], tokens[2], tokens[3]);
1690 } else
1691 context.readItemFile(tokens[1], tokens[2]);
1692
1693 return Status.OK;
1694 } else if (tokens[0].equals("openwritefile")) {
1695 assertVariableType(tokens[1], 1, SString.prefix);
1696 assertVariableType(tokens[2], 2, SPointer.filePrefix);
1697
1698 if (tokens.length > 3) {
1699 assertVariableType(tokens[3], 3, SBoolean.prefix);
1700 context.openWriteFile(tokens[1], tokens[2], tokens[3]);
1701 } else
1702 context.openWriteFile(tokens[1], tokens[2]);
1703
1704 return Status.OK;
1705 } else if (tokens[0].equals("writefile")
1706 || tokens[0].equals("writelinefile")
1707 || tokens[0].equals("writelnfile")) {
1708 assertVariableType(tokens[1], 1, SPointer.filePrefix);
1709
1710 StringBuilder textToWrite = new StringBuilder();
1711 if (tokens.length == 1) {
1712 textToWrite.append(context.getPrimitives().getVariable(
1713 DEFAULT_STRING).stringValue()
1714 + " ");
1715 } else {
1716 for (int i = 2; i < tokens.length; i++) {
1717 if (Primitives.isPrimitive(tokens[i])) {
1718 textToWrite.append(context.getPrimitives().getVariable(
1719 tokens[i]).stringValue());
1720 } else
1721 throw new Exception("Illegal parametre: " + tokens[i]
1722 + " in " + code.toString());
1723 }
1724 }
1725
1726 if (!tokens[0].equals("writefile"))
1727 textToWrite.append('\n');
1728 context.writeFile(tokens[1], textToWrite.toString());
1729
1730 return Status.OK;
1731 } else if (tokens[0].equals("displayframeset")) {
1732 assertMinParametreCount(tokens, 1);
1733 String framesetName = context.getPrimitives().getStringValue(
1734 tokens[1]);
1735 int lastFrameNo = FrameIO.getLastNumber(framesetName);
1736 int firstFrameNo = 0;
1737 double pause = 0.0;
1738 // get the first and last frames to display if they were proided
1739 if (tokens.length > 2) {
1740 firstFrameNo = (int) context.getPrimitives().getIntegerValue(
1741 tokens[2]);
1742 if (tokens.length > 3) {
1743 lastFrameNo = (int) context.getPrimitives()
1744 .getIntegerValue(tokens[3]);
1745 if (tokens.length > 4) {
1746 pause = context.getPrimitives().getDoubleValue(
1747 tokens[4]);
1748 }
1749 }
1750 }
1751 Runtime runtime = Runtime.getRuntime();
1752 // Display the frames
1753 for (int i = firstFrameNo; i <= lastFrameNo; i++) {
1754 Frame frame = FrameIO.LoadFrame(framesetName + i);
1755 if (frame != null) {
1756 double thisFramesPause = pause;
1757 // check for change in delay for this frame only
1758 Item pauseItem = ItemUtils.FindTag(frame.getItems(),
1759 "@DisplayFramePause:");
1760 if (pauseItem != null) {
1761 try {
1762 // attempt to read in the delay value
1763 thisFramesPause = Double.parseDouble(ItemUtils
1764 .StripTag(
1765 ((Text) pauseItem).getFirstLine(),
1766 "@DisplayFramePause:"));
1767 } catch (NumberFormatException nfe) {
1768 }
1769 }
1770 DisplayIO.setCurrentFrame(frame);
1771 pause(thisFramesPause);
1772
1773 long freeMemory = runtime.freeMemory();
1774 if (freeMemory < DisplayTree.GARBAGE_COLLECTION_THRESHOLD) {
1775 runtime.gc();
1776 FrameGraphics
1777 .DisplayMessage("Force Garbage Collection!");
1778 }
1779 }
1780 }
1781 return Status.OK;
1782 } else if (tokens[0].equals("createframeset")) {
1783 String framesetName = DEFAULT_STRING;
1784 String successVar = null;
1785 if (tokens.length > 1) {
1786 framesetName = tokens[1];
1787 if (tokens.length > 2)
1788 successVar = tokens[2];
1789 }
1790 context.createFrameset(framesetName, successVar);
1791 return Status.OK;
1792 } else if (tokens[0].equals("writetree")) {
1793 assertMinParametreCount(tokens, 3);
1794 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1795 Frame source = (Frame) context.getPointers().getVariable(tokens[1])
1796 .getValue();
1797 String format = context.getPrimitives().getStringValue(tokens[2]);
1798 String fileName = context.getPrimitives().getStringValue(tokens[3]);
1799 WriteTree wt = new WriteTree(format, fileName);
1800 if (wt.initialise(source)) {
1801 wt.setStartFrame(source);
1802 wt.run();
1803 }
1804 return Status.OK;
1805 } else if (tokens[0].equals("concatstr")) {
1806 assertMinParametreCount(tokens, 3);
1807 String resultVar = tokens[tokens.length - 1];
1808
1809 StringBuilder sb = new StringBuilder();
1810 // loop through all the strings concatenating them
1811 for (int i = 1; i < tokens.length - 1; i++) {
1812 // assertPrimitiveType(tokens[i], i);
1813 sb.append(context.getPrimitives().getStringValue(tokens[i]));
1814 }
1815 context.getPrimitives().setValue(resultVar,
1816 new SString(sb.toString()));
1817 return Status.OK;
1818 } else if (tokens[0].equals("convstrlower")) {
1819 assertExactParametreCount(tokens, 1);
1820 // assertPrimitiveType(tokens[1], 1);
1821 context.getPrimitives().setValue(
1822 tokens[1],
1823 new SString(context.getPrimitives().getStringValue(
1824 tokens[1]).toLowerCase()));
1825 return Status.OK;
1826 } else if (tokens[0].equals("convstrupper")) {
1827 assertExactParametreCount(tokens, 1);
1828 // assertPrimitiveType(tokens[1], 1);
1829 context.getPrimitives().setValue(
1830 tokens[1],
1831 new SString(context.getPrimitives().getStringValue(
1832 tokens[1]).toUpperCase()));
1833 return Status.OK;
1834 } else if (tokens[0].equals("countcharsinstr")) {
1835 assertExactParametreCount(tokens, 3);
1836 String s = context.getPrimitives().getStringValue(tokens[1]);
1837 String pattern = context.getPrimitives().getStringValue(tokens[2]);
1838 int count = countCharsInString(s, pattern);
1839 context.getPrimitives().setValue(tokens[3], new SInteger(count));
1840 return Status.OK;
1841 } else if (tokens[0].equals("countcharsinitem")) {
1842 assertExactParametreCount(tokens, 3);
1843 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1844 Item item = (Item) context.getPointers().getVariable(tokens[1])
1845 .getValue();
1846 String pattern = context.getPrimitives().getStringValue(tokens[2]);
1847 int count = 0;
1848 if (item instanceof Text)
1849 count = countCharsInString(((Text) item).getTextNoList(),
1850 pattern);
1851 context.getPrimitives().setValue(tokens[3], new SInteger(count));
1852 return Status.OK;
1853 } else if (tokens[0].equals("parseframename")) {
1854 assertExactParametreCount(tokens, 4);
1855 String frameName = context.getPrimitives()
1856 .getStringValue(tokens[1]);
1857 String frameSet = "";
1858 int frameNo = -1;
1859 boolean success = true;
1860 try {
1861 frameSet = Conversion.getFrameset(frameName, false);
1862 frameNo = Conversion.getFrameNumber(frameName);
1863 } catch (Exception e) {
1864 success = false;
1865 }
1866 // assertPrimitiveType(tokens[2], 2);
1867 context.getPrimitives().setValue(tokens[2], new SBoolean(success));
1868
1869 // assertPrimitiveType(tokens[3], 3);
1870 context.getPrimitives().setValue(tokens[3], new SString(frameSet));
1871
1872 // assertPrimitiveType(tokens[4], 4);
1873 context.getPrimitives().setValue(tokens[4], new SInteger(frameNo));
1874
1875 return Status.OK;
1876 } else if (tokens[0].equals("parsestr")) {
1877 assertMinParametreCount(tokens, 2);
1878 // assertPrimitiveType(tokens[1], 1);
1879 // assertPrimitiveType(tokens[2], 2);
1880
1881 String s = context.getPrimitives().getStringValue(tokens[1]);
1882
1883 String separator = context.getPrimitives()
1884 .getStringValue(tokens[2]);
1885
1886 String[] split = s.split(separator, tokens.length - 4);
1887
1888 if (tokens.length > 3) {
1889 // assertPrimitiveType(tokens[3], 3);
1890 int count = split.length;
1891 // if the string is not blank and its got a remainder then
1892 // decrease the count by 1 to account for the remainder
1893 if (split.length != 0 && split.length > tokens.length - 5)
1894 count--;
1895
1896 context.getPrimitives()
1897 .setValue(tokens[3], new SInteger(count));
1898
1899 if (tokens.length > 4) {
1900 // Set the remainder string
1901 // assertPrimitiveType(tokens[4], 4);
1902 if (split.length < tokens.length - 4)
1903 context.getPrimitives().setValue(tokens[4],
1904 new SString());
1905 else
1906 context.getPrimitives().setValue(tokens[4],
1907 new SString(split[split.length - 1]));
1908
1909 // Set the strings for each of the vars
1910 if (tokens.length > 5) {
1911 for (int i = 5; i < tokens.length; i++) {
1912 // assertPrimitiveType(tokens[i], i);
1913 if (split.length < i - 4)
1914 context.getPrimitives().setValue(tokens[i],
1915 new SString());
1916 else
1917 context.getPrimitives().setValue(tokens[i],
1918 new SString(split[i - 5]));
1919 }
1920 }
1921 }
1922 }
1923 return Status.OK;
1924 } else if (tokens[0].equals("stripstr")) {
1925 assertExactParametreCount(tokens, 2);
1926 String s = context.getPrimitives().getStringValue(tokens[1]);
1927 String charsToStrip = context.getPrimitives().getStringValue(
1928 tokens[2]);
1929 for (int i = 0; i < charsToStrip.length(); i++)
1930 s = s.replaceAll(charsToStrip.substring(i, i + 1), "");
1931 context.getPrimitives().setValue(tokens[1], new SString(s));
1932 return Status.OK;
1933 } else if (tokens[0].equals("subststr")) {
1934 assertExactParametreCount(tokens, 3);
1935 String oldString = context.getPrimitives()
1936 .getStringValue(tokens[2]);
1937 String newString = context.getPrimitives()
1938 .getStringValue(tokens[3]);
1939 String result = context.getPrimitives().getStringValue(tokens[1]);
1940 result = result.replaceAll(oldString, newString);
1941 context.getPrimitives().setValue(tokens[1], new SString(result));
1942 return Status.OK;
1943 } else if (tokens[0].equals("substr")) {
1944 assertExactParametreCount(tokens, 4);
1945 int startPos = (int) context.getPrimitives().getIntegerValue(
1946 tokens[2]) - 1;
1947 int length = (int) context.getPrimitives().getIntegerValue(
1948 tokens[3]);
1949 String s = context.getPrimitives().getStringValue(tokens[1]);
1950 String result;
1951 if (startPos + length < s.length())
1952 result = s.substring(startPos, startPos + length);
1953 else
1954 result = s.substring(startPos);
1955 context.getPrimitives().setValue(tokens[4], new SString(result));
1956 return Status.OK;
1957 } else if (tokens[0].equals("pause")) {
1958 String lengthVar = DEFAULT_REAL;
1959
1960 if (tokens.length > 1) {
1961 assertExactParametreCount(tokens, 1);
1962 lengthVar = tokens[1];
1963 }
1964
1965 pause(context.getPrimitives().getDoubleValue(lengthVar));
1966 return Status.OK;
1967 } else if (tokens[0].equals("glidecursorto")) {
1968 assertMinParametreCount(tokens, 2);
1969 int finalX = (int) context.getPrimitives().getIntegerValue(
1970 tokens[1]);
1971 int finalY = (int) context.getPrimitives().getIntegerValue(
1972 tokens[2]);
1973 int milliseconds = 1000;
1974 if (tokens.length > 3)
1975 milliseconds = (int) (context.getPrimitives().getDoubleValue(
1976 tokens[3]) * 1000);
1977
1978 int initialX = DisplayIO.getMouseX();
1979 int initialY = DisplayIO.getMouseY();
1980
1981 final int timeInterval = 40;
1982
1983 int deltaX = (int) (finalX - initialX);
1984 int deltaY = (int) (finalY - initialY);
1985
1986 int intervals = milliseconds / timeInterval;
1987 for (double i = 0; i < intervals; i++) {
1988 int newX = initialX + (int) (deltaX * i / intervals);
1989 int newY = initialY + (int) (deltaY * i / intervals);
1990 Thread.yield();
1991 Thread.sleep(timeInterval);
1992 DisplayIO.setCursorPosition(newX, newY);
1993 // DisplayIO.repaint();
1994 }
1995 // Thread.yield();
1996 Thread.sleep(milliseconds % timeInterval);
1997 DisplayIO.setCursorPosition(finalX, finalY);
1998 return Status.OK;
1999 } else if (tokens[0].equals("glideitemto")) {
2000 assertMinParametreCount(tokens, 3);
2001 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
2002 Item item = (Item) context.getPointers().getVariable(tokens[1])
2003 .getValue();
2004 int finalX = (int) context.getPrimitives().getIntegerValue(
2005 tokens[2]);
2006 int finalY = (int) context.getPrimitives().getIntegerValue(
2007 tokens[3]);
2008
2009 // DisplayIO.setCursorPosition(item.getX(), item.getY());
2010 // FrameMouseActions.pickup(item);
2011
2012 int milliseconds = 1000;
2013 if (tokens.length > 4)
2014 milliseconds = (int) (context.getPrimitives().getDoubleValue(
2015 tokens[4]) * 1000);
2016
2017 int initialX = item.getX();
2018 int initialY = item.getY();
2019 // int initialX = DisplayIO.getMouseX();
2020 // int initialY = DisplayIO.getMouseY();
2021
2022 final int timeInterval = 40;
2023
2024 int deltaX = (int) (finalX - initialX);
2025 int deltaY = (int) (finalY - initialY);
2026
2027 int intervals = milliseconds / timeInterval;
2028 for (double i = 0; i < intervals; i++) {
2029 int newX = initialX + (int) (deltaX * i / intervals);
2030 int newY = initialY + (int) (deltaY * i / intervals);
2031 Thread.yield();
2032 Thread.sleep(timeInterval);
2033 // DisplayIO.setCursorPosition(newX, newY);
2034
2035 item.setPosition(newX, newY);
2036 FrameGraphics.Repaint();
2037 }
2038 // Thread.yield();
2039 Thread.sleep(milliseconds % timeInterval);
2040 item.setPosition(finalX, finalY);
2041 // DisplayIO.setCursorPosition(finalX, finalY);
2042 FrameMouseActions.anchor(item);
2043 Frame.FreeItems.clear();
2044 FrameGraphics.Repaint();
2045 // FrameMouseActions.updateCursor();
2046 return Status.OK;
2047 }
2048 // Now look for fixed parametre statements
2049 else if (tokens.length == 1) {
2050 if (tokens[0].equals(EXIT_TEXT)) {
2051 return Status.Exit;
2052 } else if (tokens[0].equals(LOOP_TEXT)) {
2053 Status status = Status.OK;
2054 // Keep looping until break or exit occurs
2055 while (status == Status.OK || status == Status.Continue)
2056 status = RunFrameAndReportError(code, context);
2057 if (status == Status.Continue || status == Status.Break)
2058 status = Status.OK;
2059 return status;
2060 } else if (tokens[0].equals(CONTINUE_TEXT)
2061 || tokens[0].equals(CONTINUE2_TEXT)) {
2062 return Status.Continue;
2063 } else if (tokens[0].equals(BREAK_TEXT)
2064 || tokens[0].equals(BREAK2_TEXT)) {
2065 return Status.Break;
2066 } else if (tokens[0].equals(RETURN_TEXT)) {
2067 return Status.Return;
2068 } else if (tokens[0].equals("pressleftbutton")) {
2069 DisplayIO.pressMouse(InputEvent.BUTTON1_MASK);
2070 return Status.OK;
2071 } else if (tokens[0].equals("pressmiddlebutton")) {
2072 DisplayIO.pressMouse(InputEvent.BUTTON2_MASK);
2073 return Status.OK;
2074 } else if (tokens[0].equals("pressrightbutton")) {
2075 DisplayIO.pressMouse(InputEvent.BUTTON3_MASK);
2076 return Status.OK;
2077 } else if (tokens[0].equals("releaseleftbutton")) {
2078 DisplayIO.releaseMouse(InputEvent.BUTTON1_MASK);
2079 return Status.OK;
2080 } else if (tokens[0].equals("releasemiddlebutton")) {
2081 DisplayIO.releaseMouse(InputEvent.BUTTON2_MASK);
2082 return Status.OK;
2083 } else if (tokens[0].equals("releaserightbutton")) {
2084 DisplayIO.releaseMouse(InputEvent.BUTTON3_MASK);
2085 return Status.OK;
2086 } else if (tokens[0].equals("clickleftbutton")) {
2087 DisplayIO.clickMouse(InputEvent.BUTTON1_MASK);
2088 return Status.OK;
2089 } else if (tokens[0].equals("clickmiddlebutton")) {
2090 DisplayIO.clickMouse(InputEvent.BUTTON2_MASK);
2091 return Status.OK;
2092 } else if (tokens[0].equals("clickrightbutton")) {
2093 DisplayIO.clickMouse(InputEvent.BUTTON3_MASK);
2094 return Status.OK;
2095 } else if (tokens[0].equals("repaint")) {
2096 FrameGraphics.Repaint();
2097 return Status.OK;
2098 }
2099
2100 if (tokens[0].equals("add")) {
2101 context.getPrimitives().add(DEFAULT_INTEGER);
2102 } else if (tokens[0].equals("subtract")) {
2103 context.getPrimitives().subtract(DEFAULT_INTEGER);
2104 } else
2105 throw new RuntimeException("Invalid statement:");
2106 return Status.OK;
2107 } else if (tokens.length == 2) {
2108 if (tokens[0].equals("closewritefile")) {
2109 assertVariableType(tokens[1], 1, SPointer.filePrefix);
2110 context.closeWriteFile(tokens[1]);
2111
2112 return Status.OK;
2113 } else if (tokens[0].equals("closereadfile")) {
2114 assertVariableType(tokens[1], 1, SPointer.filePrefix);
2115 context.closeReadFile(tokens[1]);
2116
2117 return Status.OK;
2118 }
2119
2120 if (Primitives.isPrimitive(tokens[1])) {
2121 if (tokens[0].equals("add")) {
2122 context.getPrimitives().add(tokens[1]);
2123 } else if (tokens[0].equals("subtract")) {
2124 context.getPrimitives().subtract(tokens[1]);
2125 } else
2126 throw new RuntimeException("Invalid statement:");
2127 return Status.OK;
2128 }
2129 } else if (tokens.length == 3) {
2130 if (tokens[0].startsWith("foreach")) {
2131 Class itemType = Object.class;
2132 String type = tokens[0].substring("foreach".length());
2133 // Check the type of foreach loop
2134 // and set the item type to iterate over
2135 if (type.equals("dot")) {
2136 itemType = Dot.class;
2137 } else if (type.equals("text")) {
2138 itemType = Text.class;
2139 } else if (type.equals("line")) {
2140 itemType = Line.class;
2141 }
2142
2143 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
2144 assertVariableType(tokens[2], 2, SPointer.framePrefix);
2145 Frame currFrame = (Frame) context.getPointers().getVariable(
2146 tokens[2]).getValue();
2147 // Create the ip variable
2148 Item frameName = currFrame.getFrameNameItem();
2149 Item frameTitle = currFrame.getTitle();
2150
2151 for (Item i : currFrame.getItems()) {
2152 if (i == frameName || i == frameTitle)
2153 continue;
2154 if (!(itemType.isInstance(i)))
2155 continue;
2156
2157 context.getPointers().setObject(tokens[1], i);
2158 Status status = RunFrameAndReportError(code, context);
2159 // check if we need to exit this loop because of
2160 // statements in the code that was run
2161 if (status == Status.Exit || status == Status.Return)
2162 return status;
2163 else if (status == Status.Break)
2164 return Status.OK;
2165 }
2166 return Status.OK;
2167 }
2168
2169 if (Primitives.isPrimitive(tokens[1])
2170 && Primitives.isPrimitive(tokens[2])) {
2171 if (tokens[0].equals("movecursorto")) {
2172 assertExactParametreCount(tokens, 2);
2173 int x = (int) context.getPrimitives().getIntegerValue(
2174 tokens[1]);
2175 int y = (int) context.getPrimitives().getIntegerValue(
2176 tokens[2]);
2177 DisplayIO.setCursorPosition(x, y);
2178 return Status.OK;
2179 } else if (tokens[0].equals("not")) {
2180 context.getPrimitives().not(tokens[1], tokens[2]);
2181 } else if (tokens[0].equals("exp")) {
2182 context.getPrimitives().exp(tokens[1], tokens[2]);
2183 } else if (tokens[0].equals("log")) {
2184 context.getPrimitives().log(tokens[1], tokens[2]);
2185 } else if (tokens[0].equals("log10")) {
2186 context.getPrimitives().log10(tokens[1], tokens[2]);
2187 } else if (tokens[0].equals("sqrt")) {
2188 context.getPrimitives().sqrt(tokens[1], tokens[2]);
2189 } else if (tokens[0].equals("add")) {
2190 context.getPrimitives().add(tokens[1], tokens[2]);
2191 } else if (tokens[0].equals("subtract")) {
2192 context.getPrimitives().subtract(tokens[1], tokens[2]);
2193 } else if (tokens[0].equals("multiply")) {
2194 context.getPrimitives().multiply(tokens[1], tokens[2]);
2195 } else if (tokens[0].equals("divide")) {
2196 context.getPrimitives().divide(tokens[1], tokens[2]);
2197 } else
2198 throw new RuntimeException("Invalid statement:");
2199 return Status.OK;
2200 }
2201 } else if (tokens.length == 4) {
2202 if (Primitives.isPrimitive(tokens[1])
2203 && Primitives.isPrimitive(tokens[2])
2204 && Primitives.isPrimitive(tokens[3])) {
2205 if (tokens[0].equals("add")) {
2206 context.getPrimitives()
2207 .add(tokens[1], tokens[2], tokens[3]);
2208 } else if (tokens[0].equals("subtract")) {
2209 context.getPrimitives().subtract(tokens[1], tokens[2],
2210 tokens[3]);
2211 } else if (tokens[0].equals("divide")) {
2212 context.getPrimitives().divide(tokens[1], tokens[2],
2213 tokens[3]);
2214 } else if (tokens[0].equals("multiply")) {
2215 context.getPrimitives().multiply(tokens[1], tokens[2],
2216 tokens[3]);
2217 } else if (tokens[0].equals("modulo")) {
2218 context.getPrimitives().modulo(tokens[1], tokens[2],
2219 tokens[3]);
2220 } else if (tokens[0].equals("power")) {
2221 context.getPrimitives().power(tokens[1], tokens[2],
2222 tokens[3]);
2223 } else
2224 throw new Exception("Statement not found: " + tokens[0]
2225 + " in " + code.toString());
2226 return Status.OK;
2227 }
2228 }
2229 throw new RuntimeException("Unknown statement: ");
2230 }
2231
2232 private static void pause(double time) throws Exception {
2233 for (int i = 0; i < time * 10; i++) {
2234 Thread.yield();
2235 Thread.sleep(100);
2236 }
2237 }
2238
2239 public static int countCharsInString(String s, String pattern) {
2240 String newString = s;
2241 int count = -1;
2242 do {
2243 count++;
2244 s = newString;
2245 newString = s.replaceFirst(pattern, "");
2246 } while (s.length() != newString.length());
2247
2248 return count;
2249 }
2250
2251 public static void assertVariableType(String varName, int no, String type)
2252 throws Exception {
2253 if (!varName.startsWith(type))
2254 throw new IncorrectTypeException(type, no);
2255 }
2256
2257 /*
2258 * public static void assertPrimitiveType(String varName, int no) throws
2259 * Exception { if (!Primitives.isPrimitive(varName)) throw new
2260 * IncorrectTypeException("primitive", no); }
2261 */
2262
2263 public static void assertMinParametreCount(String[] tokens,
2264 int minParametres) throws Exception {
2265 if (tokens.length - 1 < minParametres)
2266 throw new BelowMinParametreCountException(minParametres);
2267 }
2268
2269 public static void assertExactParametreCount(String[] tokens,
2270 int parametreCount) throws Exception {
2271 if (tokens.length - 1 != parametreCount)
2272 throw new IncorrectParametreCountException(parametreCount);
2273 }
2274
2275 private static String getMessage(String[] tokens, Context context,
2276 String code, String separator, int firstStringIndex)
2277 throws Exception {
2278 StringBuilder message = new StringBuilder();
2279 if (tokens.length == firstStringIndex) {
2280 message.append(context.getPrimitives().getVariable(DEFAULT_STRING)
2281 .stringValue());
2282 } else {
2283 for (int i = firstStringIndex; i < tokens.length; i++) {
2284 if (Primitives.isPrimitive(tokens[i])) {
2285 message.append(context.getPrimitives().getVariable(
2286 tokens[i]).stringValue()
2287 + separator);
2288 } else
2289 throw new Exception("Illegal parametre: [" + tokens[i]
2290 + "] in line " + code);
2291 }
2292 }
2293 return message.toString();
2294 }
2295}
Note: See TracBrowser for help on using the repository browser.