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

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

Added faster versions of search frameset

File size: 97.2 KB
Line 
1package org.expeditee.actions;
2
3import java.awt.Color;
4import java.awt.Point;
5import java.awt.event.InputEvent;
6import java.awt.geom.Point2D;
7import java.io.BufferedReader;
8import java.io.InputStreamReader;
9import java.util.ArrayList;
10import java.util.Collection;
11import java.util.HashMap;
12import java.util.LinkedList;
13import java.util.List;
14import java.util.Map;
15import java.util.Random;
16import java.util.regex.Pattern;
17
18import org.expeditee.agents.Agent;
19import org.expeditee.agents.DefaultAgent;
20import org.expeditee.agents.DisplayTree;
21import org.expeditee.agents.SearchAgent;
22import org.expeditee.agents.SearchFrameset;
23import org.expeditee.agents.SearchTree;
24import org.expeditee.agents.WriteTree;
25import org.expeditee.gui.AttributeUtils;
26import org.expeditee.gui.Browser;
27import org.expeditee.gui.DisplayIO;
28import org.expeditee.gui.Frame;
29import org.expeditee.gui.FrameGraphics;
30import org.expeditee.gui.FrameIO;
31import org.expeditee.gui.FrameKeyboardActions;
32import org.expeditee.gui.FrameMouseActions;
33import org.expeditee.gui.FrameUtils;
34import org.expeditee.gui.FreeItems;
35import org.expeditee.gui.MessageBay;
36import org.expeditee.io.Conversion;
37import org.expeditee.items.Dot;
38import org.expeditee.items.Item;
39import org.expeditee.items.ItemUtils;
40import org.expeditee.items.Line;
41import org.expeditee.items.Text;
42import org.expeditee.items.Item.HighlightMode;
43import org.expeditee.simple.AboveMaxParametreCountException;
44import org.expeditee.simple.BelowMinParametreCountException;
45import org.expeditee.simple.Context;
46import org.expeditee.simple.ExpediteeJEP;
47import org.expeditee.simple.IncorrectParametreCountException;
48import org.expeditee.simple.IncorrectTypeException;
49import org.expeditee.simple.Pointers;
50import org.expeditee.simple.Primitives;
51import org.expeditee.simple.SBoolean;
52import org.expeditee.simple.SCharacter;
53import org.expeditee.simple.SInteger;
54import org.expeditee.simple.SPointer;
55import org.expeditee.simple.SPrimitive;
56import org.expeditee.simple.SReal;
57import org.expeditee.simple.SString;
58import org.expeditee.simple.SVariable;
59import org.expeditee.simple.UnitTestFailedException;
60import org.expeditee.stats.AgentStats;
61import org.expeditee.stats.SessionStats;
62import org.nfunk.jep.Node;
63
64public class Simple implements Runnable {
65
66 private static final String DEFAULT_STRING = "$s.";
67
68 private static final String DEFAULT_BOOLEAN = "$b.";
69
70 private static final String DEFAULT_CHAR = "$c.";
71
72 private static final String DEFAULT_INTEGER = "$i.";
73
74 private static final String DEFAULT_REAL = "$r.";
75
76 private static final String DEFAULT_ITEM = "$ip.";
77
78 private static final String DEFAULT_FRAME = "$fp.";
79
80 private static final String DEFAULT_ASSOCIATION = "$ap.";
81
82 private static final String EXIT_TEXT = "exitall";
83
84 private static enum Status {
85 Exit, OK, Break, Continue, Return, TrueIf, FalseIf;
86 };
87
88 private static final String BREAK2_TEXT = "exitrepeat";
89
90 private static final String BREAK_TEXT = "break";
91
92 private static final String CONTINUE2_TEXT = "nextrepeat";
93
94 private static final String CONTINUE_TEXT = "continue";
95
96 private static final String RETURN_TEXT = "return";
97
98 private static final String LOOP_TEXT = "repeat";
99
100 private static final String TOKEN_SEPARATOR = " +";
101
102 public static final String RUN_FRAME_ACTION = "runframe";
103
104 public static final String DEBUG_FRAME_ACTION = "debugframe";
105
106 /**
107 * Keeps track of how many simple programs are running. Used to check if
108 * simple should read in keyboard input. Or if the keyboard input should be
109 * handled normally by Expeditee.
110 */
111 private static int _programsRunning = 0;
112
113 /**
114 * This flag is set to true if Simple should hijack keyboard input from
115 * Expeditee
116 */
117 private static boolean _consumeKeyboardInput = false;
118
119 public static void ProgramFinished() {
120 _programsRunning--;
121 _stop = false;
122 }
123
124 private static LinkedList<Character> _KeyStrokes = new LinkedList<Character>();
125
126 private static boolean _stop;
127
128 private static Agent _agent = null;
129
130 private static boolean _step;
131
132 private static int _stepPause = -1;
133
134 private static Color _stepColor;
135
136 private static boolean _nextStatement;
137
138 public static void KeyStroke(char c) {
139 _KeyStrokes.add(c);
140 }
141
142 public static boolean isProgramRunning() {
143 return _programsRunning > 0;
144 }
145
146 public static boolean consumeKeyboardInput() {
147 return _consumeKeyboardInput && _programsRunning > 0;
148 }
149
150 public static void NewSimpleTest() {
151 Frame newSimpleTest = FrameIO.CreateFrame(DisplayIO.getCurrentFrame()
152 .getFramesetName(), "Test", null);
153 List<String> actions = new ArrayList<String>();
154 actions.add(RUN_FRAME_ACTION);
155 newSimpleTest.getTitleItem().setActions(actions);
156 FrameUtils.DisplayFrame(newSimpleTest, true);
157 MessageBay.displayMessage("New test created");
158 }
159
160 public static void NextTest() {
161 Frame next = DisplayIO.getCurrentFrame();
162 do {
163 next = FrameIO.LoadNext(next);
164 } while (next != null && !next.isTestFrame());
165 FrameUtils.DisplayFrame(next, true);
166 }
167
168 public static void PreviousTest() {
169 Frame prev = DisplayIO.getCurrentFrame();
170 do {
171 prev = FrameIO.LoadPrevious(prev);
172 } while (prev != null && !prev.isTestFrame());
173
174 FrameUtils.DisplayFrame(prev, true);
175 }
176
177 public static void LastTest() {
178 Frame next = FrameIO.LoadLast();
179 Frame lastTest = null;
180 do {
181 // check if its a test frame
182 if (next != null && next.isTestFrame()) {
183 lastTest = next;
184 break;
185 }
186
187 next = FrameIO.LoadPrevious(next);
188 } while (next != null);
189
190 FrameUtils.DisplayFrame(lastTest, true);
191 }
192
193 public static void RunSimpleTests(String frameset) {
194 RunSimpleTests(frameset, false, true);
195 }
196
197 public static void RunSimpleTestsVerbose(String frameset) {
198 RunSimpleTests(frameset, true, true);
199 }
200
201 private String _frameset;
202
203 private static boolean _verbose = false;
204
205 public Simple(String frameset, boolean verbose) {
206 _frameset = frameset;
207 _verbose = verbose;
208 }
209
210 public void run() {
211 runSuite();
212 }
213
214 public boolean runSuite() {
215 int testsPassed = 0;
216 int testsFailed = 0;
217
218 FrameIO.SaveFrame(DisplayIO.getCurrentFrame(), false);
219 MessageBay.displayMessage("Starting test suite: " + _frameset,
220 Color.CYAN);
221
222 // Get the next number in the inf file for the _frameset
223 int lastFrameNo = FrameIO.getLastNumber(_frameset);
224
225 // Loop through all the valid frames in the _frameset
226 for (int i = 1; i <= lastFrameNo; i++) {
227 String nextFrameName = _frameset + i;
228 Frame nextFrame = FrameIO.LoadFrame(nextFrameName);
229 if (nextFrame == null)
230 continue;
231 Text frameTitle = nextFrame.getTitleItem();
232 if (frameTitle == null)
233 continue;
234 // Run the frames with the RunFrame action on the title
235 Text title = frameTitle.copy();
236 List<String> actions = title.getAction();
237 if (actions == null || title.isAnnotation())
238 continue;
239 if (actions.get(0).toLowerCase().equals("runframe")) {
240 boolean passed = true;
241 String errorMessage = null;
242 try {
243 title.setLink(nextFrameName);
244 // TODO add the ability to run a setup frame
245 // which sets up variables to be used in all
246 // tests
247 AgentStats.reset();
248 _KeyStrokes.clear();
249 _programsRunning++;
250 Context context = new Context();
251 RunFrameAndReportError(title, context);
252 _programsRunning--;
253 // if the throws exception annotation is on the frame then
254 // it passes only if an exception is thrown
255 if (title.getParentOrCurrentFrame().hasAnnotation(
256 "ThrowsException")) {
257 errorMessage = "Expected exception " + title.toString();
258 passed = false;
259 }
260 } catch (Exception e) {
261 _programsRunning--;
262 if (!title.getParentOrCurrentFrame().hasAnnotation(
263 "ThrowsException")) {
264 errorMessage = e.getMessage();
265 passed = false;
266 }
267 }
268 if (passed) {
269 if (_verbose)
270 MessageBay.displayMessage("Test passed: "
271 + title.toString(), Item.GREEN);
272 testsPassed++;
273 } else {
274 testsFailed++;
275 // Print out the reason for failed tests
276 MessageBay.linkedErrorMessage(errorMessage);
277 if (Simple._stop) {
278 Simple._stop = false;
279 return false;
280 }
281 }
282 }
283 }
284 // The statement below assumes there are no other programs running at
285 // the same time
286 assert (_programsRunning == 0);
287 // Report the number of test passed and failed
288 MessageBay.displayMessage(
289 "Total tests: " + (testsPassed + testsFailed), Color.CYAN);
290 if (testsPassed > 0)
291 MessageBay.displayMessage("Passed: " + testsPassed, Item.GREEN);
292 if (testsFailed > 0)
293 MessageBay.displayMessage("Failed: " + testsFailed, Color.RED);
294 // Remove items from the cursor...
295 FreeItems.getInstance().clear();
296
297 return testsFailed == 0;
298 }
299
300 /**
301 * Runs a suite of tests stored in a given frameset.
302 *
303 * @param frameset
304 * @param verbose
305 * @param newThread
306 * false if tests should be run on the current frame
307 */
308 public static void RunSimpleTests(String frameset, boolean verbose,
309 boolean newThread) {
310 _stop = false;
311 Simple testSuite = new Simple(frameset, verbose);
312 if (newThread) {
313 Thread t = new Thread(testSuite);
314 t.setPriority(Thread.MIN_PRIORITY);
315 t.start();
316 } else {
317 if (!testSuite.runSuite()) {
318 throw new RuntimeException(frameset + " failed");
319 }
320 }
321
322 }
323
324 private static void RunFrame(Text current, boolean acceptKeyboardInput,
325 boolean step, int pause, Color color) {
326 try {
327 DisplayIO.addToBack(current.getParent());
328
329 _stepColor = color == null ? Color.green : color;
330 _stepColor = new Color(_stepColor.getRed(), _stepColor.getGreen(),
331 _stepColor.getBlue(), 50);
332 _stepPause = pause;
333 _step = step;
334 _consumeKeyboardInput = acceptKeyboardInput;
335 FrameIO.SaveFrame(DisplayIO.getCurrentFrame(), true);
336
337 // an item without a link signals to run the current frame
338 if (current.getLink() == null) {
339 // Make a copy but hide it
340 current = current.copy();
341 current.setLink(DisplayIO.getCurrentFrame().getName());
342 }
343
344 _KeyStrokes.clear();
345
346 Thread t = new Thread(current);
347 t.setPriority(Thread.MIN_PRIORITY);
348 t.start();
349 } catch (Exception e) {
350 }
351 }
352
353 public static void RunFrame(Text current, boolean acceptKeyboardInput) {
354 RunFrame(current, acceptKeyboardInput, false, 0, null);
355 }
356
357 public static void RunFrame(Text current) {
358 RunFrame(current, false);
359 }
360
361 /**
362 * At present programs which accept keyboard input can not be debugged.
363 *
364 * @param current
365 * @param pause
366 */
367 public static void DebugFrame(Text current, float pause, Color color) {
368 if (isProgramRunning()) {
369 stop();
370 }
371 RunFrame(current, false, true, Math.round(pause * 1000), color);
372 }
373
374 /**
375 * At present programs which accept keyboard input can not be debugged.
376 *
377 * @param current
378 * @param pause
379 * the time to pause between
380 */
381 public static void DebugFrame(Text current, float pause) {
382 DebugFrame(current, pause, null);
383 }
384
385 public static void DebugFrame(Text current) {
386 DebugFrame(current, -1.0F, null);
387 }
388
389 private static void FlagError(Item item) {
390 FrameUtils.DisplayFrame(item.getParent().getName(), true);
391 item.setHighlightMode(HighlightMode.Normal);
392 item.setHighlightColor(Color.CYAN);
393 FrameIO.SaveFrame(item.getParent());
394 }
395
396 /**
397 * Runs a simple code begining on a frame linked to by the specified item
398 * parametre.
399 *
400 * @param current
401 * the item that is linked to the frame to be run.
402 */
403 public static Status RunFrameAndReportError(Item current, Context context)
404 throws Exception {
405 // the item must link to a frame
406 if (current.getLink() == null) {
407 throw new Exception("Could not run unlinked item: "
408 + current.toString());
409 }
410
411 Frame child = FrameIO.LoadFrame(current.getAbsoluteLink());
412
413 // Create frame variables for each linked annotation item on the frame
414 // which has a single word of text corresponding to the variable name
415 for (Text text : child.getAnnotationItems()) {
416 String link = text.getAbsoluteLink();
417 if (link == null)
418 continue;
419 Frame frame = FrameIO.LoadFrame(link);
420 if (frame == null)
421 continue;
422 // Now save the frame as a variable
423 String varName = text.getText().substring(1).trim();
424 if (varName.indexOf(' ') > 0)
425 continue;
426 context.getPointers().setObject(SPointer.framePrefix + varName,
427 frame);
428 context.getPointers().setObject(SPointer.itemPrefix + varName,
429 frame.getTitleItem());
430 context.getPrimitives().add(SString.prefix + varName,
431 new SString(frame.getName()));
432 }
433
434 if (_step) {
435 if (child != DisplayIO.getCurrentFrame()) {
436 DisplayIO.setCurrentFrame(child, true);
437 }
438 DisplayIO.addToBack(child);
439 }
440
441 AgentStats.FrameExecuted();
442
443 // if the frame could not be loaded
444 if (child == null) {
445 throw new Exception("Could not load item link: "
446 + current.toString());
447 }
448
449 // loop through non-title, non-name, text items
450 List<Text> body = child.getBodyTextItems(false);
451
452 // if no item was found
453 if (body.size() == 0)
454 throw new Exception("No code to be executed: " + current.toString());
455
456 Status lastItemStatus = Status.OK;
457 for (Text item : body) {
458 AgentStats.ItemExecuted();
459 try {
460 Color oldColor = item.getBackgroundColor();
461 if (_step) {
462 pause(item);
463 }
464 lastItemStatus = RunItem(item, context, lastItemStatus);
465 if (_step) {
466 if (item.getLink() == null) {
467 item.setBackgroundColor(oldColor);
468 } else {
469 item.setHighlightMode(Item.HighlightMode.None);
470 }
471 }
472
473 if (lastItemStatus != Status.OK) {
474 if (lastItemStatus != Status.TrueIf
475 && lastItemStatus != Status.FalseIf) {
476 if (_step) {
477 DisplayIO.removeFromBack();
478 }
479 return lastItemStatus;
480 }
481 }
482 } catch (ArrayIndexOutOfBoundsException e) {
483 FlagError(item);
484 throw new Exception("Too few parametres: " + item.toString());
485 } catch (NullPointerException e) {
486 FlagError(item);
487 throw new Exception("Null pointer exception: "
488 + item.toString());
489 } catch (RuntimeException e) {
490 FlagError(item);
491 throw new Exception(e.getMessage() + " " + item.toString());
492 } catch (Exception e) {
493 throw new Exception(e.getMessage());
494 }
495 }
496
497 if (_step) {
498 DisplayIO.removeFromBack();
499 if (DisplayIO.getCurrentFrame() != current.getParent())
500 DisplayIO.setCurrentFrame(current.getParent(), true);
501 }
502
503 return Status.OK;
504 }
505
506 /**
507 * @param item
508 * @param oldColor
509 * @throws Exception
510 * @throws InterruptedException
511 */
512 private static void pause(Text item) throws Exception, InterruptedException {
513 if (!_step)
514 return;
515
516 Color oldColor = item.getBackgroundColor();
517 item.setBackgroundColor(_stepColor);
518 item.setHighlightMode(Item.HighlightMode.None);
519
520 // Make sure we are on the frame with this item
521 Frame parent = item.getParentOrCurrentFrame();
522 if (!parent.equals(DisplayIO.getCurrentFrame())) {
523 DisplayIO.setCurrentFrame(parent, true);
524 }
525
526 FrameGraphics.Repaint();
527
528 int timeRemaining;
529 if (_stepPause < 0)
530 timeRemaining = Integer.MAX_VALUE;
531 else
532 timeRemaining = _stepPause;
533
534 while (timeRemaining > 0 && !_nextStatement) {
535 if (_stop) {
536 item.setBackgroundColor(oldColor);
537 item.setHighlightMode(HighlightMode.Normal, _stepColor);
538 throw new Exception("Program terminated");
539 }
540 Thread.sleep(DefaultAgent.TIMER_RESOLUTION);
541 timeRemaining -= DefaultAgent.TIMER_RESOLUTION;
542 }
543 _nextStatement = false;
544 // Turn off the highlighting
545 item.setBackgroundColor(oldColor);
546 }
547
548 private static void pause(double time) throws Exception {
549 for (int i = 0; i < time * 10; i++) {
550 if (_stop) {
551 throw new Exception("Program terminated");
552 }
553 Thread.yield();
554 Thread.sleep(100);
555 }
556 }
557
558 /**
559 * This method should be modified to parse strings correctly
560 *
561 * @param statement
562 * @return
563 */
564 private static String[] parseStatement(Text code) throws Exception {
565 String statement = code.getText().trim();
566 ArrayList<String> tokens = new ArrayList<String>();
567
568 // At the moment annotation items are ignored by the interpreter
569 // // Check special annotation tags for programs
570 // if (statement.length() > 0 && statement.charAt(0) == '@') {
571 // statement = statement.toLowerCase();
572 // // Flags the next unit test as being required to throw an exception
573 // if (statement.equals("@throwsexception")) {
574 // code.getParentOrCurrentFrame().setThrowsException(true);
575 // }
576 // return null;
577 // }
578
579 for (int i = 0; i < statement.length(); i++) {
580 char c = statement.charAt(i);
581 // ignore spaces
582 if (c != ' ') {
583 int startOfToken = i;
584 if (c == '\"') {
585 int endOfToken = statement.length() - 1;
586 // find the end of the string literal
587 while (statement.charAt(endOfToken) != '\"')
588 endOfToken--;
589 if (endOfToken > startOfToken) {
590 tokens.add(statement.substring(startOfToken,
591 endOfToken + 1));
592 } else {
593 throw new RuntimeException("Expected matching \" ");
594 }
595 break;
596 } else if (c == '#' || c == '/') {
597 break;
598 } else {
599 // read in a normal token
600 while (++i < statement.length()
601 && statement.charAt(i) != ' ')
602 ;
603 tokens.add(statement.substring(startOfToken, i)
604 .toLowerCase());
605 }
606 }
607 }
608
609 String[] a = new String[tokens.size()];
610 a = tokens.toArray(a);
611 code.setProcessedText(a);
612 return a;
613 }
614
615 /**
616 * Runs a SIMPLE procedure statement.
617 *
618 * @param tokens
619 * the parsed Call statement.
620 * @param code
621 * the expeditee item containing the procedure call and the link
622 * to the frame with the procedure code.
623 * @param context
624 * the current context from which the procedure call is being
625 * made.
626 * @throws Exception
627 * when errors occur in running the procedure.
628 */
629 private static Status Call(String[] tokens, Item code, Context context)
630 throws Exception {
631 // Check that the call statement is linked
632 if (code.getLink() == null)
633 throw new Exception("Unlinked call statement: " + code.toString());
634
635 Frame procedure = FrameIO.LoadFrame(code.getAbsoluteLink());
636
637 // Add call to the start of the title if it doesnt exist
638 // This makes the call and signature tokens counts match
639 String procedureTitle = procedure.getTitleItem().getFirstLine();
640 if (!procedureTitle.toLowerCase().startsWith("call "))
641 procedureTitle = "call " + procedureTitle;
642
643 // Check that the calling statement matches the procedure
644 // signature
645 String[] procedureSignature = procedureTitle.split(TOKEN_SEPARATOR);
646
647 // Check for the right amount of parametres
648 if (procedureSignature.length < tokens.length)
649 throw new Exception("Call statement has too many parametres: "
650 + code.toString());
651 else if (procedureSignature.length > tokens.length)
652 throw new Exception("Call statement has too few parametres: "
653 + code.toString());
654 // else if (procedureSignature[1].equals(tokens[1]))
655 // throw new Exception("Call statement and procedure name dont match: "
656 // + code.toString());
657
658 // create the new context for the sub procedure
659 Context newContext = new Context();
660 // Check that the types/prefixes match
661 for (int i = 2; i < tokens.length; i++) {
662 // TODO allow for auto casting of primitives
663 if (tokens[i].substring(1, 2).equals(
664 procedureSignature[i].substring(1, 2))) {
665 // Add the variables to the new context
666 if (Primitives.isPrimitive(tokens[i])) {
667 try {
668 // try and get the value for the variable
669 SPrimitive p = context.getPrimitives().getVariable(
670 tokens[i]);
671 newContext.getPrimitives()
672 .add(procedureSignature[i], p);
673 } catch (Exception e) {
674 // If an exception occurs the variable doesnt
675 // exist in the current context
676 // So the variable must be added to both context
677 context.getPrimitives().add(tokens[i], new SString(""));
678 newContext.getPrimitives().add(procedureSignature[i],
679 new SString(""));
680 }
681 } else if (Pointers.isPointer(tokens[i])) {
682 try {
683 // try and get the value for the variable
684 SPointer p = context.getPointers().getVariable(
685 tokens[i]);
686 newContext.getPointers().add(procedureSignature[i], p);
687 } catch (Exception e) {
688 // If an exception occurs the variable doesnt
689 // exist in the current context
690 // So the variable must be added to both context
691 context.getPointers().setObject(tokens[i], null);
692 newContext.getPointers().setObject(
693 procedureSignature[i], null);
694 }
695 } else
696 throw new Exception("Unrecognised variable type: "
697 + tokens[i] + " in " + code.toString());
698 } else
699 throw new IncorrectTypeException(procedureSignature[i], i);
700 }
701
702 // Follow the link and Run the code for the procedure
703 Status result = RunFrameAndReportError(code, newContext);
704 // If a return statement ends the procedure then we accept this as
705 // normal execution
706 switch (result) {
707 case Return:
708 result = Status.OK;
709 break;
710 case Break:
711 throw new Exception(BREAK_TEXT + " statement without matching "
712 + LOOP_TEXT + " in " + code.toString());
713 case Continue:
714 throw new Exception("");
715 }
716
717 // Now copy the values from the procedure context into the
718 // current context
719 for (int i = 2; i < tokens.length; i++) {
720 try {
721 if (Primitives.isPrimitive(tokens[i])) {
722 // try and get the value for the variable
723 SVariable p = context.getPrimitives()
724 .getVariable(tokens[i]);
725 SVariable newP = newContext.getPrimitives().getVariable(
726 procedureSignature[i]);
727 p.setValue(newP);
728 } else {
729 // try and get the value for the variable
730 SVariable p = context.getPointers().getVariable(tokens[i]);
731 SVariable newP = newContext.getPointers().getVariable(
732 procedureSignature[i]);
733 p.setValue(newP);
734 }
735 } catch (Exception e) {
736 assert (false);
737 }
738 }
739
740 return result;
741 }
742
743 /**
744 * Runs a text item on a frame as a SIMPLE statement. The statement is
745 * parsed and if it is a recognised SIMPLE keyword or procedure the code is
746 * executed.
747 *
748 * @param code
749 * the item containing the code to be executed.
750 * @param context
751 * @return
752 * @throws Exception
753 */
754 private static Status RunItem(Text code, Context context,
755 Status lastItemStatus) throws Exception {
756 if (_stop) {
757 throw new Exception("Program terminated");
758 }
759
760 String[] tokens = code.getProcessedText();
761
762 if (tokens == null) {
763 tokens = parseStatement(code);
764 }
765
766 // Annotation items are ignored after parsing running options
767 if (tokens == null) {
768 return Status.OK;
769 // Comments without links are ignored
770 } else if (tokens.length == 0) {
771 if (code.getLink() == null)
772 return Status.OK;
773 else
774 return RunFrameAndReportError(code, context);
775 }
776
777 // At present only set statements can have literals so they
778 // are the only statements that we have to worry about string
779 // literals
780 if (tokens[0].equals("call") && tokens.length >= 2) {
781 return Call(tokens, code, context);
782 // Check if the user wants to display a message
783 // Check for set statements
784 } else if (tokens[0].startsWith("calculatestring")) {
785 assertMinParametreCount(tokens, 1);
786 String toCalculate = context.getPrimitives().getStringValue(
787 tokens[1]);
788 boolean result = true;
789 String error = "";
790 ExpediteeJEP myParser = new ExpediteeJEP();
791 // Add the variables in the system
792 context.getPrimitives().addToParser(myParser);
793 Node equation = myParser.parseExpression(toCalculate);
794 // TODO get the answer
795 if (equation == null) {
796 result = false;
797 error = myParser.getErrorInfo().replace("\n", "");
798 } else {
799 double value = myParser.getValue();
800 if (myParser.hasError()) {
801 result = false;
802 error = myParser.getErrorInfo().replace("\n", "");
803 } else {
804 // Add a new variable if its an assignment statement
805 String newVar = myParser.getNewVariable();
806 if (newVar.length() > 0) {
807 try {
808 context.getPrimitives().setValue(newVar,
809 new SReal(value));
810 } catch (IncorrectTypeException e) {
811 result = false;
812 error = e.getMessage();
813 }
814 }
815 if (tokens.length > 2) {
816 context.getPrimitives().setValue(tokens[2],
817 new SReal(value));
818 }
819 }
820 }
821 // Set the result variable if there is one
822 if (tokens.length > 3) {
823 context.getPrimitives().setValue(tokens[3],
824 new SBoolean(result));
825 // Set the result variable if there is one
826 if (tokens.length > 4 && !result) {
827 context.getPrimitives().setValue(tokens[4], error);
828 }
829 }
830 } else if (tokens[0].startsWith("calculateitem")) {
831 assertMinParametreCount(tokens, 1);
832 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
833 Item item = (Item) context.getPointers().getVariable(tokens[1])
834 .getValue();
835 Frame frame = null;
836 if (tokens.length > 2) {
837 assertVariableType(tokens[2], 2, SPointer.framePrefix);
838 frame = (Frame) context.getPointers().getVariable(tokens[2])
839 .getValue();
840 }
841 Misc.calculate(frame, item);
842 } else if (tokens[0].startsWith("issearchpatternvalid")) {
843 assertExactParametreCount(tokens, 2);
844 boolean result = true;
845 try {
846 Pattern.compile(context.getPrimitives().getStringValue(
847 tokens[1]));
848 } catch (Exception e) {
849 result = false;
850 }
851 context.getPrimitives().setValue(tokens[2], new SBoolean(result));
852 } else if (tokens[0].startsWith("search")) {
853 if (tokens[0].equals("searchstr")) {
854 assertExactParametreCount(tokens, 5);
855 String searchStr = context.getPrimitives().getStringValue(
856 tokens[1]);
857 String pattern = context.getPrimitives().getStringValue(
858 tokens[2]);
859 String[] result = searchStr.split(pattern, 2);
860 boolean bFound = result.length > 1;
861 context.getPrimitives().setValue(tokens[3],
862 new SBoolean(bFound));
863 if (bFound) {
864 context.getPrimitives().setValue(tokens[4],
865 new SInteger(result[0].length() + 1));
866 context.getPrimitives().setValue(
867 tokens[5],
868 new SInteger(searchStr.length()
869 - result[1].length()));
870 }
871 } else if (tokens[0].equals("searchitem")) {
872 assertExactParametreCount(tokens, 5);
873 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
874 boolean bFound = false;
875 Item searchItem = (Item) context.getPointers().getVariable(
876 tokens[1]).getValue();
877 if (searchItem instanceof Text) {
878 bFound = context.searchItem((Text) searchItem, context
879 .getPrimitives().getStringValue(tokens[2]), null,
880 tokens[4], tokens[5], null);
881 }
882 context.getPrimitives().setValue(tokens[3],
883 new SBoolean(bFound));
884 } else if (tokens[0].equals("searchframe")) {
885 assertExactParametreCount(tokens, 6);
886 assertVariableType(tokens[1], 1, SPointer.framePrefix);
887 assertVariableType(tokens[4], 4, SPointer.itemPrefix);
888 Frame frameToSearch = (Frame) context.getPointers()
889 .getVariable(tokens[1]).getValue();
890 boolean bFound = false;
891 for (Text itemToSearch : frameToSearch.getTextItems()) {
892 bFound = context.searchItem(itemToSearch, context
893 .getPrimitives().getStringValue(tokens[2]),
894 tokens[4], tokens[5], tokens[6], null);
895 if (bFound)
896 break;
897 }
898 context.getPrimitives().setValue(tokens[3],
899 new SBoolean(bFound));
900 } else if (tokens[0].equals("searchframeset")) {
901 assertMinParametreCount(tokens, 3);
902
903 String frameset = context.getPrimitives().getStringValue(
904 tokens[1]);
905 boolean bReplace = false;
906 if (tokens.length > 4) {
907 bReplace = context.getPrimitives().getBooleanValue(
908 tokens[4]);
909 }
910 String replacementString = null;
911 // If in replacement mode get the string to replace the
912 // searchPattern with
913 if (bReplace) {
914 if (tokens.length > 5) {
915 replacementString = context.getPrimitives()
916 .getStringValue(tokens[5]);
917 } else {
918 replacementString = "";
919 }
920 }
921 String resultsFrameset = context.getPrimitives()
922 .getStringValue(tokens[3]);
923 String pattern = context.getPrimitives().getStringValue(
924 tokens[2]);
925 long firstFrame = 1;
926 long maxFrame = Long.MAX_VALUE;
927 if(tokens.length > 7){
928 firstFrame = context.getPrimitives().getIntegerValue(tokens[7]);
929 if(tokens.length > 8){
930 maxFrame = context.getPrimitives().getIntegerValue(tokens[8]);
931 }
932 }
933
934 SearchAgent searchAgent = new SearchFrameset(firstFrame, maxFrame);
935 searchAgent.initialise(null, null, frameset, resultsFrameset,
936 replacementString, pattern);
937 _agent = searchAgent;
938 searchAgent.run();
939 _agent = null;
940
941 if (tokens.length > 6) {
942 context.getPrimitives().setValue(tokens[6],
943 searchAgent.getResultsFrameName());
944 }
945 } else if (tokens[0].equals("searchtree")) {
946 assertMinParametreCount(tokens, 3);
947
948 String topFrameName = context.getPrimitives().getStringValue(
949 tokens[1]);
950 boolean bReplace = false;
951 if (tokens.length > 4) {
952 bReplace = context.getPrimitives().getBooleanValue(
953 tokens[4]);
954 }
955 String replacementString = null;
956 // If in replacement mode get the string to replace the
957 // searchPattern with
958 if (bReplace) {
959 if (tokens.length > 5) {
960 replacementString = context.getPrimitives()
961 .getStringValue(tokens[5]);
962 } else {
963 replacementString = "";
964 }
965 }
966 String resultsFrameset = context.getPrimitives()
967 .getStringValue(tokens[3]);
968 String pattern = context.getPrimitives().getStringValue(
969 tokens[2]);
970 SearchAgent searchAgent = new SearchTree();
971 _agent = searchAgent;
972 searchAgent.initialise(null, null, topFrameName,
973 resultsFrameset, replacementString, pattern);
974 searchAgent.run();
975 _agent = null;
976 if (tokens.length > 6) {
977 context.getPrimitives().setValue(tokens[6],
978 searchAgent.getResultsFrameName());
979 }
980 } else {
981 throw new Exception("Unsupported search command: "
982 + code.toString());
983 }
984 } else if (tokens[0].startsWith("set")) {
985 if (tokens[0].equals("set")) {
986 try {
987 // Check if we are setting variable to variable
988 if (tokens[2].startsWith(SVariable.prefix)
989 && tokens.length == 3) {
990 context.getPrimitives().set(tokens[1], tokens[2]);
991 }
992 // Otherwise we are setting a variable with a literal
993 else {
994 // check for strings enclosed in quotes
995 if (tokens[2].startsWith("\"")) {
996 context.getPrimitives().setValue(
997 tokens[1],
998 new SString(tokens[2].substring(1,
999 tokens[2].length() - 1)));
1000 // set a literal
1001 } else if (tokens.length == 3) {
1002 context.getPrimitives().setValue(tokens[1],
1003 tokens[2]);
1004 }
1005 }
1006 } catch (Exception e) {
1007 throw new RuntimeException(e.getMessage());
1008 }
1009 } else if (tokens[0].equals("setassociation")) {
1010 assertExactParametreCount(tokens, 3);
1011
1012 Map<String, String> map = (Map<String, String>) context
1013 .getPointers().getVariable(tokens[1]).getValue();
1014 String attribute = context.getPrimitives().getStringValue(
1015 tokens[2]);
1016 String value = context.getPrimitives()
1017 .getStringValue(tokens[3]);
1018 map.put(attribute, value);
1019 } else if (tokens[0].equals("setframevalue")) {
1020 assertMinParametreCount(tokens, 3);
1021 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1022
1023 // Get the attribute to be searched for on the target frame
1024 Frame targetFrame = (Frame) context.getPointers().getVariable(
1025 tokens[1]).getValue();
1026 String targetAttribute = context.getPrimitives()
1027 .getStringValue(tokens[2]).toLowerCase()
1028 + ":";
1029 String value = context.getPrimitives()
1030 .getStringValue(tokens[3]);
1031 Boolean found = false;
1032 Text attributeItem = null;
1033 Item valueItem = null;
1034 // Begin the search
1035 for (Text text : targetFrame.getTextItems()) {
1036 String s = text.getText().toLowerCase();
1037
1038 if (s.startsWith(targetAttribute)) {
1039 attributeItem = text;
1040 AttributeUtils.replaceValue(attributeItem, value);
1041 found = true;
1042 break;
1043 }
1044 }
1045 // Keep looking for a matching value nearby if we found an
1046 // attribute without the value in the same item
1047 if (!found && attributeItem != null) {
1048 Point2D.Float endPoint = attributeItem
1049 .getParagraphEndPosition();
1050
1051 for (Text text : targetFrame.getTextItems()) {
1052 Point startPoint = text.getPosition();
1053 if (Math.abs(startPoint.y - endPoint.y) < 10
1054 && Math.abs(startPoint.x - endPoint.x) < 20) {
1055 found = true;
1056 valueItem = text;
1057 text.setText(value);
1058 break;
1059 }
1060 }
1061 }
1062
1063 // Set the values of the output parametres
1064 if (tokens.length > 4) {
1065 context.getPrimitives().setValue(tokens[4],
1066 new SBoolean(found));
1067 if (tokens.length > 5) {
1068 context.getPointers().setObject(tokens[5],
1069 attributeItem);
1070 if (tokens.length > 6) {
1071 context.getPointers().setObject(tokens[6],
1072 valueItem);
1073 }
1074 }
1075 }
1076 } else if (tokens[0].startsWith("setitem")) {
1077 if (tokens[0].equals("setitemposition")) {
1078 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1079 // assertPrimitiveType(tokens[2], 2);
1080 // assertPrimitiveType(tokens[3], 3);
1081 Item item = (Item) context.getPointers().getVariable(
1082 tokens[1]).getValue();
1083 item.setPosition(context.getPrimitives().getVariable(
1084 tokens[2]).integerValue().intValue(), context
1085 .getPrimitives().getVariable(tokens[3])
1086 .integerValue().intValue());
1087 } else if (tokens[0].equals("setitemthickness")) {
1088 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1089 // assertPrimitiveType(tokens[2], 2);
1090 Item item = (Item) context.getPointers().getVariable(
1091 tokens[1]).getValue();
1092 item.setThickness(context.getPrimitives().getVariable(
1093 tokens[2]).integerValue().intValue());
1094 } else if (tokens[0].equals("setitemwidth")) {
1095 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1096 // assertPrimitiveType(tokens[2], 2);
1097 Item item = (Item) context.getPointers().getVariable(
1098 tokens[1]).getValue();
1099 item.setWidth(context.getPrimitives()
1100 .getVariable(tokens[2]).integerValue().intValue());
1101 } else if (tokens[0].equals("setitemsize")) {
1102 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1103 // assertPrimitiveType(tokens[2], 2);
1104 Item item = (Item) context.getPointers().getVariable(
1105 tokens[1]).getValue();
1106 item.setSize(context.getPrimitives().getVariable(tokens[2])
1107 .integerValue().intValue());
1108 } else if (tokens[0].equals("setitemlink")) {
1109 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1110 // assertPrimitiveType(tokens[2], 2);
1111 Item item = (Item) context.getPointers().getVariable(
1112 tokens[1]).getValue();
1113 item.setLink(context.getPrimitives().getVariable(tokens[2])
1114 .stringValue());
1115 } else if (tokens[0].equals("setitemdata")) {
1116 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1117 // assertPrimitiveType(tokens[2], 2);
1118 Item item = (Item) context.getPointers().getVariable(
1119 tokens[1]).getValue();
1120 item.setData(context.getPrimitives().getVariable(tokens[2])
1121 .stringValue());
1122 } else if (tokens[0].equals("setitemaction")) {
1123 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1124 // assertPrimitiveType(tokens[2], 2);
1125 Item item = (Item) context.getPointers().getVariable(
1126 tokens[1]).getValue();
1127 item.setAction(context.getPrimitives().getVariable(
1128 tokens[2]).stringValue());
1129 } else if (tokens[0].equals("setitemfillcolor")) {
1130 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1131 // assertPrimitiveType(tokens[2], 2);
1132 Item item = (Item) context.getPointers().getVariable(
1133 tokens[1]).getValue();
1134 String stringColor = context.getPrimitives().getVariable(
1135 tokens[2]).stringValue();
1136 item.setBackgroundColor((Color) Conversion.Convert(
1137 Color.class, stringColor));
1138 } else if (tokens[0].equals("setitemcolor")) {
1139 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1140 // assertPrimitiveType(tokens[2], 2);
1141 Item item = (Item) context.getPointers().getVariable(
1142 tokens[1]).getValue();
1143 String stringColor = context.getPrimitives().getVariable(
1144 tokens[2]).stringValue();
1145 item.setColor((Color) Conversion.Convert(Color.class,
1146 stringColor, item.getColor()));
1147 } else if (tokens[0].equals("setitemtext")) {
1148 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1149 // assertPrimitiveType(tokens[2], 2);
1150 String newText = context.getPrimitives().getVariable(
1151 tokens[2]).stringValue();
1152 Text textItem = (Text) context.getPointers().getVariable(
1153 tokens[1]).getValue();
1154 textItem.setText(newText);
1155 } else
1156 throw new Exception("Unsupported setItem command: "
1157 + code.toString());
1158 } else if (tokens[0].equals("setstrchar")) {
1159 assertExactParametreCount(tokens, 3);
1160 StringBuffer s = new StringBuffer(context.getPrimitives()
1161 .getStringValue(tokens[1]));
1162 int pos = (int) context.getPrimitives().getIntegerValue(
1163 tokens[2]);
1164 char newChar = context.getPrimitives().getCharacterValue(
1165 tokens[3]);
1166 while (pos > s.length()) {
1167 s.append(newChar);
1168 }
1169 s.setCharAt(pos - 1, newChar);
1170
1171 context.getPrimitives().setValue(tokens[1],
1172 new SString(s.toString()));
1173 } else if (tokens[0].equals("setcharinitem")) {
1174 assertExactParametreCount(tokens, 4);
1175 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1176
1177 int row = (int) context.getPrimitives().getIntegerValue(
1178 tokens[3]) - 1;
1179 int col = (int) context.getPrimitives().getIntegerValue(
1180 tokens[4]) - 1;
1181 char newChar = context.getPrimitives().getCharacterValue(
1182 tokens[2]);
1183 Text item = (Text) context.getPointers().getVariable(tokens[1])
1184 .getValue();
1185 List<String> itemText = item.getTextList();
1186
1187 while (row >= itemText.size()) {
1188 StringBuffer sb = new StringBuffer();
1189 for (int i = 0; i <= col; i++)
1190 sb.append(newChar);
1191 itemText.add(sb.toString());
1192 }
1193 StringBuffer sb = new StringBuffer(itemText.get(row));
1194 while (sb.length() <= col)
1195 sb.append(newChar);
1196 sb.setCharAt(col, newChar);
1197
1198 // set the modified string
1199 itemText.set(row, sb.toString());
1200 item.setTextList(itemText);
1201 }
1202 } else if (tokens[0].startsWith("assert")) {
1203 if (tokens[0].equals("asserttrue")) {
1204 assertExactParametreCount(tokens, 1);
1205 if (!context.getPrimitives().getBooleanValue(tokens[1]))
1206 throw new UnitTestFailedException("true", "false");
1207 } else if (tokens[0].equals("assertfalse")) {
1208 assertExactParametreCount(tokens, 1);
1209 if (context.getPrimitives().getBooleanValue(tokens[1]))
1210 throw new UnitTestFailedException("false", "true");
1211 } else if (tokens[0].equals("assertfail")) {
1212 assertExactParametreCount(tokens, 0);
1213 throw new UnitTestFailedException("pass", "fail");
1214 } else if (tokens[0].equals("assertnull")) {
1215 assertExactParametreCount(tokens, 1);
1216 if (!context.isNull(tokens[1]))
1217 throw new UnitTestFailedException("null", "not null");
1218 } else if (tokens[0].equals("assertnotnull")) {
1219 assertExactParametreCount(tokens, 1);
1220 if (context.isNull(tokens[1]))
1221 throw new UnitTestFailedException("not null", "null");
1222 } else if (tokens[0].equals("assertdefined")) {
1223 assertExactParametreCount(tokens, 1);
1224 if (!context.isDefined(tokens[1]))
1225 throw new UnitTestFailedException("defined", "not defined");
1226 } else if (tokens[0].equals("assertnotdefined")) {
1227 assertExactParametreCount(tokens, 1);
1228 if (context.isDefined(tokens[1]))
1229 throw new UnitTestFailedException("defined", "not defined");
1230 } else if (tokens[0].equals("assertequals")) {
1231 assertExactParametreCount(tokens, 2);
1232 if (!context.getPrimitives().equalValues(tokens[1], tokens[2]))
1233 throw new UnitTestFailedException(context.getPrimitives()
1234 .getStringValue(tokens[1]), context.getPrimitives()
1235 .getStringValue(tokens[2]));
1236 } else if (tokens[0].equals("assertequalframes")) {
1237 assertExactParametreCount(tokens, 2);
1238 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1239 assertVariableType(tokens[2], 2, SPointer.framePrefix);
1240 Frame frame1 = (Frame) context.getPointers().getVariable(
1241 tokens[1]).getValue();
1242 Frame frame2 = (Frame) context.getPointers().getVariable(
1243 tokens[2]).getValue();
1244 // Check that all the items on the frame are the same
1245 List<Item> items1 = frame1.getVisibleItems();
1246 List<Item> items2 = frame2.getVisibleItems();
1247 if (items1.size() != items2.size()) {
1248 throw new UnitTestFailedException(items1.size() + " items",
1249 items2.size() + " items");
1250 } else {
1251 for (int i = 0; i < items1.size(); i++) {
1252 Item i1 = items1.get(i);
1253 Item i2 = items2.get(i);
1254 String s1 = i1.getText();
1255 String s2 = i2.getText();
1256 if (!s1.equals(s2)) {
1257 throw new UnitTestFailedException(s1, s2);
1258 }
1259 }
1260 }
1261 } else if (tokens[0].equals("assertdefined")) {
1262 assertExactParametreCount(tokens, 1);
1263 if (!context.isDefined(tokens[1])) {
1264 throw new UnitTestFailedException(tokens[1] + " exists",
1265 "not defined");
1266 }
1267 } else {
1268 throw new RuntimeException("Invalid Assert statement");
1269 }
1270 } else if (tokens[0].startsWith("goto")) {
1271 String frameNameVar = DEFAULT_STRING;
1272 if (tokens.length > 1) {
1273 assertExactParametreCount(tokens, 1);
1274 frameNameVar = tokens[1];
1275 }
1276 String frameName = context.getPrimitives().getStringValue(
1277 frameNameVar);
1278 NavigationActions.Goto(frameName);
1279 } else if (tokens[0].startsWith("get")) {
1280 if (tokens[0].startsWith("getframe")) {
1281 if (tokens[0].equals("getframevalue")) {
1282 assertMinParametreCount(tokens, 3);
1283 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1284
1285 // Get the attribute to be searched for on the target frame
1286 Frame targetFrame = (Frame) context.getPointers()
1287 .getVariable(tokens[1]).getValue();
1288 String targetAttribute = context.getPrimitives()
1289 .getStringValue(tokens[2]).toLowerCase()
1290 + ":";
1291 Boolean found = false;
1292 String value = "";
1293 Text attributeItem = null;
1294 Item valueItem = null;
1295 // Begin the search
1296 for (Text text : targetFrame.getTextItems()) {
1297 String s = text.getText().toLowerCase();
1298 if (s.startsWith(targetAttribute)) {
1299 attributeItem = text;
1300 value = AttributeUtils.getValue(s);
1301 if (value.length() > 0) {
1302 found = true;
1303 }
1304 break;
1305 }
1306 }
1307 // Keep looking for a matching value nearby if we found an
1308 // attribute without the value in the same item
1309 if (!found && attributeItem != null) {
1310 Point2D.Float endPoint = attributeItem
1311 .getParagraphEndPosition();
1312
1313 for (Text text : targetFrame.getTextItems()) {
1314 Point startPoint = text.getPosition();
1315 if (Math.abs(startPoint.y - endPoint.y) < 10
1316 && Math.abs(startPoint.x - endPoint.x) < 20) {
1317 found = true;
1318 valueItem = text;
1319 value = text.getText();
1320 break;
1321 }
1322 }
1323 }
1324
1325 // Set the values of the output parametres
1326 context.getPrimitives().setValue(tokens[3],
1327 new SString(value));
1328 if (tokens.length > 4) {
1329 context.getPrimitives().setValue(tokens[4],
1330 new SBoolean(found));
1331 if (tokens.length > 5) {
1332 context.getPointers().setObject(tokens[5],
1333 attributeItem);
1334 if (tokens.length > 6) {
1335 context.getPointers().setObject(tokens[6],
1336 valueItem);
1337 }
1338 }
1339 }
1340 } else if (tokens[0].startsWith("getframename")) {
1341 String frameNameVar = DEFAULT_STRING;
1342 String frameVar = DEFAULT_FRAME;
1343
1344 if (tokens.length > 1) {
1345 assertExactParametreCount(tokens, 2);
1346 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1347 frameNameVar = tokens[2];
1348 frameVar = tokens[1];
1349 }
1350 Frame frame = (Frame) context.getPointers().getVariable(
1351 frameVar).getValue();
1352 context.getPrimitives().setValue(frameNameVar,
1353 frame.getName());
1354 } else if (tokens[0].startsWith("getframetitle")) {
1355 String frameTitleVar = DEFAULT_ITEM;
1356 String frameVar = DEFAULT_FRAME;
1357
1358 if (tokens.length > 1) {
1359 assertExactParametreCount(tokens, 2);
1360 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1361 assertVariableType(tokens[2], 2, SPointer.itemPrefix);
1362 frameTitleVar = tokens[2];
1363 frameVar = tokens[1];
1364 }
1365 Frame frame = (Frame) context.getPointers().getVariable(
1366 frameVar).getValue();
1367 context.getPointers().setObject(frameTitleVar,
1368 frame.getTitleItem());
1369 } else if (tokens[0].startsWith("getframefilepath")) {
1370 assertExactParametreCount(tokens, 2);
1371 String frameName = context.getPrimitives().getStringValue(
1372 tokens[1]);
1373 String path = FrameIO.LoadFrame(frameName).path;
1374 String filePath = FrameIO.getFrameFullPathName(path,
1375 frameName);
1376 context.getPrimitives().setValue(tokens[2], filePath);
1377 } else if (tokens[0].equals("getframelog")) {
1378 assertExactParametreCount(tokens, 1);
1379 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1380
1381 String log = SessionStats.getFrameEventList();
1382 Text t;
1383
1384 t = (Text) context.getPointers().getVariable(tokens[1])
1385 .getValue();
1386 t.setText(log);
1387 } else if (tokens[0].equals("getframeitemcount")) {
1388 String frameVar = DEFAULT_FRAME;
1389 String countVar = DEFAULT_INTEGER;
1390 if (tokens.length > 1) {
1391 assertExactParametreCount(tokens, 2);
1392 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1393 frameVar = tokens[1];
1394 countVar = tokens[2];
1395 }
1396 Frame frame = (Frame) context.getPointers().getVariable(
1397 frameVar).getValue();
1398 Integer count = frame.getItems(true).size();
1399 context.getPrimitives().setValue(countVar,
1400 new SInteger(count));
1401 }
1402 } else if (tokens[0].equals("getassociation")) {
1403 assertMinParametreCount(tokens, 3);
1404 Map map = (Map) context.getPointers().getVariable(tokens[1])
1405 .getValue();
1406 String attribute = context.getPrimitives().getStringValue(
1407 tokens[2]);
1408 String newValue = map.get(attribute).toString();
1409 context.getPrimitives().setValue(tokens[3], newValue);
1410 } else if (tokens[0].startsWith("getcurrent")) {
1411 if (tokens[0].equals("getcurrentframe")) {
1412 assertMinParametreCount(tokens, 1);
1413 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1414
1415 Frame currentFrame = DisplayIO.getCurrentFrame();
1416 context.getPointers().setObject(tokens[1], currentFrame);
1417
1418 // check if the user is also after the frameName
1419 if (tokens.length > 2) {
1420 context.getPrimitives().setValue(tokens[2],
1421 new SString(currentFrame.getName()));
1422 }
1423 } else if (tokens[0].equals("getcurrentitem")) {
1424 assertMinParametreCount(tokens, 1);
1425 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1426
1427 Item currentItem = FrameUtils.getCurrentItem();
1428
1429 context.getPointers().setObject(tokens[1], currentItem);
1430
1431 // check if the user is also after line position
1432 if (currentItem != null && currentItem instanceof Text
1433 && tokens.length > 2) {
1434 Text text = (Text) currentItem;
1435 int cursorLinePos = text
1436 .getLinePosition(FrameMouseActions.getY());
1437 context.getPrimitives().setValue(tokens[2],
1438 new SInteger(cursorLinePos + 1));
1439 if (tokens.length > 3) {
1440 int cursorCharPos = text.getCharPosition(
1441 cursorLinePos, DisplayIO.getMouseX())
1442 .getCharIndex();
1443 context.getPrimitives().setValue(tokens[3],
1444 new SInteger(cursorCharPos + 1));
1445 }
1446 }
1447 }
1448 } else if (tokens[0].startsWith("getitem")) {
1449 if (tokens[0].equals("getitemposition")) {
1450 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1451 // assertPrimitiveType(tokens[2], 2);
1452 // assertPrimitiveType(tokens[3], 3);
1453 Point pos = ((Item) context.getPointers().getVariable(
1454 tokens[1]).getValue()).getPosition();
1455 Integer x = pos.x;
1456 Integer y = pos.y;
1457 context.getPrimitives()
1458 .setValue(tokens[2], new SInteger(x));
1459 context.getPrimitives()
1460 .setValue(tokens[3], new SInteger(y));
1461 } else if (tokens[0].equals("getitemthickness")) {
1462 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1463 // assertPrimitiveType(tokens[2], 2);
1464 Float thickness = ((Item) context.getPointers()
1465 .getVariable(tokens[1]).getValue()).getThickness();
1466 context.getPrimitives().setValue(tokens[2],
1467 new SReal(thickness));
1468 } else if (tokens[0].equals("getitemwidth")) {
1469 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1470 // assertPrimitiveType(tokens[2], 2);
1471 Integer width = ((Item) context.getPointers().getVariable(
1472 tokens[1]).getValue()).getWidth();
1473 context.getPrimitives().setValue(tokens[2],
1474 new SInteger(width));
1475 } else if (tokens[0].equals("getitemsize")) {
1476 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1477 // assertPrimitiveType(tokens[2], 2);
1478 Integer size = (int) ((Item) context.getPointers()
1479 .getVariable(tokens[1]).getValue()).getSize();
1480 context.getPrimitives().setValue(tokens[2],
1481 new SInteger(size));
1482 } else if (tokens[0].equals("getitemlink")) {
1483 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1484 // assertPrimitiveType(tokens[2], 2);
1485 String link = ((Item) context.getPointers().getVariable(
1486 tokens[1]).getValue()).getAbsoluteLink();
1487 context.getPrimitives().setValue(tokens[2],
1488 new SString(link));
1489 } else if (tokens[0].equals("getitemdata")) {
1490 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1491 Collection<String> dataList = ((Item) context.getPointers()
1492 .getVariable(tokens[1]).getValue()).getData();
1493 String data = "";
1494 if (dataList.size() > 0)
1495 data = dataList.iterator().next();
1496 context.getPrimitives().setValue(tokens[2],
1497 new SString(data));
1498 } else if (tokens[0].equals("getitemaction")) {
1499 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1500 Collection<String> dataList = ((Item) context.getPointers()
1501 .getVariable(tokens[1]).getValue()).getAction();
1502 String action = "";
1503 if (dataList.size() > 0)
1504 action = dataList.iterator().next();
1505 context.getPrimitives().setValue(tokens[2],
1506 new SString(action));
1507 } else if (tokens[0].equals("getitemfillcolor")) {
1508 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1509 // assertPrimitiveType(tokens[2], 2);
1510 Color itemColor = ((Item) context.getPointers()
1511 .getVariable(tokens[1]).getValue())
1512 .getPaintBackgroundColor();
1513 String color = itemColor.getRed() + " "
1514 + itemColor.getGreen() + " " + itemColor.getBlue();
1515 context.getPrimitives().setValue(tokens[2],
1516 new SString(color));
1517 } else if (tokens[0].equals("getitemcolor")) {
1518 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1519 // assertPrimitiveType(tokens[2], 2);
1520 Color itemColor = ((Item) context.getPointers()
1521 .getVariable(tokens[1]).getValue()).getPaintColor();
1522 String color = itemColor.getRed() + " "
1523 + itemColor.getGreen() + " " + itemColor.getBlue();
1524 context.getPrimitives().setValue(tokens[2],
1525 new SString(color));
1526 } else if (tokens[0].equals("getitemtext")) {
1527 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1528 Item item = ((Item) context.getPointers().getVariable(
1529 tokens[1]).getValue());
1530 context.getPrimitives().setValue(
1531 tokens[2],
1532 new SString((item instanceof Text) ? ((Text) item)
1533 .getText() : ""));
1534 } else
1535 throw new Exception("Unsupported getItem command: "
1536 + code.toString());
1537 } else if (tokens[0].equals("getstrchar")) {
1538 assertExactParametreCount(tokens, 3);
1539 String s = context.getPrimitives().getStringValue(tokens[1]);
1540 int pos = (int) context.getPrimitives().getIntegerValue(
1541 tokens[2]);
1542
1543 context.getPrimitives().setValue(tokens[3],
1544 new SCharacter(s.charAt(pos - 1)));
1545 } else if (tokens[0].equals("getstrlength")) {
1546 assertExactParametreCount(tokens, 2);
1547 String s = context.getPrimitives().getStringValue(tokens[1]);
1548
1549 context.getPrimitives().setValue(tokens[2],
1550 new SInteger(s.length()));
1551 } else if (tokens[0].equals("getelapsedtime")) {
1552 assertExactParametreCount(tokens, 1);
1553 context.getPrimitives().setValue(tokens[1],
1554 new SInteger(AgentStats.getMilliSecondsElapsed()));
1555 } else if (tokens[0].equals("getlastnumberinframeset")) {
1556 String framesetNameVar = DEFAULT_STRING;
1557 String countVar = DEFAULT_INTEGER;
1558 if (tokens.length > 1) {
1559 assertMinParametreCount(tokens, 2);
1560 framesetNameVar = tokens[1];
1561 countVar = tokens[2];
1562 }
1563 String frameset = context.getPrimitives().getStringValue(
1564 framesetNameVar);
1565 long count = FrameIO.getLastNumber(frameset);
1566 context.getPrimitives().setValue(countVar, new SInteger(count));
1567 } else if (tokens[0].equals("getlistofframesets")) {
1568 String stringVar = DEFAULT_ITEM;
1569 if (tokens.length > 1) {
1570 assertMinParametreCount(tokens, 1);
1571 stringVar = tokens[1];
1572 }
1573 context.getPrimitives().setValue(stringVar,
1574 FrameIO.getFramesetList());
1575 } else if (tokens[0].equals("getsessionstats")) {
1576 assertExactParametreCount(tokens, 1);
1577 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1578
1579 String stats = SessionStats.getCurrentStats();
1580 Text t = (Text) context.getPointers().getVariable(tokens[1])
1581 .getValue();
1582 t.setText(stats);
1583 } else if (tokens[0].equals("getrandominteger")) {
1584 assertExactParametreCount(tokens, 3);
1585 int lowerBound = (int) context.getPrimitives().getIntegerValue(
1586 tokens[1]);
1587 int upperBound = (int) context.getPrimitives().getIntegerValue(
1588 tokens[2]);
1589 Random random = new Random();
1590 long result = Math.abs(random.nextInt())
1591 % (upperBound - lowerBound) + lowerBound;
1592 context.getPrimitives().setValue(tokens[3],
1593 new SInteger(result));
1594 } else if (tokens[0].equals("getrandomreal")) {
1595 assertExactParametreCount(tokens, 3);
1596 double lowerBound = context.getPrimitives().getDoubleValue(
1597 tokens[1]);
1598 double upperBound = context.getPrimitives().getDoubleValue(
1599 tokens[2]);
1600 Random random = new Random();
1601 double result = random.nextDouble() * (upperBound - lowerBound)
1602 + lowerBound;
1603 context.getPrimitives().setValue(tokens[3], new SReal(result));
1604 } else if (tokens[0].equals("getrandomtextitem")) {
1605 assertExactParametreCount(tokens, 2);
1606 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1607 assertVariableType(tokens[2], 2, SPointer.itemPrefix);
1608 List<Text> items = ((Frame) context.getPointers().getVariable(
1609 tokens[1]).getValue()).getBodyTextItems(false);
1610 Random random = new Random();
1611 int itemIndex = random.nextInt(items.size());
1612 context.getPointers()
1613 .setObject(tokens[2], items.get(itemIndex));
1614 }
1615 } else if (tokens[0].equals("or")) {
1616 for (int i = 1; i < tokens.length - 1; i++) {
1617 if (Primitives.isPrimitive(tokens[i])) {
1618 if (context.getPrimitives().getBooleanValue(tokens[i])) {
1619 context.getPrimitives().setValue(
1620 tokens[tokens.length - 1], new SBoolean(true));
1621 return Status.OK;
1622 }
1623 }
1624 }
1625 context.getPrimitives().setValue(tokens[tokens.length - 1],
1626 new SBoolean(false));
1627 } else if (tokens[0].equals("and")) {
1628 for (int i = 1; i < tokens.length - 1; i++) {
1629 if (Primitives.isPrimitive(tokens[i])) {
1630 if (!context.getPrimitives().getBooleanValue(tokens[i])) {
1631 context.getPrimitives().setValue(
1632 tokens[tokens.length - 1], new SBoolean(false));
1633 return Status.OK;
1634 }
1635 }
1636 }
1637 context.getPrimitives().setValue(tokens[tokens.length - 1],
1638 new SBoolean(true));
1639 } else if (tokens[0].equals("messagelnitem")
1640 || tokens[0].equals("messagelineitem")) {
1641 String itemVar = DEFAULT_ITEM;
1642
1643 if (tokens.length > 1) {
1644 assertExactParametreCount(tokens, 1);
1645 itemVar = tokens[1];
1646 assertVariableType(itemVar, 1, SPointer.itemPrefix);
1647 }
1648 Item message = (Item) context.getPointers().getVariable(itemVar)
1649 .getValue();
1650 try {
1651 MessageBay.displayMessage(((Text) message).copy());
1652 } catch (NullPointerException e) {
1653 MessageBay.displayMessage("null");
1654 } catch (ClassCastException e) {
1655 // Just ignore not text items!
1656 MessageBay.displayMessage(message.toString());
1657 } catch (Exception e) {
1658 // Just ignore other errors
1659 }
1660 } else if (tokens[0].equals("messageln")
1661 || tokens[0].equals("messageline")
1662 || tokens[0].equals("messagelnnospaces")
1663 || tokens[0].equals("messagelinenospaces")
1664 || tokens[0].equals("errorln") || tokens[0].equals("errorline")) {
1665 String message = getMessage(tokens, context, code.toString(),
1666 tokens[0].endsWith("nospaces") ? "" : " ", 1);
1667
1668 if (tokens[0].equals("errorln") || tokens[0].equals("errorline"))
1669 MessageBay.errorMessage(message);
1670 else
1671 MessageBay.displayMessageAlways(message);
1672 } else if (tokens[0].equals("typeatrate")) {
1673 assertMinParametreCount(tokens, 1);
1674 double delay = context.getPrimitives().getDoubleValue(tokens[1]);
1675 String s = getMessage(tokens, context, code.toString(), " ", 2);
1676 for (int i = 0; i < s.length(); i++) {
1677 FrameKeyboardActions.processChar(s.charAt(i), false);
1678 Thread.sleep((int) (delay * 1000));
1679 }
1680 } else if (tokens[0].equals("type") || tokens[0].equals("typenospaces")) {
1681
1682 String s = getMessage(tokens, context, code.toString(), tokens[0]
1683 .equals("type") ? " " : "", 1);
1684 for (int i = 0; i < s.length(); i++) {
1685 FrameKeyboardActions.processChar(s.charAt(i), false);
1686 Thread.sleep(25);
1687 }
1688 } else if (tokens[0].equals("runstring")) {
1689 String codeText = getMessage(tokens, context, code.toString(), " ",
1690 1);
1691 Text dynamicCode = new Text(codeText);
1692 RunItem(dynamicCode, context, Status.OK);
1693 } else if (tokens[0].equals("runoscommand")) {
1694 String command = getMessage(tokens, context, code.toString(), " ",
1695 1);
1696 Runtime.getRuntime().exec(command);
1697 } else if (tokens[0].equals("executeoscommand")) {
1698 String command = getMessage(tokens, context, code.toString(), " ",
1699 1);
1700 try {
1701 Process p = Runtime.getRuntime().exec(command);
1702 MessageBay.displayMessage(command, Color.darkGray);
1703
1704 BufferedReader stdInput = new BufferedReader(
1705 new InputStreamReader(p.getInputStream()));
1706 BufferedReader stdError = new BufferedReader(
1707 new InputStreamReader(p.getErrorStream()));
1708 String message = "";
1709 while ((message = stdInput.readLine()) != null) {
1710 MessageBay.displayMessage(message);
1711 }
1712 while ((message = stdError.readLine()) != null) {
1713 MessageBay.errorMessage(message);
1714 }
1715 } catch (Exception e) {
1716 throw new RuntimeException(e.getMessage());
1717 }
1718 } else if (tokens[0].startsWith("else")) {
1719 // if the if statement was false then run the else statement
1720 if (lastItemStatus == Status.FalseIf) {
1721 // check if it is a one line if statment
1722 if (tokens.length > 1) {
1723 // put together the one line statement
1724 StringBuilder statement = new StringBuilder();
1725 for (int i = 1; i < tokens.length; i++)
1726 statement.append(tokens[i]).append(' ');
1727 // create a copy of the code item to run
1728 Text copiedCode = code.copy();
1729 copiedCode.setText(statement.toString());
1730 return RunItem(copiedCode, context, Status.OK);
1731 } else {
1732 return RunFrameAndReportError(code, context);
1733 }
1734 } else if (lastItemStatus == Status.TrueIf) {
1735 return Status.OK;
1736 }
1737 throw new RuntimeException("Else without matching If statement");
1738 } else if (tokens[0].startsWith("if")) {
1739 Boolean result = null;
1740 int parametres = 1;
1741 String variable = DEFAULT_ITEM;
1742 String ifStatement = tokens[0];
1743 // Set the default variable
1744 if (tokens.length == 1) {
1745 if (ifStatement.equals("if") || ifStatement.equals("ifnot"))
1746 variable = DEFAULT_STRING;
1747 else if (ifStatement.equals("ifzero")
1748 || ifStatement.equals("ifnotzero"))
1749 variable = DEFAULT_INTEGER;
1750 } else {
1751 variable = tokens[1];
1752 }
1753
1754 if (ifStatement.equals("if")) {
1755 result = context.getPrimitives().getBooleanValue(variable);
1756 } else if (ifStatement.equals("ifnot")) {
1757 result = !context.getPrimitives().getBooleanValue(variable);
1758 } else if (ifStatement.equals("ifdefined")) {
1759 result = context.isDefined(tokens[1]);
1760 } else if (ifStatement.equals("ifnotdefined")) {
1761 result = !context.isDefined(tokens[1]);
1762 } else if (ifStatement.equals("ifzero")) {
1763 result = context.getPrimitives().getIntegerValue(variable) == 0;
1764 } else if (ifStatement.equals("ifnotzero")) {
1765 result = context.getPrimitives().getIntegerValue(variable) != 0;
1766 } else if (tokens[0].equals("ifeq")) {
1767 result = context.equalValues(tokens[1], tokens[2]);
1768 parametres = 2;
1769 } else if (tokens[0].equals("ifeqnocase")) {
1770 result = context.getPrimitives().equalValuesNoCase(tokens[1],
1771 tokens[2]);
1772 parametres = 2;
1773 } else if (tokens[0].equals("ifnoteqnocase")) {
1774 result = !context.getPrimitives().equalValuesNoCase(tokens[1],
1775 tokens[2]);
1776 parametres = 2;
1777 } else if (tokens[0].equals("ifnoteq")) {
1778 result = !context.equalValues(tokens[1], tokens[2]);
1779 parametres = 2;
1780 } else if (tokens[0].equals("ifless")) {
1781 result = context.getPrimitives().compareValues(tokens[1],
1782 tokens[2]) < 0;
1783 parametres = 2;
1784 } else if (tokens[0].equals("ifgtr")) {
1785 result = context.getPrimitives().compareValues(tokens[1],
1786 tokens[2]) > 0;
1787 parametres = 2;
1788 } else if (tokens[0].equals("ifgeq")) {
1789 result = context.getPrimitives().compareValues(tokens[1],
1790 tokens[2]) >= 0;
1791 parametres = 2;
1792 } else if (tokens[0].equals("ifleq")) {
1793 result = context.getPrimitives().compareValues(tokens[1],
1794 tokens[2]) <= 0;
1795 parametres = 2;
1796 } else if (tokens[0].equals("ifexistingframe")) {
1797 result = FrameIO.canAccessFrame(context.getPrimitives()
1798 .getStringValue(tokens[1]));
1799 } else if (tokens[0].equals("ifexistingframeset")) {
1800 String framesetName = context.getPrimitives().getStringValue(
1801 tokens[1]);
1802 result = FrameIO.canAccessFrameset(framesetName);
1803 } else {
1804 // assertVariableType(variable, 1, SPointer.itemPrefix);
1805 if (ifStatement.equals("ifannotation")) {
1806 result = ((Item) context.getPointers()
1807 .getVariable(variable).getValue()).isAnnotation();
1808 } else if (ifStatement.equals("iflinked")) {
1809 result = ((Item) context.getPointers()
1810 .getVariable(variable).getValue()).getLink() != null;
1811 } else if (ifStatement.equals("ifactioned")) {
1812 result = ((Item) context.getPointers()
1813 .getVariable(variable).getValue()).hasAction();
1814 } else if (ifStatement.equals("ifnotactioned")) {
1815 result = !((Item) context.getPointers().getVariable(
1816 variable).getValue()).hasAction();
1817 } else if (ifStatement.equals("ifbodytext")) {
1818 Item i = (Item) context.getPointers().getVariable(variable)
1819 .getValue();
1820 result = i instanceof Text && !i.isFrameName()
1821 && !i.isFrameTitle();
1822 } else if (ifStatement.equals("ifnotannotation")) {
1823 result = !((Item) context.getPointers().getVariable(
1824 variable).getValue()).isAnnotation();
1825 } else if (ifStatement.equals("ifnotlinked")) {
1826 result = ((Item) context.getPointers()
1827 .getVariable(variable).getValue()).getLink() == null;
1828 } else if (ifStatement.equals("ifnotbodytext")) {
1829 Item i = (Item) context.getPointers().getVariable(variable)
1830 .getValue();
1831 result = !(i instanceof Text) || i.isFrameName()
1832 || i.isFrameTitle();
1833 }
1834 }
1835
1836 if (result == null)
1837 throw new RuntimeException("Invalid If statement");
1838 // Now check if we need to run the code
1839 else if (result) {
1840 Status status;
1841 // check if it is a one line if statment
1842 if (tokens.length > parametres + 1) {
1843 // put together the one line statement
1844 StringBuilder statement = new StringBuilder();
1845 for (int i = parametres + 1; i < tokens.length; i++)
1846 statement.append(tokens[i]).append(' ');
1847 // create a copy of the code item to run
1848 Text copiedCode = code.copy();
1849 copiedCode.setText(statement.toString());
1850 status = RunItem(copiedCode, context, Status.OK);
1851 } else {
1852 status = RunFrameAndReportError(code, context);
1853 }
1854 if (status == Status.OK) {
1855 return Status.TrueIf;
1856 } else {
1857 return status;
1858 }
1859 }
1860 return Status.FalseIf;
1861 } // Look for variable length methods
1862 else if (tokens[0].equals("attachitemtocursor")) {
1863 String itemVar = DEFAULT_ITEM;
1864
1865 if (tokens.length > 1) {
1866 assertExactParametreCount(tokens, 1);
1867 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1868 itemVar = tokens[1];
1869 }
1870 Item item = (Item) context.getPointers().getVariable(itemVar)
1871 .getValue();
1872 item
1873 .setPosition(FrameMouseActions.MouseX,
1874 FrameMouseActions.MouseY);
1875 FrameMouseActions.pickup(item);
1876 } else if (tokens[0].equals("attachstrtocursor")) {
1877 String stringVar = DEFAULT_STRING;
1878
1879 if (tokens.length > 1) {
1880 assertExactParametreCount(tokens, 1);
1881 stringVar = tokens[1];
1882 }
1883 String s = context.getPrimitives().getStringValue(stringVar);
1884 Frame frame = DisplayIO.getCurrentFrame();
1885 Item item = frame.createNewText(s);
1886 item
1887 .setPosition(FrameMouseActions.MouseX,
1888 FrameMouseActions.MouseY);
1889 FrameMouseActions.pickup(item);
1890 } else if (tokens[0].equals("additemtoframe")) {
1891 String itemVar = DEFAULT_ITEM;
1892 String frameVar = DEFAULT_FRAME;
1893
1894 if (tokens.length > 1) {
1895 assertExactParametreCount(tokens, 2);
1896 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1897 assertVariableType(tokens[2], 2, SPointer.itemPrefix);
1898 itemVar = tokens[2];
1899 frameVar = tokens[1];
1900 }
1901 Frame frame = (Frame) context.getPointers().getVariable(frameVar)
1902 .getValue();
1903 Item item = (Item) context.getPointers().getVariable(itemVar)
1904 .getValue();
1905 frame.addItem(item);
1906 } else if (tokens[0].equals("connectdots")) {
1907 assertMinParametreCount(tokens, 2);
1908 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1909 assertVariableType(tokens[2], 2, SPointer.itemPrefix);
1910 Item dot1 = null;
1911 Item dot2 = null;
1912 try {
1913 dot1 = (Item) context.getPointers().getVariable(tokens[1])
1914 .getValue();
1915 } catch (Exception e) {
1916 throw new IncorrectTypeException("Dot", 1);
1917 }
1918 try {
1919 dot2 = (Item) context.getPointers().getVariable(tokens[2])
1920 .getValue();
1921 } catch (Exception e) {
1922 throw new IncorrectTypeException("Dot", 2);
1923 }
1924 Frame frame = dot1.getParent();
1925 frame.addItem(new Line(dot1, dot2, frame.getNextItemID()));
1926 } else if (tokens[0].equals("createitem")
1927 || tokens[0].equals("createtext")) {
1928 assertMinParametreCount(tokens, 4);
1929 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1930 assertVariableType(tokens[4], 4, SPointer.itemPrefix);
1931 Frame frame = (Frame) context.getPointers().getVariable(tokens[1])
1932 .getValue();
1933 Item newItem;
1934 int x = (int) context.getPrimitives().getIntegerValue(tokens[2]);
1935 int y = (int) context.getPrimitives().getIntegerValue(tokens[3]);
1936 // check for the option text and action for the new item
1937 if (tokens.length > 5) {
1938 String newText = context.getPrimitives().getStringValue(
1939 tokens[5]);
1940 String newAction = null;
1941 if (tokens.length > 6) {
1942 newAction = context.getPrimitives().getStringValue(
1943 tokens[6]);
1944 }
1945 newItem = frame.addText(x, y, newText, newAction);
1946 } else {
1947 if (tokens[0].equals("createtext")) {
1948 newItem = frame.createNewText();
1949 newItem.setPosition(x, y);
1950 } else {
1951 // create a point if the optional params are not provided
1952 newItem = frame.addDot(x, y);
1953 }
1954 }
1955 context.getPointers().setObject(tokens[4], newItem);
1956 } else if (tokens[0].equals("deleteitem")) {
1957 assertMinParametreCount(tokens, 1);
1958 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
1959 Item item = (Item) context.getPointers().getVariable(tokens[1])
1960 .getValue();
1961 item.delete();
1962 } else if (tokens[0].equals("deleteframe")) {
1963 assertMinParametreCount(tokens, 1);
1964 assertVariableType(tokens[1], 1, SPointer.framePrefix);
1965 Frame frame = (Frame) context.getPointers().getVariable(tokens[1])
1966 .getValue();
1967 String errorMessage = "Error deleting " + frame.getName();
1968 boolean success = false;
1969 try {
1970 success = FrameIO.DeleteFrame(frame) != null;
1971 if (!success && _verbose)
1972 MessageBay.warningMessage(errorMessage);
1973 } catch (Exception e) {
1974 // If an exception is thrown then success is false
1975 if (_verbose) {
1976 MessageBay.warningMessage(errorMessage
1977 + (e.getMessage() != null ? ". " + e.getMessage()
1978 : ""));
1979 }
1980 }
1981 if (tokens.length > 2) {
1982 context.getPrimitives().setValue(tokens[2],
1983 new SBoolean(success));
1984 }
1985 } else if (tokens[0].equals("deleteframeset")) {
1986 assertMinParametreCount(tokens, 1);
1987 String framesetName = context.getPrimitives().getStringValue(
1988 tokens[1]);
1989 boolean success = FrameIO.DeleteFrameset(framesetName);
1990 if (!success && _verbose) {
1991 MessageBay.warningMessage("Error deleting " + framesetName);
1992 }
1993 if (tokens.length > 2) {
1994 context.getPrimitives().setValue(tokens[2],
1995 new SBoolean(success));
1996 }
1997 } else if (tokens[0].equals("copyitem")) {
1998 assertMinParametreCount(tokens, 2);
1999 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
2000 assertVariableType(tokens[2], 2, SPointer.itemPrefix);
2001 Item item = (Item) context.getPointers().getVariable(tokens[1])
2002 .getValue();
2003 Item copy = item.copy();
2004 context.getPointers().setObject(tokens[2], copy);
2005 } else if (tokens[0].equals("copyframeset")) {
2006 assertMinParametreCount(tokens, 2);
2007 String framesetToCopy = context.getPrimitives().getStringValue(
2008 tokens[1]);
2009 String copiedFrameset = context.getPrimitives().getStringValue(
2010 tokens[2]);
2011 boolean success = FrameIO.CopyFrameset(framesetToCopy,
2012 copiedFrameset);
2013 if (!success && _verbose)
2014 MessageBay.warningMessage("Error copying " + framesetToCopy);
2015 if (tokens.length > 3) {
2016 context.getPrimitives().setValue(tokens[3],
2017 new SBoolean(success));
2018 }
2019 } else if (tokens[0].equals("copyframe")) {
2020 assertMinParametreCount(tokens, 2);
2021 assertVariableType(tokens[1], 1, SPointer.framePrefix);
2022 assertVariableType(tokens[2], 2, SPointer.framePrefix);
2023 Frame frameToCopy = (Frame) context.getPointers().getVariable(
2024 tokens[1]).getValue();
2025 FrameIO.SuspendCache();
2026 Frame freshCopy = FrameIO.LoadFrame(frameToCopy.getName());
2027 // Change the frameset if one was provided
2028 if (tokens.length > 3) {
2029 String destinationFrameset = context.getPrimitives()
2030 .getStringValue(tokens[3]);
2031 freshCopy.setFrameset(destinationFrameset);
2032 }// Otherwise add it to the end of this frameset
2033 int nextNumber = FrameIO.getLastNumber(freshCopy.getFramesetName()) + 1;
2034 // if the frameset doesnt already exist then create it
2035 if (nextNumber <= 0) {
2036 try {
2037 FrameIO.CreateFrameset(freshCopy.getFramesetName(),
2038 frameToCopy.path);
2039 nextNumber = 1;
2040 } catch (Exception e) {
2041 }
2042 }
2043 boolean success = false;
2044 if (nextNumber > 0) {
2045 freshCopy.setFrameNumber(nextNumber);
2046 context.getPointers().setObject(tokens[2], freshCopy);
2047 String fileContents = FrameIO.ForceSaveFrame(freshCopy);
2048 success = fileContents != null;
2049 }
2050 FrameIO.ResumeCache();
2051 if (success) {
2052 // Need to add the new copy to the cache in case it is edited by
2053 // other simple statements
2054 FrameIO.addToCache(freshCopy);
2055 }
2056 if (!success && _verbose)
2057 MessageBay.warningMessage("Error copying "
2058 + frameToCopy.getName());
2059 if (tokens.length > 4) {
2060 context.getPrimitives().setValue(tokens[4],
2061 new SBoolean(success));
2062 }
2063 } else if (tokens[0].equals("createframe")) {
2064
2065 String framesetName = DEFAULT_STRING;
2066 String frameVar = DEFAULT_FRAME;
2067
2068 if (tokens.length > 1) {
2069 assertMinParametreCount(tokens, 2);
2070 assertVariableType(tokens[2], 2, SPointer.framePrefix);
2071 framesetName = tokens[1];
2072 frameVar = tokens[2];
2073 }
2074
2075 if (tokens.length > 3) {
2076 context.createFrame(framesetName, frameVar, tokens[3]);
2077 } else
2078 context.createFrame(framesetName, frameVar, null);
2079 } else if (tokens[0].equals("closeframe")) {
2080 String frameVar = DEFAULT_FRAME;
2081
2082 if (tokens.length > 1) {
2083 assertVariableType(tokens[1], 1, SPointer.framePrefix);
2084 frameVar = tokens[1];
2085 }
2086
2087 if (tokens.length > 2) {
2088 // assertPrimitiveType(tokens[3], 3);
2089 context.closeFrame(frameVar, tokens[3]);
2090 } else
2091 context.closeFrame(frameVar, null);
2092 } else if (tokens[0].equals("readframe")
2093 || tokens[0].equals("openframe")) {
2094
2095 String frameName = DEFAULT_STRING;
2096 String frameVar = DEFAULT_FRAME;
2097
2098 if (tokens.length > 1) {
2099 assertMinParametreCount(tokens, 2);
2100 assertVariableType(tokens[2], 2, SPointer.framePrefix);
2101 frameName = tokens[1];
2102 frameVar = tokens[2];
2103 // assertPrimitiveType(frameName, 1);
2104 }
2105
2106 if (tokens.length > 3) {
2107 // assertPrimitiveType(tokens[3], 3);
2108 context.readFrame(frameName, frameVar, tokens[3]);
2109 } else
2110 context.readFrame(frameName, frameVar, null);
2111 } else if (tokens[0].equals("exitexpeditee")) {
2112 Browser._theBrowser.exit();
2113 } else if (tokens[0].equals("readkbdcond")) {
2114
2115 String nextCharVarName = DEFAULT_CHAR;
2116 String wasCharVarName = DEFAULT_BOOLEAN;
2117
2118 if (tokens.length > 1) {
2119 assertMinParametreCount(tokens, 2);
2120 assertVariableType(tokens[2], 2, SPointer.framePrefix);
2121 nextCharVarName = tokens[1];
2122 wasCharVarName = tokens[2];
2123 }
2124
2125 Character nextChar = _KeyStrokes.poll();
2126 boolean hasChar = nextChar != null;
2127 context.getPrimitives().setValue(wasCharVarName,
2128 new SBoolean(hasChar));
2129 if (hasChar)
2130 context.getPrimitives().setValue(nextCharVarName,
2131 new SCharacter(nextChar));
2132 } else if (tokens[0].equals("createassociation")) {
2133
2134 String associationVar = DEFAULT_ASSOCIATION;
2135
2136 if (tokens.length > 0) {
2137 assertVariableType(tokens[1], 2, SPointer.associationPrefix);
2138 associationVar = tokens[1];
2139 }
2140 Map<String, String> newMap = new HashMap<String, String>();
2141 context.getPointers().setObject(associationVar, newMap);
2142 } else if (tokens[0].equals("deleteassociation")) {
2143
2144 String associationVar = DEFAULT_ASSOCIATION;
2145
2146 if (tokens.length > 0) {
2147 assertVariableType(tokens[1], 2, SPointer.associationPrefix);
2148 associationVar = tokens[1];
2149 }
2150 context.getPointers().delete(associationVar);
2151 } else if (tokens[0].equals("openreadfile")) {
2152 assertVariableType(tokens[1], 1, SString.prefix);
2153 assertVariableType(tokens[2], 2, SPointer.filePrefix);
2154
2155 if (tokens.length > 3) {
2156 assertVariableType(tokens[3], 3, SBoolean.prefix);
2157 context.openReadFile(tokens[1], tokens[2], tokens[3]);
2158 } else
2159 context.openReadFile(tokens[1], tokens[2]);
2160 } else if (tokens[0].equals("readlinefile")
2161 || tokens[0].equals("readlnfile")) {
2162 assertVariableType(tokens[1], 1, SPointer.filePrefix);
2163
2164 if (tokens.length > 3) {
2165 assertVariableType(tokens[3], 3, SBoolean.prefix);
2166 context.readLineFile(tokens[1], tokens[2], tokens[3]);
2167 } else
2168 context.readLineFile(tokens[1], tokens[2]);
2169 } else if (tokens[0].equals("readitemfile")) {
2170 assertVariableType(tokens[1], 1, SPointer.filePrefix);
2171 assertVariableType(tokens[2], 1, SPointer.itemPrefix);
2172
2173 if (tokens.length > 3) {
2174 assertVariableType(tokens[3], 3, SBoolean.prefix);
2175 context.readItemFile(tokens[1], tokens[2], tokens[3]);
2176 } else
2177 context.readItemFile(tokens[1], tokens[2]);
2178 } else if (tokens[0].equals("openwritefile")) {
2179 assertVariableType(tokens[1], 1, SString.prefix);
2180 assertVariableType(tokens[2], 2, SPointer.filePrefix);
2181
2182 if (tokens.length > 3) {
2183 assertVariableType(tokens[3], 3, SBoolean.prefix);
2184 context.openWriteFile(tokens[1], tokens[2], tokens[3]);
2185 } else
2186 context.openWriteFile(tokens[1], tokens[2]);
2187 } else if (tokens[0].equals("writefile")
2188 || tokens[0].equals("writelinefile")
2189 || tokens[0].equals("writelnfile")) {
2190 assertVariableType(tokens[1], 1, SPointer.filePrefix);
2191
2192 StringBuffer textToWrite = new StringBuffer();
2193 if (tokens.length == 1) {
2194 textToWrite.append(context.getPrimitives().getVariable(
2195 DEFAULT_STRING).stringValue()
2196 + " ");
2197 } else {
2198 for (int i = 2; i < tokens.length; i++) {
2199 if (Primitives.isPrimitive(tokens[i])) {
2200 textToWrite.append(context.getPrimitives().getVariable(
2201 tokens[i]).stringValue());
2202 } else
2203 throw new Exception("Illegal parametre: " + tokens[i]
2204 + " in " + code.toString());
2205 }
2206 }
2207
2208 if (!tokens[0].equals("writefile"))
2209 textToWrite.append(Text.LINE_SEPARATOR);
2210 context.writeFile(tokens[1], textToWrite.toString());
2211 } else if (tokens[0].equals("displayframeset")) {
2212 assertMinParametreCount(tokens, 1);
2213 String framesetName = context.getPrimitives().getStringValue(
2214 tokens[1]);
2215 int lastFrameNo = FrameIO.getLastNumber(framesetName);
2216 int firstFrameNo = 0;
2217 double pause = 0.0;
2218 // get the first and last frames to display if they were proided
2219 if (tokens.length > 2) {
2220 firstFrameNo = (int) context.getPrimitives().getIntegerValue(
2221 tokens[2]);
2222 if (tokens.length > 3) {
2223 lastFrameNo = (int) context.getPrimitives()
2224 .getIntegerValue(tokens[3]);
2225 if (tokens.length > 4) {
2226 pause = context.getPrimitives().getDoubleValue(
2227 tokens[4]);
2228 }
2229 }
2230 }
2231 Runtime runtime = Runtime.getRuntime();
2232 // Display the frames
2233 for (int i = firstFrameNo; i <= lastFrameNo; i++) {
2234 Frame frame = FrameIO.LoadFrame(framesetName + i);
2235 if (frame != null) {
2236 double thisFramesPause = pause;
2237 // check for change in delay for this frame only
2238 Item pauseItem = ItemUtils.FindTag(frame.getItems(),
2239 "@DisplayFramePause:");
2240 if (pauseItem != null) {
2241 try {
2242 // attempt to read in the delay value
2243 thisFramesPause = Double.parseDouble(ItemUtils
2244 .StripTag(
2245 ((Text) pauseItem).getFirstLine(),
2246 "@DisplayFramePause"));
2247 } catch (NumberFormatException nfe) {
2248 }
2249 }
2250 DisplayIO.setCurrentFrame(frame, false);
2251 pause(thisFramesPause);
2252
2253 long freeMemory = runtime.freeMemory();
2254 if (freeMemory < DisplayTree.GARBAGE_COLLECTION_THRESHOLD) {
2255 runtime.gc();
2256 MessageBay.displayMessage("Force Garbage Collection!");
2257 }
2258 }
2259 }
2260 } else if (tokens[0].equals("createframeset")) {
2261 String framesetName = DEFAULT_STRING;
2262 String successVar = null;
2263 if (tokens.length > 1) {
2264 framesetName = tokens[1];
2265 if (tokens.length > 2)
2266 successVar = tokens[2];
2267 }
2268 context.createFrameset(framesetName, successVar);
2269 } else if (tokens[0].equals("writetree")) {
2270 assertMinParametreCount(tokens, 3);
2271 assertVariableType(tokens[1], 1, SPointer.framePrefix);
2272 Frame source = (Frame) context.getPointers().getVariable(tokens[1])
2273 .getValue();
2274 String format = context.getPrimitives().getStringValue(tokens[2]);
2275 String fileName = context.getPrimitives().getStringValue(tokens[3]);
2276 WriteTree wt = new WriteTree(format, fileName);
2277 if (wt.initialise(source, null)) {
2278 _agent = wt;
2279 wt.run();
2280 _agent = null;
2281 }
2282 } else if (tokens[0].equals("concatstr")) {
2283 assertMinParametreCount(tokens, 3);
2284 String resultVar = tokens[tokens.length - 1];
2285
2286 StringBuilder sb = new StringBuilder();
2287 // loop through all the strings concatenating them
2288 for (int i = 1; i < tokens.length - 1; i++) {
2289 // assertPrimitiveType(tokens[i], i);
2290 sb.append(context.getPrimitives().getStringValue(tokens[i]));
2291 }
2292 context.getPrimitives().setValue(resultVar,
2293 new SString(sb.toString()));
2294 } else if (tokens[0].equals("convstrlower")) {
2295 assertExactParametreCount(tokens, 1);
2296 // assertPrimitiveType(tokens[1], 1);
2297 context.getPrimitives().setValue(
2298 tokens[1],
2299 new SString(context.getPrimitives().getStringValue(
2300 tokens[1]).toLowerCase()));
2301 } else if (tokens[0].equals("convstrupper")) {
2302 assertExactParametreCount(tokens, 1);
2303 // assertPrimitiveType(tokens[1], 1);
2304 context.getPrimitives().setValue(
2305 tokens[1],
2306 new SString(context.getPrimitives().getStringValue(
2307 tokens[1]).toUpperCase()));
2308 } else if (tokens[0].equals("countcharsinstr")) {
2309 assertExactParametreCount(tokens, 3);
2310 String s = context.getPrimitives().getStringValue(tokens[1]);
2311 String pattern = context.getPrimitives().getStringValue(tokens[2]);
2312 int count = countCharsInString(s, pattern);
2313 context.getPrimitives().setValue(tokens[3], new SInteger(count));
2314 } else if (tokens[0].equals("countcharsinitem")) {
2315 assertExactParametreCount(tokens, 3);
2316 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
2317 Item item = (Item) context.getPointers().getVariable(tokens[1])
2318 .getValue();
2319 String pattern = context.getPrimitives().getStringValue(tokens[2]);
2320 int count = 0;
2321 if (item instanceof Text)
2322 count = countCharsInString(((Text) item).getText(), pattern);
2323 context.getPrimitives().setValue(tokens[3], new SInteger(count));
2324 } else if (tokens[0].equals("clearframe")) {
2325 String frameVar = DEFAULT_FRAME;
2326 if (tokens.length > 1) {
2327 assertMinParametreCount(tokens, 1);
2328 assertVariableType(tokens[1], 1, SPointer.framePrefix);
2329 frameVar = tokens[1];
2330 }
2331 boolean success = true;
2332 try {
2333 Frame frameToClear = (Frame) context.getPointers().getVariable(
2334 frameVar).getValue();
2335 frameToClear.clear(false);
2336 assert (frameToClear.getItems().size() <= 1);
2337 } catch (Exception e) {
2338 success = false;
2339 }
2340 if (tokens.length > 2) {
2341 assertExactParametreCount(tokens, 2);
2342 context.getPrimitives().setValue(tokens[2],
2343 new SBoolean(success));
2344 }
2345 } else if (tokens[0].equals("parseframename")) {
2346 assertExactParametreCount(tokens, 4);
2347 String frameName = context.getPrimitives()
2348 .getStringValue(tokens[1]);
2349 String frameSet = "";
2350 int frameNo = -1;
2351 boolean success = true;
2352 try {
2353 frameSet = Conversion.getFramesetName(frameName, false);
2354 frameNo = Conversion.getFrameNumber(frameName);
2355 } catch (Exception e) {
2356 success = false;
2357 if (_verbose)
2358 MessageBay.warningMessage("Error parsing " + frameName);
2359 }
2360 // assertPrimitiveType(tokens[2], 2);
2361 context.getPrimitives().setValue(tokens[2], new SBoolean(success));
2362
2363 // assertPrimitiveType(tokens[3], 3);
2364 context.getPrimitives().setValue(tokens[3], new SString(frameSet));
2365
2366 // assertPrimitiveType(tokens[4], 4);
2367 context.getPrimitives().setValue(tokens[4], new SInteger(frameNo));
2368 } else if (tokens[0].equals("parsestr")) {
2369 assertMinParametreCount(tokens, 2);
2370 // assertPrimitiveType(tokens[1], 1);
2371 // assertPrimitiveType(tokens[2], 2);
2372
2373 String s = context.getPrimitives().getStringValue(tokens[1]);
2374
2375 String separator = context.getPrimitives()
2376 .getStringValue(tokens[2]);
2377
2378 String[] split = s.split(separator, tokens.length - 4);
2379
2380 if (tokens.length > 3) {
2381 // assertPrimitiveType(tokens[3], 3);
2382 int count = split.length;
2383 // if the string is not blank and its got a remainder then
2384 // decrease the count by 1 to account for the remainder
2385 if (split.length != 0 && split.length > tokens.length - 5)
2386 count--;
2387
2388 context.getPrimitives()
2389 .setValue(tokens[3], new SInteger(count));
2390
2391 if (tokens.length > 4) {
2392 // Set the remainder string
2393 // assertPrimitiveType(tokens[4], 4);
2394 if (split.length < tokens.length - 4)
2395 context.getPrimitives().setValue(tokens[4],
2396 new SString());
2397 else
2398 context.getPrimitives().setValue(tokens[4],
2399 new SString(split[split.length - 1]));
2400
2401 // Set the strings for each of the vars
2402 if (tokens.length > 5) {
2403 for (int i = 5; i < tokens.length; i++) {
2404 // assertPrimitiveType(tokens[i], i);
2405 if (split.length < i - 4)
2406 context.getPrimitives().setValue(tokens[i],
2407 new SString());
2408 else
2409 context.getPrimitives().setValue(tokens[i],
2410 new SString(split[i - 5]));
2411 }
2412 }
2413 }
2414 }
2415 } else if (tokens[0].equals("stripstr")) {
2416 assertExactParametreCount(tokens, 2);
2417 String s = context.getPrimitives().getStringValue(tokens[1]);
2418 String charsToStrip = context.getPrimitives().getStringValue(
2419 tokens[2]);
2420 for (int i = 0; i < charsToStrip.length(); i++)
2421 s = s.replaceAll(charsToStrip.substring(i, i + 1), "");
2422 context.getPrimitives().setValue(tokens[1], new SString(s));
2423 } else if (tokens[0].equals("subststr")) {
2424 assertExactParametreCount(tokens, 3);
2425 String oldString = context.getPrimitives()
2426 .getStringValue(tokens[2]);
2427 String newString = context.getPrimitives()
2428 .getStringValue(tokens[3]);
2429 String result = context.getPrimitives().getStringValue(tokens[1]);
2430 result = result.replaceAll(oldString, newString);
2431 context.getPrimitives().setValue(tokens[1], new SString(result));
2432 } else if (tokens[0].equals("substr")) {
2433 assertExactParametreCount(tokens, 4);
2434 int startPos = (int) context.getPrimitives().getIntegerValue(
2435 tokens[2]) - 1;
2436 int length = (int) context.getPrimitives().getIntegerValue(
2437 tokens[3]);
2438 String s = context.getPrimitives().getStringValue(tokens[1]);
2439 String result;
2440 if (startPos + length < s.length())
2441 result = s.substring(startPos, startPos + length);
2442 else
2443 result = s.substring(startPos);
2444 context.getPrimitives().setValue(tokens[4], new SString(result));
2445 } else if (tokens[0].equals("pause")) {
2446 String lengthVar = DEFAULT_REAL;
2447
2448 if (tokens.length > 1) {
2449 assertExactParametreCount(tokens, 1);
2450 lengthVar = tokens[1];
2451 }
2452
2453 pause(context.getPrimitives().getDoubleValue(lengthVar));
2454 } else if (tokens[0].equals("glidecursorto")) {
2455 assertMinParametreCount(tokens, 2);
2456 int finalX = (int) context.getPrimitives().getIntegerValue(
2457 tokens[1]);
2458 int finalY = (int) context.getPrimitives().getIntegerValue(
2459 tokens[2]);
2460 int milliseconds = 1000;
2461 if (tokens.length > 3)
2462 milliseconds = (int) (context.getPrimitives().getDoubleValue(
2463 tokens[3]) * 1000);
2464
2465 int initialX = DisplayIO.getMouseX();
2466 int initialY = FrameMouseActions.getY();
2467
2468 final int timeInterval = 40;
2469
2470 int deltaX = (int) (finalX - initialX);
2471 int deltaY = (int) (finalY - initialY);
2472
2473 int intervals = milliseconds / timeInterval;
2474 for (double i = 0; i < intervals; i++) {
2475 int newX = initialX + (int) (deltaX * i / intervals);
2476 int newY = initialY + (int) (deltaY * i / intervals);
2477 Thread.yield();
2478 Thread.sleep(timeInterval);
2479 DisplayIO.setCursorPosition(newX, newY);
2480 // DisplayIO.repaint();
2481 }
2482 // Thread.yield();
2483 Thread.sleep(milliseconds % timeInterval);
2484 DisplayIO.setCursorPosition(finalX, finalY);
2485 } else if (tokens[0].equals("glideitemto")) {
2486 assertMinParametreCount(tokens, 3);
2487 assertVariableType(tokens[1], 1, SPointer.itemPrefix);
2488 Item item = (Item) context.getPointers().getVariable(tokens[1])
2489 .getValue();
2490 int finalX = (int) context.getPrimitives().getIntegerValue(
2491 tokens[2]);
2492 int finalY = (int) context.getPrimitives().getIntegerValue(
2493 tokens[3]);
2494
2495 // DisplayIO.setCursorPosition(item.getX(), item.getY());
2496 // FrameMouseActions.pickup(item);
2497
2498 int milliseconds = 1000;
2499 if (tokens.length > 4)
2500 milliseconds = (int) (context.getPrimitives().getDoubleValue(
2501 tokens[4]) * 1000);
2502
2503 int initialX = item.getX();
2504 int initialY = item.getY();
2505 // int initialX = DisplayIO.getMouseX();
2506 // int initialY = DisplayIO.getMouseY();
2507
2508 final int timeInterval = 40;
2509
2510 int deltaX = (int) (finalX - initialX);
2511 int deltaY = (int) (finalY - initialY);
2512
2513 int intervals = milliseconds / timeInterval;
2514 for (double i = 0; i < intervals; i++) {
2515 int newX = initialX + (int) (deltaX * i / intervals);
2516 int newY = initialY + (int) (deltaY * i / intervals);
2517 Thread.yield();
2518 Thread.sleep(timeInterval);
2519 // DisplayIO.setCursorPosition(newX, newY);
2520
2521 item.setPosition(newX, newY);
2522 FrameGraphics.Repaint();
2523 }
2524 // Thread.yield();
2525 Thread.sleep(milliseconds % timeInterval);
2526 item.setPosition(finalX, finalY);
2527 // DisplayIO.setCursorPosition(finalX, finalY);
2528 FrameMouseActions.anchor(item);
2529 FreeItems.getInstance().clear();
2530 FrameGraphics.Repaint();
2531 // FrameMouseActions.updateCursor();
2532 }
2533 // Now look for fixed parametre statements
2534 else if (tokens[0].equals(EXIT_TEXT)) {
2535 return Status.Exit;
2536 } else if (tokens[0].equals(LOOP_TEXT)) {
2537 Status status = Status.OK;
2538 // Check if its a counter loop
2539 if (tokens.length > 1) {
2540 // Get the number of times to repeat the loop
2541 long finalCount = context.getPrimitives().getIntegerValue(
2542 tokens[1]);
2543 String counterVar = tokens.length > 2 ? tokens[2] : null;
2544 long count = 0;
2545 while ((status == Status.OK || status == Status.Continue)
2546 && (count < finalCount)) {
2547 count++;
2548 // Update the counter variable
2549 if (counterVar != null) {
2550 context.getPrimitives().setValue(counterVar,
2551 new SInteger(count));
2552 }
2553 status = RunFrameAndReportError(code, context);
2554 pause(code);
2555 }
2556 } else {
2557 // Keep looping until break or exit occurs
2558 while (status == Status.OK || status == Status.Continue) {
2559 status = RunFrameAndReportError(code, context);
2560 pause(code);
2561 }
2562 }
2563 if (status == Status.Continue || status == Status.Break)
2564 status = Status.OK;
2565 return status;
2566 } else if (tokens[0].equals(CONTINUE_TEXT)
2567 || tokens[0].equals(CONTINUE2_TEXT)) {
2568 return Status.Continue;
2569 } else if (tokens[0].equals(BREAK_TEXT)
2570 || tokens[0].equals(BREAK2_TEXT)) {
2571 return Status.Break;
2572 } else if (tokens[0].equals(RETURN_TEXT)) {
2573 return Status.Return;
2574 } else if (tokens[0].equals("pressleftbutton")) {
2575 assertExactParametreCount(tokens, 0);
2576 DisplayIO.pressMouse(InputEvent.BUTTON1_MASK);
2577 } else if (tokens[0].equals("pressmiddlebutton")) {
2578 assertExactParametreCount(tokens, 0);
2579 DisplayIO.pressMouse(InputEvent.BUTTON2_MASK);
2580 } else if (tokens[0].equals("pressrightbutton")) {
2581 assertExactParametreCount(tokens, 0);
2582 DisplayIO.pressMouse(InputEvent.BUTTON3_MASK);
2583 } else if (tokens[0].equals("releaseleftbutton")) {
2584 assertExactParametreCount(tokens, 0);
2585 DisplayIO.releaseMouse(InputEvent.BUTTON1_MASK);
2586 } else if (tokens[0].equals("releasemiddlebutton")) {
2587 assertExactParametreCount(tokens, 0);
2588 DisplayIO.releaseMouse(InputEvent.BUTTON2_MASK);
2589 } else if (tokens[0].equals("releaserightbutton")) {
2590 assertExactParametreCount(tokens, 0);
2591 DisplayIO.releaseMouse(InputEvent.BUTTON3_MASK);
2592 } else if (tokens[0].equals("clickleftbutton")) {
2593 assertExactParametreCount(tokens, 0);
2594 FrameMouseActions.leftButton();
2595 // DisplayIO.clickMouse(InputEvent.BUTTON1_MASK);
2596 } else if (tokens[0].equals("clickmiddlebutton")) {
2597 assertExactParametreCount(tokens, 0);
2598 FrameMouseActions.middleButton();
2599 // DisplayIO.clickMouse(InputEvent.BUTTON2_MASK);
2600 } else if (tokens[0].equals("clickrightbutton")) {
2601 assertExactParametreCount(tokens, 0);
2602 FrameMouseActions.rightButton();
2603 // DisplayIO.clickMouse(InputEvent.BUTTON3_MASK);
2604 } else if (tokens[0].equals("repaint")) {
2605 assertExactParametreCount(tokens, 0);
2606 // FrameGraphics.Repaint();
2607 FrameGraphics.requestRefresh(true);
2608 } else if (tokens[0].equals("add")) {
2609 assertMaxParametreCount(tokens, 3);
2610 switch (tokens.length) {
2611 case 1:
2612 context.getPrimitives().add(DEFAULT_INTEGER);
2613 break;
2614 case 2:
2615 context.getPrimitives().add(tokens[1]);
2616 break;
2617 case 3:
2618 context.getPrimitives().add(tokens[2], tokens[1]);
2619 break;
2620 case 4:
2621 context.getPrimitives().add(tokens[1], tokens[2], tokens[3]);
2622 break;
2623 default:
2624 assert (false);
2625 }
2626 } else if (tokens[0].equals("subtract")) {
2627 assertMaxParametreCount(tokens, 3);
2628 switch (tokens.length) {
2629 case 1:
2630 context.getPrimitives().subtract(DEFAULT_INTEGER);
2631 break;
2632 case 2:
2633 context.getPrimitives().subtract(tokens[1]);
2634 break;
2635 case 3:
2636 context.getPrimitives().subtract(tokens[2], tokens[1]);
2637 break;
2638 case 4:
2639 context.getPrimitives().subtract(tokens[1], tokens[2],
2640 tokens[3]);
2641 break;
2642 default:
2643 assert (false);
2644 }
2645 } else if (tokens[0].equals("multiply")) {
2646 assertMinParametreCount(tokens, 2);
2647 assertMaxParametreCount(tokens, 3);
2648 switch (tokens.length) {
2649 case 3:
2650 context.getPrimitives().multiply(tokens[2], tokens[1]);
2651 break;
2652 case 4:
2653 context.getPrimitives().multiply(tokens[1], tokens[2],
2654 tokens[3]);
2655 break;
2656 default:
2657 assert (false);
2658 }
2659 } else if (tokens[0].equals("divide")) {
2660 assertMinParametreCount(tokens, 2);
2661 assertMaxParametreCount(tokens, 3);
2662 switch (tokens.length) {
2663 case 3:
2664 context.getPrimitives().divide(tokens[2], tokens[1]);
2665 break;
2666 case 4:
2667 context.getPrimitives().divide(tokens[1], tokens[2], tokens[3]);
2668 break;
2669 default:
2670 assert (false);
2671 }
2672 } else if (tokens[0].equals("modulo")) {
2673 assertExactParametreCount(tokens, 3);
2674 context.getPrimitives().modulo(tokens[1], tokens[2], tokens[3]);
2675 } else if (tokens[0].equals("power")) {
2676 assertExactParametreCount(tokens, 3);
2677 context.getPrimitives().power(tokens[1], tokens[2], tokens[3]);
2678 } else if (tokens[0].equals("not")) {
2679 assertExactParametreCount(tokens, 2);
2680 context.getPrimitives().not(tokens[1], tokens[2]);
2681 } else if (tokens[0].equals("exp")) {
2682 assertExactParametreCount(tokens, 2);
2683 context.getPrimitives().exp(tokens[1], tokens[2]);
2684 } else if (tokens[0].equals("log")) {
2685 assertExactParametreCount(tokens, 2);
2686 context.getPrimitives().log(tokens[2], tokens[2]);
2687 } else if (tokens[0].equals("log10")) {
2688 assertExactParametreCount(tokens, 2);
2689 context.getPrimitives().log10(tokens[1], tokens[2]);
2690 } else if (tokens[0].equals("sqrt")) {
2691 assertExactParametreCount(tokens, 2);
2692 context.getPrimitives().sqrt(tokens[1], tokens[2]);
2693 } else if (tokens[0].equals("closewritefile")) {
2694 assertVariableType(tokens[1], 1, SPointer.filePrefix);
2695 context.closeWriteFile(tokens[1]);
2696 } else if (tokens[0].equals("closereadfile")) {
2697 assertVariableType(tokens[1], 1, SPointer.filePrefix);
2698 context.closeReadFile(tokens[1]);
2699 } else if (tokens[0].startsWith("foreach")) {
2700 if (tokens[0].equals("foreachassociation")) {
2701 assertExactParametreCount(tokens, 3);
2702 assertVariableType(tokens[1], 1, SPointer.associationPrefix);
2703 Map<String, String> map = (Map<String, String>) context
2704 .getPointers().getVariable(tokens[1]).getValue();
2705 for (Map.Entry entry : map.entrySet()) {
2706 String value = entry.getValue().toString();
2707 String key = entry.getKey().toString();
2708 context.getPrimitives().setValue(tokens[2], key);
2709 context.getPrimitives().setValue(tokens[3], value);
2710 Status status = RunFrameAndReportError(code, context);
2711 pause(code);
2712 // check if we need to exit this loop because of
2713 // statements in the code that was run
2714 if (status == Status.Exit || status == Status.Return)
2715 return status;
2716 else if (status == Status.Break)
2717 break;
2718 }
2719 } else {
2720 Class itemType = Object.class;
2721 String type = tokens[0].substring("foreach".length());
2722 // Check the type of foreach loop
2723 // and set the item type to iterate over
2724 if (type.equals("dot")) {
2725 itemType = Dot.class;
2726 } else if (type.equals("text")) {
2727 itemType = Text.class;
2728 } else if (type.equals("line")) {
2729 itemType = Line.class;
2730 } else if (type.equals("item") || type.equals("")) {
2731 itemType = Object.class;
2732 } else {
2733 throw new RuntimeException("Invalid ForEach loop type");
2734 }
2735
2736 assertVariableType(tokens[2], 2, SPointer.itemPrefix);
2737 assertVariableType(tokens[1], 1, SPointer.framePrefix);
2738 Frame currFrame = (Frame) context.getPointers().getVariable(
2739 tokens[1]).getValue();
2740 // Create the ip variable
2741 Item frameTitle = currFrame.getTitleItem();
2742
2743 for (Item i : currFrame.getVisibleItems()) {
2744 if (i == frameTitle)
2745 continue;
2746 if (!(itemType.isInstance(i)))
2747 continue;
2748
2749 context.getPointers().setObject(tokens[2], i);
2750 Status status = RunFrameAndReportError(code, context);
2751 pause(code);
2752 // check if we need to exit this loop because of
2753 // statements in the code that was run
2754 if (status == Status.Exit || status == Status.Return)
2755 return status;
2756 else if (status == Status.Break)
2757 return Status.OK;
2758 }
2759 }
2760 } else if (tokens[0].equals("movecursorto")) {
2761 assertExactParametreCount(tokens, 2);
2762 int x = (int) context.getPrimitives().getIntegerValue(tokens[1]);
2763 int y = (int) context.getPrimitives().getIntegerValue(tokens[2]);
2764 DisplayIO.setCursorPosition(x, y);
2765 } else {
2766 throw new RuntimeException("Unknown statement");
2767 }
2768 return Status.OK;
2769 }
2770
2771 public static int countCharsInString(String s, String pattern) {
2772 String newString = s;
2773 int count = -1;
2774 do {
2775 count++;
2776 s = newString;
2777 newString = s.replaceFirst(pattern, "");
2778 } while (s.length() != newString.length());
2779
2780 return count;
2781 }
2782
2783 public static void assertVariableType(String varName, int no, String type)
2784 throws Exception {
2785 if (!varName.startsWith(type))
2786 throw new IncorrectTypeException(type, no);
2787 }
2788
2789 /*
2790 * public static void assertPrimitiveType(String varName, int no) throws
2791 * Exception { if (!Primitives.isPrimitive(varName)) throw new
2792 * IncorrectTypeException("primitive", no); }
2793 */
2794
2795 public static void assertMinParametreCount(String[] tokens,
2796 int minParametres) throws Exception {
2797 if (tokens.length - 1 < minParametres)
2798 throw new BelowMinParametreCountException(minParametres);
2799 }
2800
2801 public static void assertExactParametreCount(String[] tokens,
2802 int parametreCount) throws Exception {
2803 if (tokens.length - 1 != parametreCount)
2804 throw new IncorrectParametreCountException(parametreCount);
2805 }
2806
2807 public static void assertMaxParametreCount(String[] tokens,
2808 int parametreCount) throws Exception {
2809 if (tokens.length - 1 > parametreCount)
2810 throw new AboveMaxParametreCountException(parametreCount);
2811 }
2812
2813 private static String getMessage(String[] tokens, Context context,
2814 String code, String separator, int firstStringIndex)
2815 throws Exception {
2816 StringBuilder message = new StringBuilder();
2817 if (tokens.length == firstStringIndex) {
2818 message.append(context.getPrimitives().getVariable(DEFAULT_STRING)
2819 .stringValue());
2820 } else {
2821 for (int i = firstStringIndex; i < tokens.length; i++) {
2822 if (Primitives.isPrimitive(tokens[i])) {
2823 message.append(context.getPrimitives().getVariable(
2824 tokens[i]).stringValue()
2825 + separator);
2826 } else
2827 throw new Exception("Illegal parametre: [" + tokens[i]
2828 + "] in line " + code);
2829 }
2830 }
2831 return message.toString();
2832 }
2833
2834 public static void stop() {
2835 _stop = true;
2836 if (_agent != null) {
2837 _agent.stop();
2838 }
2839 }
2840
2841 public static void nextStatement() {
2842 _nextStatement = true;
2843 }
2844
2845 public static void ProgramStarted() {
2846 _programsRunning++;
2847 AgentStats.reset();
2848 MessageBay.displayMessage("Running SimpleProgram...", Color.BLUE);
2849 }
2850
2851 public static boolean isVerbose() {
2852 return _verbose;
2853 }
2854}
Note: See TracBrowser for help on using the repository browser.