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

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