fixed heinous bug in switchbox routing
[slipway.git] / src / edu / berkeley / slipway / gui / Gui.java
1 package edu.berkeley.slipway.gui;
2
3 import com.atmel.fpslic.*;
4 import edu.berkeley.slipway.*;
5 import static com.atmel.fpslic.FpslicConstants.*;
6 import static com.atmel.fpslic.FpslicUtil.*;
7 import edu.berkeley.slipway.*;
8 import java.awt.*;
9 import java.awt.geom.*;
10 import java.awt.event.*;
11 import java.awt.color.*;
12 import org.ibex.util.*;
13 import java.io.*;
14 import java.util.*;
15 import javax.swing.*;
16 import static edu.berkeley.slipway.gui.GuiConstants.*;
17
18 public class Gui extends ZoomingPanel implements KeyListener, MouseMotionListener {
19
20     Graphics2D g;
21     G gg;
22
23     Fpslic at40k;
24     FtdiBoard drone;
25
26     private Cell[][] ca = new Cell[128][];
27
28     //public static final Color nonselectedcell = new Color(0x44, 0x44, 0x44);
29     public static final Color nonselectedcell = new Color(0xee, 0xee, 0xee);
30     public static final Color selectedcell    = new Color(0x00, 0x00, 0x00);
31
32     public void writeMode4() {
33         try {
34             final JFileChooser fc = new JFileChooser();
35             int returnVal = fc.showSaveDialog(this);
36             Writer pw = new OutputStreamWriter(new FileOutputStream(fc.getSelectedFile()));
37             FpslicUtil.writeMode4(pw, drone);
38             pw.flush();
39             pw.close();
40             System.err.println("done writing");
41         } catch (Exception e) {
42             e.printStackTrace();
43         }
44     }
45
46     public void readMode4() {
47         try {
48             final JFileChooser fc = new JFileChooser();
49             int returnVal = fc.showOpenDialog(this);
50             FpslicUtil.readMode4(new FileInputStream(fc.getSelectedFile()), drone);
51             System.err.println("done reading");
52             repaint();
53         } catch (Exception e) {
54             e.printStackTrace();
55         }
56     }
57
58     public Gui(Fpslic at40k, FtdiBoard drone) {
59         this(at40k, drone, 24, 24);
60     }
61     public Gui(Fpslic at40k, FtdiBoard drone, int width, int height) {
62         this.at40k = at40k;
63         this.drone = drone;
64         for(int i=0; i<ca.length; i++)
65             ca[i] = new Cell[128];
66         for(int x=0; x<width; x++)
67             for(int y=0; y<height; y++)
68                 new Cell(x,y, at40k.cell(x, y));
69
70
71         new Thread() {
72             public void run() {
73                 while(true) scan();
74             }
75         }.start();
76
77         /*
78         Fpslic.Cell c = at40k.cell(0,0);
79         for(int i=0; i<256; i++) {
80             c.ylut(i);
81             System.out.println(c.printYLut());
82         }
83         */
84     }
85
86     public class Cell {
87         Fpslic.Cell cell;
88         boolean in = false;
89         public boolean scanme = false;
90         public boolean xon = false;
91         public boolean yon = false;
92         public boolean xknown = false;
93         public boolean yknown = false;
94         int _x, _y;
95         public Cell(int x, int y, Fpslic.Cell cell) {
96             _x = x;
97             _y = y;
98             ca[_x][_y] = this;
99             this.cell = cell;
100             cells.add(this);
101         }
102         public void clear() {
103             gg.color(in ? selectedcell : (scanme ? new Color(0xbb, 0xbb, 0xbb) : nonselectedcell));
104             g.fillRect(0, 0, SIZE, SIZE);
105         }
106         public void draw() {
107
108             if (cell.relevant() || scanme) {
109                 drawWires();
110                 drawLocal();
111                 
112                 AffineTransform t = g.getTransform();
113                 
114                 drawBuffer();
115                 g.transform(rotateInnerTransform());
116                 drawMux();
117                 drawRegister();
118                 drawInternalRouting();
119                 g.setTransform(t);
120                 
121                 drawGates();
122             }
123             drawBorder();
124         }
125         public void drawBuffer() {
126             /*
127             if (!cell.out_relevant()) return;
128
129             GeneralPath p = new GeneralPath();
130             p.moveTo(24, 61);
131             p.lineTo(22, 68);
132             p.lineTo(29, 66);
133             p.lineTo(24, 61);
134             gg.color(cell.oe() == NONE ? Color.white : Color.green);
135             g.fill(p);
136             gg.color(Color.green);
137             g.draw(p);
138
139             gg.color(Color.magenta);
140             if (cell.oe() == V4) {
141                 gg.line(24, 62, 16, 63);
142             } else if (cell.oe() == H4) {
143                 gg.line(24, 67, 24, 76);
144             }
145             */
146         }
147         public void drawWires() {
148             gg.color(MAGENTA);
149             for(int i=0; i<5; i++)
150                 if (i!=3)
151                 if (cell.hwire(i).isDriven()) {
152                     gg.color(cell.out(i) ? ORANGE : MAGENTA);
153                     gg.line(0, SIZE-(2*(1+RINGS)+2*i), SIZE, SIZE-(2*(1+RINGS)+2*i));
154                 }
155             for(int i=0; i<5; i++)
156                 if (i!=3)
157                 if (cell.vwire(i).isDriven()) {
158                     gg.color(cell.out(i) ? ORANGE : MAGENTA);
159                     gg.line(2*(1+RINGS)+2*i, 0, 2*(1+RINGS)+2*i, SIZE);
160                 }
161             if (cell.zi_to_xlut_relevant()) wire(cell.zi(), true);
162             if (cell.zi_to_ylut_relevant()) wire(cell.zi(), false);
163             if (cell.zi_to_xlut_relevant()) wire(cell.wi(), true);
164             if (cell.zi_to_ylut_relevant()) wire(cell.wi(), false);
165         }
166
167         public void wire(int plane, boolean xlut) {
168             if (!(plane >= L0 && plane <= L4 && cell.vx(plane))) return;
169             if (xlut ? xlut_relevant(cell) : cell.ylut_relevant())
170                 route(new P(17 - 2*(plane-L0), 8),
171                       rotateInner(xlut ? new P(38, 18) : new P(64, 18)),
172                       3);
173         }
174
175         public P corner(int corner, int size, int ring) {
176             switch(corner) {
177                 case NW: return new P(0    +2*ring,  size -2*ring);
178                 case SW: return new P(0    +2*ring,  0    +2*ring);
179                 case NE: return new P(size -2*ring,  size -2*ring);
180                 case SE: return new P(size -2*ring,  0    +2*ring);
181                 default: return null;
182             }
183         }
184
185         public void drawInternalRouting() {
186             gg.color(ORANGE);
187             if (cell.fb_relevant()) {
188                 if (cell.f()) {
189                     gg.line(51, 74, 37, 74);
190                     gg.line(37, 74, 51, 12);
191                 } else if (cell.c() == XLUT) {
192                     gg.color(LIGHTRED);
193                     gg.line(33, 52, 51, 52);
194                     gg.line(51, 52, 51, 12);
195                 } else if (cell.c() == YLUT) {
196                     gg.color(LIGHTBLUE);
197                     gg.line(67, 52, 51, 52);
198                     gg.line(51, 52, 51, 12);
199                 } else {
200                     gg.line(51, 56, 41, 56);
201                     gg.line(41, 56, 51, 12);
202                 }
203                 if (xlut_relevant(cell)) {
204                     gg.line(52, 12, XLUT_OUTPUT_POINT.getX(), 12);
205                     gg.line(XLUT_OUTPUT_POINT.getX(), 12, XLUT_OUTPUT_POINT.getX(), 32);
206                 }
207                 if (cell.ylut_relevant()) {
208                     gg.line(52, 12, YLUT_OUTPUT_POINT.getX(), 12);
209                     gg.line(YLUT_OUTPUT_POINT.getX(), 12, YLUT_OUTPUT_POINT.getX(), 32);
210                 }
211             }
212         }
213
214         public void drawLocal() {
215             if (!cell.ylut_relevant() && !xlut_relevant(cell)) return;
216
217             P in = rotateOuter(new P(HOFF, 0));
218             P join = rotateInner(new P(HOFF, CORE_OFFSET));
219             int rot = rot();
220             switch(rot) {
221                 case 0: case 2:
222                     join = new P(in.getX(), join.getY());
223                     break;
224                 case 1: case 3:
225                     join = new P(join.getX(), in.getY());
226                     break;
227             }
228
229             // x-input to cell
230             gg.color(RED);
231             P xi  = corner(cell.xi(), SIZE, 4);
232             if (((cell.xlut_relevant() && cell.xi_to_xlut_relevant()) ||
233                 (cell.ylut_relevant() && cell.xi_to_ylut_relevant()))
234                 && (cell.xi() != NONE) && (cell.xi() < L0 || cell.xi() > L4)
235                 ) {
236                 P xi2 = corner(cell.xi(), SIZE + 2*BEVEL, -1).translate(-BEVEL, -BEVEL);
237                 switch(cell.xi()) {
238                     case NW: case NE:
239                         xi = translate(xi, 0, -3);
240                         xi2 = translate(xi2, 0, -3);
241                         break;
242                     case SW: case SE:
243                         xi = translate(xi, 0, 3);
244                         xi2 = translate(xi2, 0, 3);
245                         break;
246                 }
247                 gg.line(xi2, xi);
248             }
249
250             if (xlut_relevant(cell)) {
251
252                 if (cell.xi_to_xlut_relevant() && xi != null)
253                     route(xi, rotateInner(new P(SIZE - CORE_OFFSET - CORE_SIZE/2 - CORE_SIZE / 3, 20)), 4);
254
255                 // xlut y-input
256                 gg.color(BLUE);
257                 if (cell.yi_to_xlut_relevant())
258                     route(in, rotateInner(new P(SIZE - CORE_OFFSET - CORE_SIZE/2 - CORE_SIZE / 6, 20)), 5);
259
260                 // xlut output
261                 int xring = 4;
262                 gg.color(cell.xo() ? ORANGE : LIGHTRED);
263                 P xout = rotateInner(new P(SIZE-CORE_OFFSET-CORE_SIZE+17 - 2, CORE_OFFSET + CORE_SIZE - 3));
264                 if (cell.xo()) {
265                     xout = rotateInner(new P(51, 74));
266                     gg.line(rotateInner(new P(51, 62)), xout);
267                 } else if (cell.xo_relevant()) {
268                     gg.line(rotateInner(XLUT_OUTPUT_POINT), xout);
269                 }
270                 if (cell.xo_relevant(NE)) {
271                     gg.line(corner(NE, SIZE, xring).translate(0, 3), corner(NE, SIZE, 0).translate(0, 3));
272                     route(xout, corner(NE, SIZE, xring).translate(0, 3), xring);
273                 }
274                 if (cell.xo_relevant(NW)) {
275                     gg.line(corner(NW, SIZE, xring).translate(0, 3),  corner(NW, SIZE, 0).translate(0, 3));
276                     route(xout, corner(NW, SIZE, xring).translate(0, 3),  xring);
277                 }
278                 if (cell.xo_relevant(SE)) {
279                     gg.line(corner(SE, SIZE, xring).translate(0, -3), corner(SE, SIZE, 0).translate(0, -3));
280                     route(xout, corner(SE, SIZE, xring).translate(0, -3), xring);
281                 }
282                 if (cell.xo_relevant(SW)) {
283                     gg.line(corner(SW, SIZE, xring).translate(0, -3),  corner(SW, SIZE, 0).translate(0, -3));
284                     route(xout, corner(SW, SIZE, xring).translate(0, -3),  xring);
285                 }
286             }
287
288             if (cell.ylut_relevant()) {
289
290                 // ylut y-input
291                 gg.color(BLUE);
292                 if (cell.yi_to_ylut_relevant())
293                     route(in, rotateInner(new P(SIZE - CORE_OFFSET - CORE_SIZE/2 + CORE_SIZE / 6, 20)), 5);
294
295                 // ylut x-input
296                 gg.color(RED);
297                 if (xi != null && cell.xi_to_ylut_relevant())
298                     route(xi, rotateInner(new P(SIZE - CORE_OFFSET - CORE_SIZE/2 + CORE_SIZE / 3, 20)), 4);
299
300                 // lines directly from the ylut output to the four neighbors
301                 gg.color(cell.yo() ? ORANGE : LIGHTBLUE);
302                 P yout = rotateInner(new P(SIZE-CORE_OFFSET-CORE_SIZE+51 - 2, CORE_OFFSET + CORE_SIZE - 3));
303                 if (cell.yo()) {
304                     yout = rotateInner(new P(51, 74));
305                     gg.line(rotateInner(new P(51, 62)), yout);
306                 } else if (cell.yo_relevant()) {
307                     gg.line(rotateInner(YLUT_OUTPUT_POINT), yout);
308                 }
309                 if (cell.yo_relevant(NORTH)) route(yout, new P(SIZE-40, SIZE+ 0), 2);
310                 if (cell.yo_relevant(EAST))  route(yout, new P(SIZE+ 0,      40), 2);
311                 if (cell.yo_relevant(SOUTH)) route(yout, new P(     40,       0), 2);
312                 if (cell.yo_relevant(WEST))  route(yout, new P(      0, SIZE-40), 2);
313             }
314
315         }
316
317         private AffineTransform rotateOuterTransform() {
318             int rot = rot();
319             AffineTransform a = new AffineTransform();
320             a.rotate((Math.PI/2) * rot);
321             switch(rot) {
322                 case 0: break;
323                 case 1: a.translate(0,  -SIZE); break;
324                 case 2: a.translate(-SIZE, -SIZE); break;
325                 case 3: a.translate(-SIZE, 0); break;
326             }
327             return a;
328         }
329
330         private P rotateOuter(P p) { return p.transform(rotateOuterTransform()); }
331         private P rotateInner(P p) { return p.transform(rotateInnerTransform()); }
332         private P unRotateInner(P p) { return p.inverseTransform(rotateInnerTransform()); }
333
334         private AffineTransform rotateInnerTransform() {
335             int rot = rot();            
336             AffineTransform a = new AffineTransform();
337             a.translate(SIZE-CORE_SIZE-CORE_OFFSET, CORE_OFFSET);
338             a.rotate((Math.PI/2) * rot);
339             switch(rot) {
340                 case 0: break;
341                 case 1: a.translate(0,  -CORE_SIZE); break;
342                 case 2: a.translate(-CORE_SIZE, -CORE_SIZE); break;
343                 case 3: a.translate(-CORE_SIZE, 0); break;
344             }
345             a.translate(-1 * (SIZE-CORE_SIZE-CORE_OFFSET), -CORE_OFFSET);
346             return a;
347         }
348
349
350         private P project(P p1, int ring) {
351             double north = Math.abs( (SIZE-(ring*2)) - p1.getY() );
352             double south = Math.abs( (     (ring*2)) - p1.getY() );
353             double east  = Math.abs( (SIZE-(ring*2)) - p1.getX() );
354             double west  = Math.abs( (     (ring*2)) - p1.getX() );
355             if (north < south && north < east && north < west) return new P(p1.x,        SIZE-ring*2);
356             else if (south < east && south < west)             return new P(p1.x,        ring*2);
357             else if (east < west)                              return new P(SIZE-ring*2, p1.y);
358             else                                               return new P(ring*2,      p1.y);
359
360         }
361
362         private void route(P p1, P p2, int ring) {
363             int ringpos = ring * 2;
364             P projected = project(p1, ring);
365             gg.line(p1, projected);
366             p1 = projected;
367
368             projected = project(p2, ring);
369             gg.line(p2, projected);
370             p2 = projected;
371
372             if (p1.x==p2.x || p1.y==p2.y) {
373                 gg.line(p1, p2);
374                 return;
375             }
376
377             if ((p1.x==SIZE-ring*2 || p1.x==ring*2) && !(p1.y==SIZE-ring*2 || p1.y==ring*2)) {
378                 P p3 = new P(p1.x, p2.y > SIZE/2 ? SIZE-ring*2 : ring*2);
379                 gg.line(p1, p3);
380                 route(p3, p2, ring);
381             } else if ((p1.y==SIZE-ring*2 || p1.y==ring*2) && !(p1.x==SIZE-ring*2 || p1.x==ring*2)) {
382                 P p3 = new P(p2.x > SIZE/2 ? SIZE-ring*2 : ring*2, p1.y);
383                 gg.line(p1, p3);
384                 route(p3, p2, ring);
385             } else
386                 route(p2, p1, ring);
387         }
388         
389         private int rot() {
390             int rot = 0;
391             switch(cell.yi()) {
392                 case SOUTH: rot = 0; break;
393                 case NORTH: rot = 2; break;
394                 case EAST: rot = 1; break;
395                 case WEST: rot = 3; break;
396                 default: {
397                     // FIXME: choose based on xin
398                     if (cell.north() != null && cell.north().yi()==SOUTH) { rot = 0; break; }
399                     if (cell.south() != null && cell.south().yi()==NORTH) { rot = 2; break; }
400                     if (cell.east()  != null && cell.east().yi()==WEST) { rot = 3; break; }
401                     if (cell.west()  != null && cell.west().yi()==EAST) { rot = 1; break; }
402                 }
403             }
404             return rot;
405         }
406         
407         public void drawGates() {
408             AffineTransform t = g.getTransform();
409             try {
410                 g.translate(SIZE-CORE_SIZE-CORE_OFFSET, CORE_OFFSET);
411                 
412                 int rot = rot();
413                 g.rotate((Math.PI/2) * rot);
414                 switch(rot) {
415                     case 0: break;
416                     case 1: g.translate(0,  -CORE_SIZE); break;
417                     case 2: g.translate(-CORE_SIZE, -CORE_SIZE); break;
418                     case 3: g.translate(-CORE_SIZE, 0); break;
419                 }
420
421                 //gg.color(Color.gray);
422                 //g.drawRect(0, 0, CORE_SIZE, CORE_SIZE);
423                 //g.scale(1, -1);
424
425
426                 g.translate(2,   5f);
427                 if (xlut_relevant(cell) || scanme) {
428                     Gate gate = getGate(cell.xlut(), true);
429                     gate.draw(g,
430                               !xknown ? Color.gray : xon ? Color.red : Color.white,
431                               (xon && xknown) ? Color.white : Color.red,
432                               xon ? Color.white : Color.red
433                               );
434                 }
435
436                 g.translate(34f, 0f);
437                 if (cell.ylut_relevant() || scanme) {
438                     Gate gate = getGate(cell.ylut(), false);
439                     gate.draw(g,
440                               !yknown ? Color.gray : yon ? Color.blue : Color.white,
441                               (yon && yknown) ? Color.white : Color.blue,
442                               yon ? Color.white : Color.blue
443                               );
444                 }
445
446             } finally {
447                 g.setTransform(t);
448             }
449         }
450         public void drawMux() {
451             if (!cell.c_relevant()) return;
452             gg.color(Color.black);
453             if (xlut_relevant(cell) && (cell.c() == ZMUX || cell.c() == XLUT)) {
454                 gg.color(LIGHTRED);
455                 gg.line(XLUT_OUTPUT_POINT, new P(XLUT_OUTPUT_POINT.getX(), 52));
456                 gg.line(new P(XLUT_OUTPUT_POINT.getX(), 52), new P(51, 52));
457             }
458             if (cell.ylut_relevant() && (cell.c() == ZMUX || cell.c() == YLUT)) {
459                 gg.color(LIGHTBLUE);
460                 gg.line(YLUT_OUTPUT_POINT, new P(YLUT_OUTPUT_POINT.getX(), 52));
461                 gg.line(new P(YLUT_OUTPUT_POINT.getX(), 52), new P(51, 52));
462             }
463             if (cell.c() == ZMUX)
464                 gg.color(ORANGE);
465
466             gg.line(51, 52, 51, 51+23);
467
468             if (cell.register_relevant() && cell.f() && !cell.b()) {
469                 gg.line(51, 56, 60, 56);
470                 gg.line(60, 56, 60, 51+25);
471             } else {
472                 gg.line(51, 51+23, 51, 51+25);
473             }
474
475             if (cell.c() == ZMUX) {
476
477                 gg.color(GREEN);
478                 int plane = cell.zi()+1;
479                 route(unRotateInner(new P(8 + 2*(plane-L0),  76 + 2*(plane-L0))),
480                       new P(51, 20),
481                       3);
482                 gg.line(new P(51, 20), new P(51, 50));
483
484                 GeneralPath p = new GeneralPath();
485                 p.moveTo(45, 50);
486                 p.lineTo(47, 54);
487                 p.lineTo(56, 54);
488                 p.lineTo(58, 50);
489                 p.lineTo(45, 50);
490                 gg.color(WHITE);
491                 gg.g.fill(p);
492
493                 gg.color(ORANGE);
494                 gg.g.draw(p);
495
496             }
497         }
498         public int ccolor() {
499             switch(cell.c()) {
500                 case XLUT: return LIGHTRED;
501                 case YLUT: return LIGHTBLUE;
502                 case ZMUX: return ORANGE;
503             }
504             return BLACK;
505         }
506         public void drawRegister() {
507             if (!cell.register_relevant()) return;
508
509             int dark = ccolor();
510             gg.color(Color.white);
511             g.fillRect(47, 58, 9, 14);
512             gg.color(dark);
513             g.drawRect(47, 58, 9, 14);
514
515             GeneralPath p = new GeneralPath();
516             p.moveTo(56, 70);
517             p.lineTo(53, 68);
518             p.lineTo(56, 66);
519             p.lineTo(56, 70);
520             gg.color(cell.ff_reset_value() ? WHITE : dark);
521             g.fill(p);
522             gg.color(dark);
523             g.draw(p);
524         }
525         public void drawBorder() {
526             gg.color(Color.gray);
527             gg.line(BEVEL, 0, SIZE-BEVEL, 0);
528             gg.line(SIZE, BEVEL, SIZE, SIZE-BEVEL);
529             gg.line(SIZE-BEVEL, SIZE, BEVEL, SIZE);
530             gg.line(0, SIZE-BEVEL, 0, BEVEL);
531             /*            
532             gg.color(0xdddddd);
533             gg.line(0, BEVEL, BEVEL,    0);
534             gg.line(SIZE-BEVEL, 0, SIZE, BEVEL);
535             gg.line(SIZE, SIZE-BEVEL, SIZE-BEVEL, SIZE);
536             gg.line(BEVEL, SIZE, 0, SIZE-BEVEL);
537             */
538         }
539     }
540
541     public void pressed() {
542         dragFrom = oldcell;
543     }
544     public void released() {
545         if (dragFrom == null || oldcell == null) return;
546         if (Math.abs(dragFrom._y - oldcell._y) > 1) return;
547         if (Math.abs(dragFrom._x - oldcell._x) > 1) return;
548         if (dragFrom._x == oldcell._x   && dragFrom._y == oldcell._y+1) oldcell.cell.yi(NORTH);
549         if (dragFrom._x == oldcell._x   && dragFrom._y == oldcell._y-1) oldcell.cell.yi(SOUTH);
550         if (dragFrom._x == oldcell._x+1 && dragFrom._y == oldcell._y)   oldcell.cell.yi(EAST);
551         if (dragFrom._x == oldcell._x-1 && dragFrom._y == oldcell._y)   oldcell.cell.yi(WEST);
552         if (dragFrom._x == oldcell._x+1 && dragFrom._y == oldcell._y+1) oldcell.cell.xi(NE);
553         if (dragFrom._x == oldcell._x+1 && dragFrom._y == oldcell._y-1) oldcell.cell.xi(SE);
554         if (dragFrom._x == oldcell._x-1 && dragFrom._y == oldcell._y+1) oldcell.cell.xi(NW);
555         if (dragFrom._x == oldcell._x-1 && dragFrom._y == oldcell._y-1) oldcell.cell.xi(SW);
556         repaint();
557     }
558     public void drawKeyboard(Image keyboardImage, Graphics2D g) {
559         /*
560                 int width = 300;
561                 int height = (keyboardImage.getHeight(null) * width) / keyboardImage.getWidth(null);
562                 g.drawImage(keyboardImage,
563                             0, getHeight() - height,
564                             width, getHeight(),
565                             0, 0,
566                             keyboardImage.getWidth(null), keyboardImage.getHeight(null),
567                             null);
568         */
569     }
570
571     public void _paint(Graphics2D g) {
572
573         this.g = g;
574         this.gg = new G(g);
575         g.setStroke(new BasicStroke((float)0.5));
576
577         g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
578         g.setRenderingHint(RenderingHints.KEY_RENDERING,    RenderingHints.VALUE_RENDER_QUALITY);
579
580         AffineTransform t  = g.getTransform();
581         for(Cell c : cells) {
582             g.setTransform(t);
583             g.translate(     c._x * SIZE /*+ (10 * (c._x/4))*/,      c._y * SIZE /*+ (10 * (c._y/4))*/);
584             c.clear();
585         }
586         for(Cell c : cells) {
587             g.setTransform(t);
588             g.translate(     c._x * SIZE /*+ (10 * (c._x/4))*/,      c._y * SIZE /*+ (10 * (c._y/4))*/);
589             c.draw();
590         }
591         g.setTransform(t);
592
593         g.setTransform(new AffineTransform());
594
595         gg.color(selectedcell);
596         g.fillRect(getWidth() - 200, 0, 200, 600);
597         gg.color(Color.white);
598         g.drawRect(getWidth() - 200, 0, 200, 600);
599
600         Cell newcell = whichCell(mousex, mousey);
601         int line = 10;
602         g.setFont(new Font("monospaced", 0, 14));
603         if (newcell != null && newcell.cell != null) {
604             g.drawString("selected: " + newcell._x + "," + newcell._y, getWidth() - 200 + 10, (line += 15));
605             g.drawString("    xlut: " + XLUT_EQUATIONS[newcell.cell.xlut() & 0xff], getWidth() - 200 + 10, (line += 15));
606             g.drawString("    ylut: " + YLUT_EQUATIONS[newcell.cell.ylut() & 0xff], getWidth() - 200 + 10, (line += 15));
607             String xi = "??";
608             switch(newcell.cell.xi()) {
609                 case NW : xi = "NW"; break;
610                 case NE : xi = "NE"; break;
611                 case SW : xi = "SW"; break;
612                 case SE : xi = "SE"; break;
613                 case NONE  : xi = "."; break;
614                 default:  xi = "L"+(newcell.cell.xi()-L0); break;
615             }
616             g.drawString("x-in mux: " + xi, getWidth() - 200 + 10, (line += 15));
617
618             String yi = "??";
619             switch(newcell.cell.yi()) {
620                 case NORTH : yi = "NORTH"; break;
621                 case SOUTH : yi = "SOUTH"; break;
622                 case EAST  : yi = "EAST"; break;
623                 case WEST  : yi = "WEST"; break;
624                 case NONE  : yi = "."; break;
625                 default:     yi = "L"+(newcell.cell.yi()-L0); break;
626             }
627             g.drawString("y-in mux: " + yi, getWidth() - 200 + 10, (line += 15));
628
629             g.drawString("w-in mux: " + (newcell.cell.wi()==NONE ? "." : ("L"+(newcell.cell.wi()-L0))),
630                          getWidth() - 200 + 10, (line += 15));
631             g.drawString("z-in mux: " + (newcell.cell.zi()==NONE ? "." : ("L"+(newcell.cell.zi()-L0))),
632                          getWidth() - 200 + 10, (line += 15));
633             g.drawString("t-in mux: ", getWidth() - 200 + 10, (line += 15));
634
635             g.drawString(" set/rst: " + (newcell.cell.ff_reset_value() ? "reset=SET" : "."),
636                          getWidth() - 200 + 10, (line += 15));
637
638             String outs = "";
639             for(int i=0; i<5; i++) outs += (newcell.cell.out(L0+i) ? (i+" ") : ". ");
640             g.drawString("     out: " + outs,
641                          getWidth() - 200 + 10, (line += 15));
642             String hs = "";
643             for(int i=0; i<5; i++) hs += (newcell.cell.hx(L0+i) ? (i+" ") : ". ");
644             g.drawString("  h conn: " + hs,
645                          getWidth() - 200 + 10, (line += 15));
646             String vs = "";
647             for(int i=0; i<5; i++) vs += (newcell.cell.vx(L0+i) ? (i+" ") : ". ");
648             g.drawString("  v conn: " + vs,
649                          getWidth() - 200 + 10, (line += 15));
650             g.drawString("out enab: " + (newcell.cell.oe()==H4 ? "H4" : newcell.cell.oe()==V4 ? "V4" : "."),
651                          getWidth() - 200 + 10, (line += 15));
652             g.drawString("   c-mux: " + (newcell.cell.c()==ZMUX ? "zmux" : newcell.cell.c()==XLUT ? "x-lut" : "y-lut"),
653                          getWidth() - 200 + 10, (line += 15));
654             g.drawString(" fb src: " + (newcell.cell.f() ? "clocked" : "."),
655                          getWidth() - 200 + 10, (line += 15));
656             g.drawString("  bypass: " + (newcell.cell.b() ? "clocked" : "."),
657                          getWidth() - 200 + 10, (line += 15));
658             g.drawString("   x out: " + (newcell.cell.xo() ? (newcell.cell.b() ? "register" : "center") : "."),
659                          getWidth() - 200 + 10, (line += 15));
660             g.drawString("   y out: " + (newcell.cell.yo() ? (newcell.cell.b() ? "register" : "center") : "."),
661                          getWidth() - 200 + 10, (line += 15));
662
663         }
664         if (shiftkey) {
665             drawKeyboard(keyboard2, g);
666         } else switch(lastChar) {
667             case 'x':
668             case 'y':
669             case 'z':
670             case 'w':
671             case 'o':
672             case 'h':
673             case 'v':
674                 drawKeyboard(keyboard3, g);
675                 break;
676             default:
677                 drawKeyboard(keyboard1, g);
678                 break;
679         }
680
681         while (mousebutton) {
682
683             if (dragFrom == null || oldcell == null) break;
684             if (Math.abs(dragFrom._y - oldcell._y) > 1) break;
685             if (Math.abs(dragFrom._x - oldcell._x) > 1) break;
686             g.setTransform(t);
687             if (dragFrom._x == oldcell._x || dragFrom._y == oldcell._y)
688                 gg.color(BLUE);
689             else
690                 gg.color(RED);
691
692             gg.line( oldcell._x * SIZE + SIZE/2,
693                      oldcell._y * SIZE + SIZE/2,
694                      dragFrom._x * SIZE + SIZE/2,
695                      dragFrom._y * SIZE + SIZE/2, 5);
696             break;
697         }
698
699         this.g = null;
700         this.gg = null;
701     }
702     Cell dragFrom = null;
703
704     public void clear() {
705         Graphics2D g = (Graphics2D)getGraphics();
706         //gg.color(Color.black);
707         //gg.color(Color.lightGray);
708         g.clearRect(0, 0, getWidth(), getHeight());
709     }
710
711     public static final P translate(P p, int dx, int dy) {
712         return new P(p.getX()+dx, p.getY()+dy);
713     }
714
715     public Cell whichCell(int x, int y) {
716         P p = new P(x,y);
717         try {
718             p = p.inverseTransform(transform);
719         } catch (Exception e) {
720             e.printStackTrace();
721         }
722         int col = ((int)p.getX()+0) / SIZE;
723         int row = ((int)p.getY()+0) / SIZE;
724         for(Cell c : cells)
725             if (c._x == col && c._y == row)
726                 return c;
727         return null;
728     }
729
730     public static boolean xlut_relevant(Fpslic.Cell c) {
731         return c.xlut_relevant();
732     }
733
734     public void mouseClicked(MouseEvent e) {
735         final Cell c = whichCell(e.getX(), e.getY());
736         if (c==null) return;
737         scan(c);
738     }
739
740     public void scan() {
741         for(int x=0; x<at40k.getWidth(); x++)
742             for(int y=0; y<at40k.getHeight(); y++)
743                 if (ca[x][y] != null)
744                     if (ca[x][y].scanme)
745                         scan(ca[x][y]);
746     }
747     public void scan(final Gui.Cell c) {
748         try {
749             final Fpslic.Cell cell = c.cell;
750             scan(at40k, cell, NONE, true);
751             boolean safe = !cell.fb_relevant();
752             if (cell.xo()) safe = false;
753             if (cell.yo()) safe = false;
754             for(int i=0; i<5; i++)
755                 if (cell.out(i))
756                     safe = false;
757             if (safe) {
758                 int oldc = cell.c();
759                 if (cell.xlut_relevant()) {
760                     cell.c(XLUT);
761                     drone.readBus(new BCB(c, XLUT));
762                 } else {
763                     c.xknown = false;
764                 }
765                 if (cell.ylut_relevant()) {
766                     cell.c(YLUT);
767                     drone.readBus(new BCB(c, YLUT));
768                 } else {
769                     c.yknown = false;
770                 }
771                 cell.c(oldc);
772             } else {
773                 switch(cell.c()) {
774                     case XLUT:
775                         if (!cell.xlut_relevant()) {
776                             c.xknown = false;
777                         } else {
778                             drone.readBus(new BCB(c, XLUT));
779                         }
780                         if (!cell.yo())
781                         for(Fpslic.Cell c2 : new Fpslic.Cell[] { cell.north(), cell.south(), cell.east(), cell.west() })
782                             if (c2!=null && !c2.relevant()) {
783                                 scan(at40k, cell, NONE, false);
784                                 c2.yo(cell);
785                                 c2.c(YLUT);
786                                 scan(at40k, c2, NONE, true);
787                                 drone.readBus(new BCB(c, YLUT));
788                                 scan(at40k, c2, NONE, false);
789                                 c2.yi(NONE);
790                                 return;
791                             }
792                         c.yknown = false;
793                         break;
794                     case YLUT:
795                         if (!cell.ylut_relevant()) {
796                             c.yknown = false;
797                         } else {
798                             drone.readBus(new BCB(c, YLUT));
799                         }
800                         if (!cell.xo())
801                         for(Fpslic.Cell c2 : new Fpslic.Cell[] { cell.nw(), cell.sw(), cell.ne(), cell.se() })
802                             if (c2!=null && !c2.relevant()) {
803                                 scan(at40k, cell, NONE, false);
804                                 c2.xo(cell);
805                                 scan(at40k, c2, NONE, true);
806                                 c2.c(XLUT);
807                                 drone.readBus(new BCB(c, XLUT));
808                                 scan(at40k, c2, NONE, false);
809                                 c2.xi(NONE);
810                                 return;
811                             }
812                         c.xknown = false;
813                         break;
814                     case ZMUX: {
815                         scan(at40k, cell, NONE, false);
816                         c.xknown = false;
817                         c.yknown = false;
818                         if (!cell.xo())
819                         for(Fpslic.Cell c2 : new Fpslic.Cell[] { cell.nw(), cell.sw(), cell.ne(), cell.se() })
820                             if (c2!=null && !c2.relevant()) {
821                                 scan(at40k, cell, NONE, false);
822                                 c2.xo(cell);
823                                 scan(at40k, c2, NONE, true);
824                                 c2.c(XLUT);
825                                 drone.readBus(new BCB(c, XLUT));
826                                 scan(at40k, c2, NONE, false);
827                                 c2.xi(NONE);
828                                 return;
829                             }
830                         if (!cell.yo())
831                         for(Fpslic.Cell c2 : new Fpslic.Cell[] { cell.north(), cell.south(), cell.east(), cell.west() })
832                             if (c2!=null && !c2.relevant()) {
833                                 c2.yo(cell);
834                                 c2.c(YLUT);
835                                 scan(at40k, c2, NONE, true);
836                                 drone.readBus(new BCB(c, YLUT));
837                                 scan(at40k, c2, NONE, false);
838                                 c2.yi(NONE);
839                                 break;
840                             }
841                         return;
842                     }
843                 }
844                 
845             }
846             scan(at40k, cell, NONE, false);
847         } catch (IOException e) {
848             throw new RuntimeException(e);
849         }
850     }
851
852     public static void scan(Fpslic dev, Fpslic.Cell cell, int source, boolean setup) {
853         if (setup) {
854             if (source != NONE) cell.c(source);
855             if (cell.b()) cell.b(false);
856             if (cell.f()) cell.f(false);
857         }
858         if (cell.out(L3)!=setup) cell.out(L3, setup);
859         if (cell.vx(L3)!=setup) cell.v(L3, setup);
860
861         Fpslic.SectorWire sw = cell.vwire(L3);
862         //System.out.println("wire is: " + sw);
863
864         if (sw.row > (12 & ~0x3) && sw.north()!=null && sw.north().drives(sw))
865             sw.north().drives(sw, false);
866         while(sw.row > (12 & ~0x3) && sw.south() != null) {
867             //System.out.println(sw + " -> " + sw.south());
868             if (sw.drives(sw.south())!=setup) sw.drives(sw.south(), setup);
869             sw = sw.south();
870         }
871         if (sw.row < (12 & ~0x3) && sw.south() != null && sw.south().drives(sw))
872             sw.north().drives(sw, false);
873         while(sw.row < (12 & ~0x3) && sw.north() != null) {
874             //System.out.println(sw + " -> " + sw.north());
875             if (sw.drives(sw.north())!=setup) sw.drives(sw.north(), setup);
876             sw = sw.north();
877         }
878
879         //cell = dev.cell(19, 15);
880         cell = dev.cell(cell.col, 15);
881         /*
882         System.out.println("cell is " + cell);
883         cell.xlut(0xff);
884         cell.ylut(0xff);
885         cell.b(false);
886         cell.f(false);
887         cell.c(XLUT);
888         cell.out(L3, true);
889         cell.oe(NONE);
890         */
891         if (cell.hx(L3) != setup) cell.h(L3, setup);
892         if (cell.vx(L3) != setup) cell.v(L3, setup);
893         sw = cell.hwire(L3);
894
895         if (sw.west()!=null && sw.west().drives(sw)) { sw.west().drives(sw, false); }
896         while(sw.east() != null) {
897             //System.out.println(sw + " -> " + sw.east());
898             if (sw.drives(sw.east())!=setup) sw.drives(sw.east(), setup);
899             sw = sw.east();
900         }
901
902     }
903
904
905     int made = 0;
906     private class BCB extends FtdiBoard.ByteCallback {
907         Gui.Cell c;
908         int who;
909         public BCB(Gui.Cell c, int who) {
910             this.who = who; this.c = c;
911             made++;
912         }
913         public void call(byte b) throws Exception {
914             boolean on = (b & 0x80) != 0;
915             switch(who) {
916                 case YLUT:
917                     c.yknown = true;
918                     c.yon = on;
919                     repaint();
920                     break;
921                 case XLUT:
922                     c.xknown = true;
923                     c.xon = on;
924                     repaint();
925                     break;
926             }
927             made--;
928         }
929     }
930
931     public Gate getGate(byte lut, boolean xlut) {
932         for(Gate g : knownGates)
933             if (g.setLut(lut, xlut))
934                 return g;
935         return unknownGate;
936     }
937
938     public Gate unknownGate = new Circle("?");
939     public Gate[] knownGates =
940         new Gate[] {
941             new And(),
942             new Or(),
943             new Circle("0") { public boolean result(boolean x, boolean y, boolean z) { return false; } },
944             new Circle("1") { public boolean result(boolean x, boolean y, boolean z) { return true; } },
945             new Circle("x") { public boolean result(boolean x, boolean y, boolean z) { return x; } },
946             new Circle("y") { public boolean result(boolean x, boolean y, boolean z) { return y; } },
947             new Circle("z") { public boolean result(boolean x, boolean y, boolean z) { return z; } },
948             new Circle("~x") { public boolean result(boolean x, boolean y, boolean z) { return !x; } },
949             new Circle("~y") { public boolean result(boolean x, boolean y, boolean z) { return !y; } },
950             new Circle("~z") { public boolean result(boolean x, boolean y, boolean z) { return !z; } }
951         };
952
953     // FIXME: 2-input gates?
954     public abstract class Gate {
955         public boolean invert_x;
956         public boolean invert_y;
957         public boolean invert_z;
958         public boolean invert_out;
959         public abstract boolean result(boolean x, boolean y, boolean z);
960         public void draw(Graphics2D g, Color fill, Color stroke, Color text) {
961             GeneralPath p = new GeneralPath();
962             makePath(p);
963             g.setColor(fill);
964             g.fill(p);
965             g.setColor(stroke);
966             g.draw(p);
967
968             AffineTransform a = g.getTransform();
969             g.scale(1, -1);
970             if (label() != null) {
971                 g.setColor(text);
972                 g.drawString(label(), 7, -14);
973             }
974             g.setTransform(a);
975         }
976         public String label() { return null; }
977         public boolean setLut(int lut, boolean xlut) {
978             /*
979             for(int inverts = 0; inverts < 16; inverts++) {
980                 invert_x   = (inverts & 0x1) != 0;
981                 invert_y   = (inverts & 0x2) != 0;
982                 invert_z   = (inverts & 0x4) != 0;
983                 invert_out = (inverts & 0x8) != 0;
984             */
985                 boolean good = true;
986                 for(int bit=0; bit<8; bit++) {
987                     boolean x = xlut ? ((bit & 0x1) != 0) : ((bit & 0x2) != 0);
988                     boolean y = xlut ? ((bit & 0x2) != 0) : ((bit & 0x1) != 0);
989                     boolean z = (bit & 0x4) != 0;
990                     boolean expect = (lut & (1<<bit)) != 0;
991
992                     // FIXME symmetry issues here....
993                     boolean result = result(x ^ invert_x, y ^ invert_y, z ^ invert_z) ^ invert_out;
994                     if (result != expect) { good = false; break; }
995                 }
996                 if (good) return true;
997                 /*
998             }
999                 */
1000             return false;
1001         }
1002         public abstract void makePath(GeneralPath gp);
1003     }
1004
1005     public class Or extends Gate {
1006         public boolean result(boolean x, boolean y, boolean z) { return x || y || z; }
1007         public String label() { return "+"; }
1008         public void draw(Graphics2D g, Color fill, Color stroke, Color text) {
1009             AffineTransform at = g.getTransform();
1010             g.scale(1, -1);
1011             g.translate(0, -40);
1012             super.draw(g, fill, stroke, text);
1013             g.setTransform(at);
1014         }
1015         public void makePath(GeneralPath gp) {
1016             gp.moveTo(29.141f, 36.301f);
1017             gp.lineTo(29.141f, 36.301f-7.161f);
1018             gp.curveTo(27.71f, 11.24f, 23.413f, 9.45f, 14.82f, 0.5f);
1019             gp.curveTo(6.229f, 9.45f, 1.932f, 11.24f, 0.5f, 29.141f);
1020             gp.lineTo(0.5f, 29.141f+7.161f);
1021             float x = 0.5f;
1022             float y = 29.141f+7.161f;
1023             gp.curveTo(5.729f+x, -1.789f+y,
1024                        6.444f+x, -2.686f+y,
1025                        14.32f+x, -3.58f+y);
1026             gp.curveTo(22.697f, 33.616f, 23.413f, 34.512f, 29.141f, 36.301f);
1027         }
1028     }
1029
1030     public class Circle extends Gate {
1031         String label;
1032         public Circle(String label) { this.label = label; }
1033         public boolean result(boolean x, boolean y, boolean z) { return false; }
1034         public String label() { return label; }
1035         public void makePath(GeneralPath gp) {
1036             int S = 30;
1037             gp.moveTo(0, S/2);
1038             gp.lineTo(S/2, S);
1039             gp.lineTo(S, S/2);
1040             gp.lineTo(S/2, 0);
1041             gp.lineTo(0, S/2);
1042             gp.closePath();
1043         }
1044     }
1045
1046     public class And extends Gate {
1047         public boolean result(boolean x, boolean y, boolean z) { return x && y && z; }
1048         public String label() { return "&"; }
1049         public void makePath(GeneralPath gp) {
1050             gp.moveTo(0, 2);
1051             gp.lineTo(0, 19);
1052             gp.curveTo(0, 27, 3, 35, 13, 35);
1053             gp.curveTo(20, 35, 23, 27, 23, 19);
1054             gp.lineTo(23, 2);
1055             gp.closePath();
1056         }
1057     }
1058
1059     public class Muller extends And {
1060         public String label() { return "C"; }
1061         public void draw(Graphics2D g, Color fill, Color stroke, Color text) {
1062             super.draw(g, fill, stroke, text);
1063             g.setColor(stroke);
1064             g.drawLine(0, 0, 23, 0);
1065         }
1066     }
1067
1068     public class Xor extends Or {
1069         public boolean result(boolean x, boolean y, boolean z) { return x ^ y ^ z; }
1070         public String label() { return "^"; }
1071         public void draw(Graphics2D g, Color fill, Color stroke, Color text) {
1072             super.draw(g, fill, stroke, text);
1073             g.setColor(stroke);
1074             AffineTransform at = g.getTransform();
1075             g.scale(1, -1);
1076             g.translate(0, -40);
1077
1078             g.translate(0, 4);
1079             GeneralPath gp = new GeneralPath();
1080             float x = 0.5f;
1081             float y = 29.141f+7.161f;
1082             gp.moveTo(x,y);
1083             gp.curveTo(5.729f+x, -1.789f+y,
1084                        6.444f+x, -2.686f+y,
1085                        14.32f+x, -3.58f+y);
1086             gp.curveTo(22.697f, 33.616f, 23.413f, 34.512f, 29.141f, 36.301f);
1087             g.draw(gp);
1088
1089             g.setTransform(at);
1090         }
1091     }
1092
1093     public abstract class Mux extends Gate {
1094         public String label() { return "?"; }
1095         public void makePath(GeneralPath gp) {
1096             gp.moveTo(0, 15);
1097             gp.lineTo(2, 23);
1098             gp.lineTo(23, 23);
1099             gp.lineTo(25, 15);
1100             gp.lineTo(0, 15);
1101         }
1102     }
1103
1104     public class X_Mux extends Mux {
1105         public boolean result(boolean x, boolean y, boolean z) { return x ? y : z; }
1106     }
1107     public class Y_Mux extends Mux {
1108         public boolean result(boolean x, boolean y, boolean z) { return y ? x : z; }
1109     }
1110     public class Z_Mux extends Mux {
1111         public boolean result(boolean x, boolean y, boolean z) { return z ? x : y; }
1112     }
1113
1114     public abstract class Buf extends Gate {
1115         public void makePath(GeneralPath gp) {
1116             gp.moveTo(0, 15);
1117             gp.lineTo(13, 35);
1118             gp.lineTo(25, 15);
1119             gp.lineTo(0, 15);
1120         }
1121     }
1122
1123     public class X extends Buf {
1124         public boolean result(boolean x, boolean y, boolean z) { return x; }
1125     }
1126     public class Y extends Buf {
1127         public boolean result(boolean x, boolean y, boolean z) { return y; }
1128     }
1129     public class Z extends Buf {
1130         public boolean result(boolean x, boolean y, boolean z) { return z; }
1131     }
1132
1133     private static Image keyboard1 = Toolkit.getDefaultToolkit().createImage("keyboard1.png");
1134     private static Image keyboard2 = Toolkit.getDefaultToolkit().createImage("keyboard2.png");
1135     private static Image keyboard3 = Toolkit.getDefaultToolkit().createImage("keyboard3.png");
1136
1137 }