2 * PuzzleApplet.java: NestedVM applet for the puzzle collection
5 import java.awt.event.*;
6 import java.awt.image.BufferedImage;
9 import javax.swing.border.BevelBorder;
10 import javax.swing.Timer;
11 import java.util.List;
13 import org.ibex.nestedvm.Runtime;
15 public class PuzzleApplet extends JApplet implements Runtime.CallJavaCB {
17 private static final long serialVersionUID = 1L;
19 private static final int CFG_SETTINGS = 0, CFG_SEED = 1, CFG_DESC = 2,
20 LEFT_BUTTON = 0x0200, MIDDLE_BUTTON = 0x201, RIGHT_BUTTON = 0x202,
21 LEFT_DRAG = 0x203, MIDDLE_DRAG = 0x204, RIGHT_DRAG = 0x205,
22 LEFT_RELEASE = 0x206, CURSOR_UP = 0x209, CURSOR_DOWN = 0x20a,
23 CURSOR_LEFT = 0x20b, CURSOR_RIGHT = 0x20c, MOD_CTRL = 0x1000,
24 MOD_SHFT = 0x2000, MOD_NUM_KEYPAD = 0x4000, ALIGN_VCENTRE = 0x100,
25 ALIGN_HCENTRE = 0x001, ALIGN_HRIGHT = 0x002, C_STRING = 0,
26 C_CHOICES = 1, C_BOOLEAN = 2;
28 private JFrame mainWindow;
30 private JMenu typeMenu;
31 private JMenuItem[] typeMenuItems;
32 private int customMenuItemIndex;
34 private JMenuItem solveCommand;
35 private Color[] colors;
36 private JLabel statusBar;
37 private PuzzlePanel pp;
38 private Runtime runtime;
39 private String[] puzzle_args;
40 private Graphics2D gg;
42 private int xarg1, xarg2, xarg3;
43 private int[] xPoints, yPoints;
44 private BufferedImage[] blitters = new BufferedImage[512];
45 private ConfigDialog dlg;
49 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
50 } catch (Exception ex) {
57 Container cp = getContentPane();
58 cp.setLayout(new BorderLayout());
59 runtime = (Runtime) Class.forName("PuzzleEngine").newInstance();
60 runtime.setCallJavaCB(this);
61 JMenuBar menubar = new JMenuBar();
63 menubar.add(jm = new JMenu("Game"));
64 addMenuItemCallback(jm, "New", "jcallback_newgame_event");
65 addMenuItemCallback(jm, "Restart", "jcallback_restart_event");
66 addMenuItemCallback(jm, "Specific...", "jcallback_config_event", CFG_DESC);
67 addMenuItemCallback(jm, "Random Seed...", "jcallback_config_event", CFG_SEED);
69 addMenuItemCallback(jm, "Undo", "jcallback_undo_event");
70 addMenuItemCallback(jm, "Redo", "jcallback_redo_event");
72 solveCommand = addMenuItemCallback(jm, "Solve", "jcallback_solve_event");
73 solveCommand.setEnabled(false);
74 if (mainWindow != null) {
76 addMenuItemCallback(jm, "Exit", "jcallback_quit_event");
78 menubar.add(typeMenu = new JMenu("Type"));
79 typeMenu.setVisible(false);
80 menubar.add(jm = new JMenu("Help"));
81 addMenuItemCallback(jm, "About", "jcallback_about_event");
83 cp.add(pp = new PuzzlePanel(), BorderLayout.CENTER);
84 pp.addKeyListener(new KeyAdapter() {
85 public void keyPressed(KeyEvent e) {
87 int shift = e.isShiftDown() ? MOD_SHFT : 0;
88 int ctrl = e.isControlDown() ? MOD_CTRL : 0;
89 switch (e.getKeyCode()) {
90 case KeyEvent.VK_LEFT:
91 case KeyEvent.VK_KP_LEFT:
92 key = shift | ctrl | CURSOR_LEFT;
94 case KeyEvent.VK_RIGHT:
95 case KeyEvent.VK_KP_RIGHT:
96 key = shift | ctrl | CURSOR_RIGHT;
99 case KeyEvent.VK_KP_UP:
100 key = shift | ctrl | CURSOR_UP;
102 case KeyEvent.VK_DOWN:
103 case KeyEvent.VK_KP_DOWN:
104 key = shift | ctrl | CURSOR_DOWN;
106 case KeyEvent.VK_PAGE_UP:
107 key = shift | ctrl | MOD_NUM_KEYPAD | '9';
109 case KeyEvent.VK_PAGE_DOWN:
110 key = shift | ctrl | MOD_NUM_KEYPAD | '3';
112 case KeyEvent.VK_HOME:
113 key = shift | ctrl | MOD_NUM_KEYPAD | '7';
115 case KeyEvent.VK_END:
116 key = shift | ctrl | MOD_NUM_KEYPAD | '1';
119 if (e.getKeyCode() >= KeyEvent.VK_NUMPAD0 && e.getKeyCode() <=KeyEvent.VK_NUMPAD9) {
120 key = MOD_NUM_KEYPAD | (e.getKeyCode() - KeyEvent.VK_NUMPAD0+'0');
125 runtimeCall("jcallback_key_event", new int[] {0, 0, key});
128 public void keyTyped(KeyEvent e) {
129 runtimeCall("jcallback_key_event", new int[] {0, 0, e.getKeyChar()});
132 pp.addMouseListener(new MouseAdapter() {
133 public void mouseReleased(MouseEvent e) {
134 mousePressedReleased(e, true);
136 public void mousePressed(MouseEvent e) {
138 mousePressedReleased(e, false);
140 private void mousePressedReleased(MouseEvent e, boolean released) {
142 if ((e.getModifiers() & (InputEvent.BUTTON2_MASK | InputEvent.SHIFT_MASK)) != 0)
143 button = MIDDLE_BUTTON;
144 else if ((e.getModifiers() & (InputEvent.BUTTON3_MASK | InputEvent.ALT_MASK)) != 0)
145 button = RIGHT_BUTTON;
146 else if ((e.getModifiers() & (InputEvent.BUTTON1_MASK)) != 0)
147 button = LEFT_BUTTON;
151 button += LEFT_RELEASE - LEFT_BUTTON;
152 runtimeCall("jcallback_key_event", new int[] {e.getX(), e.getY(), button});
155 pp.addMouseMotionListener(new MouseMotionAdapter() {
156 public void mouseDragged(MouseEvent e) {
158 if ((e.getModifiers() & (InputEvent.BUTTON2_MASK | InputEvent.SHIFT_MASK)) != 0)
159 button = MIDDLE_DRAG;
160 else if ((e.getModifiers() & (InputEvent.BUTTON3_MASK | InputEvent.ALT_MASK)) != 0)
164 runtimeCall("jcallback_key_event", new int[] {e.getX(), e.getY(), button});
167 pp.addComponentListener(new ComponentAdapter() {
168 public void componentResized(ComponentEvent e) {
172 pp.setFocusable(true);
174 timer = new Timer(20, new ActionListener() {
175 public void actionPerformed(ActionEvent e) {
176 runtimeCall("jcallback_timer_func", new int[0]);
181 gameid = getParameter("game_id");
182 } catch (java.lang.NullPointerException ex) {
185 if (gameid == null) {
188 puzzle_args = new String[2];
189 puzzle_args[0] = "puzzle";
190 puzzle_args[1] = gameid;
192 SwingUtilities.invokeLater(new Runnable() {
194 runtime.start(puzzle_args);
198 } catch (Exception ex) {
199 ex.printStackTrace();
203 public void destroy() {
204 SwingUtilities.invokeLater(new Runnable() {
207 if (mainWindow != null) {
208 mainWindow.dispose();
215 protected void handleResized() {
216 pp.createBackBuffer(pp.getWidth(), pp.getHeight(), colors[0]);
217 runtimeCall("jcallback_resize", new int[] {pp.getWidth(), pp.getHeight()});
220 private JMenuItem addMenuItemCallback(JMenu jm, String name, final String callback, final int arg) {
221 return addMenuItemCallback(jm, name, callback, new int[] {arg}, false);
224 private JMenuItem addMenuItemCallback(JMenu jm, String name, final String callback) {
225 return addMenuItemCallback(jm, name, callback, new int[0], false);
228 private JMenuItem addMenuItemCallback(JMenu jm, String name, final String callback, final int[] args, boolean checkbox) {
231 jm.add(jmi = new JCheckBoxMenuItem(name));
233 jm.add(jmi = new JMenuItem(name));
234 jmi.addActionListener(new ActionListener() {
235 public void actionPerformed(ActionEvent e) {
236 runtimeCall(callback, args);
242 protected void runtimeCall(String func, int[] args) {
243 if (runtimeCallWithResult(func, args) == 42 && mainWindow != null) {
248 protected int runtimeCallWithResult(String func, int[] args) {
250 return runtime.call(func, args);
251 } catch (Runtime.CallException ex) {
252 ex.printStackTrace();
257 private void buildConfigureMenuItem() {
258 if (typeMenu.isVisible()) {
259 typeMenu.addSeparator();
261 typeMenu.setVisible(true);
263 typeMenuItems[customMenuItemIndex] =
264 addMenuItemCallback(typeMenu, "Custom...",
265 "jcallback_config_event",
266 new int[] {CFG_SETTINGS}, true);
269 private void addTypeItem
270 (JMenu targetMenu, String name, int newId, final int ptrGameParams) {
272 typeMenu.setVisible(true);
273 typeMenuItems[newId] =
274 addMenuItemCallback(targetMenu, name,
275 "jcallback_preset_event",
276 new int[] {ptrGameParams}, true);
279 private void addTypeSubmenu
280 (JMenu targetMenu, String name, int newId) {
282 JMenu newMenu = new JMenu(name);
283 newMenu.setVisible(true);
284 typeMenuItems[newId] = newMenu;
285 targetMenu.add(newMenu);
288 public int call(int cmd, int arg1, int arg2, int arg3) {
291 case 0: // initialize
292 if (mainWindow != null) mainWindow.setTitle(runtime.cstring(arg1));
293 if ((arg2 & 1) != 0) buildConfigureMenuItem();
294 if ((arg2 & 2) != 0) addStatusBar();
295 if ((arg2 & 4) != 0) solveCommand.setEnabled(true);
296 colors = new Color[arg3];
298 case 1: // configure Type menu
301 typeMenuItems = new JMenuItem[arg2 + 2];
302 typeMenuItems[arg2] = typeMenu;
303 customMenuItemIndex = arg2 + 1;
305 } else if (xarg1 != 0) {
306 addTypeItem((JMenu)typeMenuItems[arg2],
307 runtime.cstring(arg1), arg3, xarg1);
309 addTypeSubmenu((JMenu)typeMenuItems[arg2],
310 runtime.cstring(arg1), arg3);
313 case 2: // MessageBox
314 JOptionPane.showMessageDialog(this, runtime.cstring(arg2), runtime.cstring(arg1), arg3 == 0 ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.ERROR_MESSAGE);
317 pp.setPreferredSize(new Dimension(arg1, arg2));
318 if (mainWindow != null) mainWindow.pack();
320 if (mainWindow != null) mainWindow.setVisible(true);
322 case 4: // drawing tasks
325 String text = runtime.cstring(arg2);
326 if (text.equals("")) text = " ";
327 statusBar.setText(text);
330 gg = pp.backBuffer.createGraphics();
331 if (arg2 != 0 || arg3 != 0 ||
332 arg2 + xarg2 != getWidth() ||
333 arg3 + xarg3 != getHeight()) {
334 int left = arg2, right = arg2 + xarg2;
335 int top = arg3, bottom = arg3 + xarg3;
336 int width = getWidth(), height = getHeight();
337 gg.setColor(colors != null ? colors[0] : Color.black);
338 gg.fillRect(0, 0, left, height);
339 gg.fillRect(right, 0, width-right, height);
340 gg.fillRect(0, 0, width, top);
341 gg.fillRect(0, bottom, width, height-bottom);
342 gg.setClip(left, top, right-left, bottom-top);
345 case 2: gg.dispose(); pp.repaint(); break;
346 case 3: gg.setClip(arg2, arg3, xarg1, xarg2); break;
348 if (arg2 == 0 && arg3 == 0) {
349 gg.setClip(0, 0, getWidth(), getHeight());
351 gg.setClip(arg2, arg3, getWidth()-2*arg2, getHeight()-2*arg3);
355 gg.setColor(colors[xarg3]);
356 gg.fillRect(arg2, arg3, xarg1, xarg2);
359 gg.setColor(colors[xarg3]);
360 gg.drawLine(arg2, arg3, xarg1, xarg2);
363 xPoints = new int[arg2];
364 yPoints = new int[arg2];
368 gg.setColor(colors[arg3]);
369 gg.fillPolygon(xPoints, yPoints, xPoints.length);
371 gg.setColor(colors[arg2]);
372 gg.drawPolygon(xPoints, yPoints, xPoints.length);
376 gg.setColor(colors[arg3]);
377 gg.fillOval(xarg1-xarg3, xarg2-xarg3, xarg3*2, xarg3*2);
379 gg.setColor(colors[arg2]);
380 gg.drawOval(xarg1-xarg3, xarg2-xarg3, xarg3*2, xarg3*2);
383 for(int i=0; i<blitters.length; i++) {
384 if (blitters[i] == null) {
385 blitters[i] = new BufferedImage(arg2, arg3, BufferedImage.TYPE_3BYTE_BGR);
389 throw new RuntimeException("No free blitter found!");
390 case 11: blitters[arg2] = null; break;
392 timer.start(); break;
397 case 5: // more arguments
402 case 6: // polygon vertex
407 gg.setColor(colors[arg2]);
409 String text = runtime.utfstring(arg3);
410 Font ft = new Font((xarg3 & 0x10) != 0 ? "Monospaced" : "Dialog",
412 int height100 = this.getFontMetrics(ft).getHeight();
413 ft = ft.deriveFont(arg1 * 100 / (float)height100);
414 FontMetrics fm = this.getFontMetrics(ft);
415 int asc = fm.getAscent(), desc = fm.getDescent();
416 if ((xarg3 & ALIGN_VCENTRE) != 0)
417 xarg2 += asc - (asc+desc)/2;
418 int wid = fm.stringWidth(text);
419 if ((xarg3 & ALIGN_HCENTRE) != 0)
421 else if ((xarg3 & ALIGN_HRIGHT) != 0)
424 gg.drawString(text, xarg1, xarg2);
427 case 8: // blitter_save
428 Graphics g2 = blitters[arg1].createGraphics();
429 g2.drawImage(pp.backBuffer, 0, 0, blitters[arg1].getWidth(), blitters[arg1].getHeight(),
430 arg2, arg3, arg2 + blitters[arg1].getWidth(), arg3 + blitters[arg1].getHeight(), this);
433 case 9: // blitter_load
434 gg.drawImage(blitters[arg1], arg2, arg3, this);
436 case 10: // dialog_init
437 dlg= new ConfigDialog(this, runtime.cstring(arg1));
439 case 11: // dialog_add_control
445 String name = runtime.cstring(xarg3);
448 dlg.addTextBox(ptr, name, runtime.cstring(sval_ptr));
451 dlg.addCheckBox(ptr, name, ival != 0);
454 dlg.addComboBox(ptr, name, runtime.cstring(sval_ptr), ival);
462 case 13: // tick a menu item
463 if (arg1 < 0) arg1 = customMenuItemIndex;
464 for (int i = 0; i < typeMenuItems.length; i++) {
465 if (typeMenuItems[i] instanceof JCheckBoxMenuItem) {
466 ((JCheckBoxMenuItem)typeMenuItems[i]).setSelected
472 if (cmd >= 1024 && cmd < 2048) { // palette
473 colors[cmd-1024] = new Color(arg1, arg2, arg3);
476 pp.setBackground(colors[0]);
477 if (statusBar != null) statusBar.setBackground(colors[0]);
478 this.setBackground(colors[0]);
482 } catch (Throwable ex) {
483 ex.printStackTrace();
489 private void addStatusBar() {
490 statusBar = new JLabel("test");
491 statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED));
492 getContentPane().add(BorderLayout.SOUTH,statusBar);
496 public static void main(String[] args) {
497 final PuzzleApplet a = new PuzzleApplet();
498 JFrame jf = new JFrame("Loading...");
499 jf.getContentPane().setLayout(new BorderLayout());
500 jf.getContentPane().add(a, BorderLayout.CENTER);
504 jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
505 jf.addWindowListener(new WindowAdapter() {
506 public void windowClosing(WindowEvent e) {
514 public static class PuzzlePanel extends JPanel {
516 private static final long serialVersionUID = 1L;
517 protected BufferedImage backBuffer;
519 public PuzzlePanel() {
520 setPreferredSize(new Dimension(100,100));
521 createBackBuffer(100,100, Color.black);
524 public void createBackBuffer(int w, int h, Color bg) {
525 if (w > 0 && h > 0) {
526 backBuffer = new BufferedImage(w,h, BufferedImage.TYPE_3BYTE_BGR);
527 Graphics g = backBuffer.createGraphics();
529 g.fillRect(0, 0, w, h);
534 protected void paintComponent(Graphics g) {
535 g.drawImage(backBuffer, 0, 0, this);
539 public static class ConfigComponent {
541 public int configItemPointer;
542 public JComponent component;
544 public ConfigComponent(int type, int configItemPointer, JComponent component) {
546 this.configItemPointer = configItemPointer;
547 this.component = component;
551 public class ConfigDialog extends JDialog {
553 private GridBagConstraints gbcLeft = new GridBagConstraints(
554 GridBagConstraints.RELATIVE, GridBagConstraints.RELATIVE, 1, 1,
555 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE,
556 new Insets(0, 0, 0, 0), 0, 0);
557 private GridBagConstraints gbcRight = new GridBagConstraints(
558 GridBagConstraints.RELATIVE, GridBagConstraints.RELATIVE,
559 GridBagConstraints.REMAINDER, 1, 1.0, 0,
560 GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
561 new Insets(5, 5, 5, 5), 0, 0);
562 private GridBagConstraints gbcBottom = new GridBagConstraints(
563 GridBagConstraints.RELATIVE, GridBagConstraints.RELATIVE,
564 GridBagConstraints.REMAINDER, GridBagConstraints.REMAINDER,
565 1.0, 1.0, GridBagConstraints.CENTER,
566 GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0);
568 private static final long serialVersionUID = 1L;
569 private List components = new ArrayList();
571 public ConfigDialog(JApplet parent, String title) {
572 super(JOptionPane.getFrameForComponent(parent), title, true);
573 getContentPane().setLayout(new GridBagLayout());
576 public void addTextBox(int ptr, String name, String value) {
577 getContentPane().add(new JLabel(name), gbcLeft);
578 JComponent c = new JTextField(value, 25);
579 getContentPane().add(c, gbcRight);
580 components.add(new ConfigComponent(C_STRING, ptr, c));
584 public void addCheckBox(int ptr, String name, boolean selected) {
585 JComponent c = new JCheckBox(name, selected);
586 getContentPane().add(c, gbcRight);
587 components.add(new ConfigComponent(C_BOOLEAN, ptr, c));
590 public void addComboBox(int ptr, String name, String values, int selected) {
591 getContentPane().add(new JLabel(name), gbcLeft);
592 StringTokenizer st = new StringTokenizer(values.substring(1), values.substring(0,1));
593 JComboBox c = new JComboBox();
594 c.setEditable(false);
595 while(st.hasMoreTokens())
596 c.addItem(st.nextToken());
597 c.setSelectedIndex(selected);
598 getContentPane().add(c, gbcRight);
599 components.add(new ConfigComponent(C_CHOICES, ptr, c));
602 public void finish() {
603 JPanel buttons = new JPanel(new GridLayout(1, 2, 5, 5));
604 getContentPane().add(buttons, gbcBottom);
606 buttons.add(b=new JButton("OK"));
607 b.addActionListener(new ActionListener() {
608 public void actionPerformed(ActionEvent e) {
613 getRootPane().setDefaultButton(b);
614 buttons.add(b=new JButton("Cancel"));
615 b.addActionListener(new ActionListener() {
616 public void actionPerformed(ActionEvent e) {
620 setDefaultCloseOperation(DISPOSE_ON_CLOSE);
622 setLocationRelativeTo(null);
625 private void save() {
626 for (int i = 0; i < components.size(); i++) {
627 ConfigComponent cc = (ConfigComponent) components.get(i);
630 JTextField jtf = (JTextField)cc.component;
631 runtimeCall("jcallback_config_set_string", new int[] {cc.configItemPointer, runtime.strdup(jtf.getText())});
634 JCheckBox jcb = (JCheckBox)cc.component;
635 runtimeCall("jcallback_config_set_boolean", new int[] {cc.configItemPointer, jcb.isSelected()?1:0});
638 JComboBox jcm = (JComboBox)cc.component;
639 runtimeCall("jcallback_config_set_choice", new int[] {cc.configItemPointer, jcm.getSelectedIndex()});
643 runtimeCall("jcallback_config_ok", new int[0]);