blob: be5126fe8bcadf3b055325eadcb43e62171cc05e [file] [log] [blame]
Guido van Rossum69ccfcc2002-10-28 01:06:37 +00001"""SS1 -- a spreadsheet."""
2
3import os
4import re
5import sys
6import cgi
7import rexec
8from xml.parsers import expat
9
10LEFT, CENTER, RIGHT = "LEFT", "CENTER", "RIGHT"
11
12def ljust(x, n):
13 return x.ljust(n)
14def center(x, n):
15 return x.center(n)
16def rjust(x, n):
17 return x.rjust(n)
18align2action = {LEFT: ljust, CENTER: center, RIGHT: rjust}
19
20align2xml = {LEFT: "left", CENTER: "center", RIGHT: "right"}
21xml2align = {"left": LEFT, "center": CENTER, "right": RIGHT}
22
23align2anchor = {LEFT: "w", CENTER: "center", RIGHT: "e"}
24
25def sum(seq):
26 total = 0
27 for x in seq:
28 if x is not None:
29 total += x
30 return total
31
32class Sheet:
33
34 def __init__(self):
35 self.cells = {} # {(x, y): cell, ...}
36 self.rexec = rexec.RExec()
37 m = self.rexec.add_module('__main__')
38 m.cell = self.cellvalue
39 m.cells = self.multicellvalue
40 m.sum = sum
41
42 def cellvalue(self, x, y):
43 cell = self.getcell(x, y)
44 if hasattr(cell, 'recalc'):
45 return cell.recalc(self.rexec)
46 else:
47 return cell
48
49 def multicellvalue(self, x1, y1, x2, y2):
50 if x1 > x2:
51 x1, x2 = x2, x1
52 if y1 > y2:
53 y1, y2 = y2, y1
54 seq = []
55 for y in range(y1, y2+1):
56 for x in range(x1, x2+1):
57 seq.append(self.cellvalue(x, y))
58 return seq
59
60 def getcell(self, x, y):
61 return self.cells.get((x, y))
62
63 def setcell(self, x, y, cell):
64 assert x > 0 and y > 0
65 assert isinstance(cell, BaseCell)
66 self.cells[x, y] = cell
67
68 def clearcell(self, x, y):
69 try:
70 del self.cells[x, y]
71 except KeyError:
72 pass
73
74 def clearcells(self, x1, y1, x2, y2):
75 for xy in self.selectcells(x1, y1, x2, y2):
76 del self.cells[xy]
77
78 def clearrows(self, y1, y2):
79 self.clearcells(0, y1, sys.maxint, y2)
80
81 def clearcolumns(self, x1, x2):
82 self.clearcells(x1, 0, x2, sys.maxint)
83
84 def selectcells(self, x1, y1, x2, y2):
85 if x1 > x2:
86 x1, x2 = x2, x1
87 if y1 > y2:
88 y1, y2 = y2, y1
89 return [(x, y) for x, y in self.cells
90 if x1 <= x <= x2 and y1 <= y <= y2]
91
92 def movecells(self, x1, y1, x2, y2, dx, dy):
93 if dx == 0 and dy == 0:
94 return
95 if x1 > x2:
96 x1, x2 = x2, x1
97 if y1 > y2:
98 y1, y2 = y2, y1
99 assert x1+dx > 0 and y1+dy > 0
100 new = {}
101 for x, y in self.cells:
102 cell = self.cells[x, y]
103 if hasattr(cell, 'renumber'):
104 cell = cell.renumber(x1, y1, x2, y2, dx, dy)
105 if x1 <= x <= x2 and y1 <= y <= y2:
106 x += dx
107 y += dy
108 new[x, y] = cell
109 self.cells = new
110
111 def insertrows(self, y, n):
112 assert n > 0
113 self.movecells(0, y, sys.maxint, sys.maxint, 0, n)
114
115 def deleterows(self, y1, y2):
116 if y1 > y2:
117 y1, y2 = y2, y1
118 self.clearrows(y1, y2)
119 self.movecells(0, y2+1, sys.maxint, sys.maxint, 0, y1-y2-1)
120
121 def insertcolumns(self, x, n):
122 assert n > 0
123 self.movecells(x, 0, sys.maxint, sys.maxint, n, 0)
124
125 def deletecolumns(self, x1, x2):
126 if x1 > x2:
127 x1, x2 = x2, x1
128 self.clearcells(x1, x2)
129 self.movecells(x2+1, 0, sys.maxint, sys.maxint, x1-x2-1, 0)
130
131 def getsize(self):
132 maxx = maxy = 0
133 for x, y in self.cells:
134 maxx = max(maxx, x)
135 maxy = max(maxy, y)
136 return maxx, maxy
137
138 def reset(self):
139 for cell in self.cells.itervalues():
140 if hasattr(cell, 'reset'):
141 cell.reset()
142
143 def recalc(self):
144 self.reset()
145 for cell in self.cells.itervalues():
146 if hasattr(cell, 'recalc'):
147 cell.recalc(self.rexec)
148
149 def display(self):
150 maxx, maxy = self.getsize()
151 width, height = maxx+1, maxy+1
152 colwidth = [1] * width
153 full = {}
154 # Add column heading labels in row 0
155 for x in range(1, width):
156 full[x, 0] = text, alignment = colnum2name(x), RIGHT
157 colwidth[x] = max(colwidth[x], len(text))
158 # Add row labels in column 0
159 for y in range(1, height):
160 full[0, y] = text, alignment = str(y), RIGHT
161 colwidth[0] = max(colwidth[0], len(text))
162 # Add sheet cells in columns with x>0 and y>0
163 for (x, y), cell in self.cells.iteritems():
164 if x <= 0 or y <= 0:
165 continue
166 if hasattr(cell, 'recalc'):
167 cell.recalc(self.rexec)
168 if hasattr(cell, 'format'):
169 text, alignment = cell.format()
170 assert isinstance(text, str)
171 assert alignment in (LEFT, CENTER, RIGHT)
172 else:
173 text = str(cell)
174 if isinstance(cell, str):
175 alignment = LEFT
176 else:
177 alignment = RIGHT
178 full[x, y] = (text, alignment)
179 colwidth[x] = max(colwidth[x], len(text))
180 # Calculate the horizontal separator line (dashes and dots)
181 sep = ""
182 for x in range(width):
183 if sep:
184 sep += "+"
185 sep += "-"*colwidth[x]
186 # Now print The full grid
187 for y in range(height):
188 line = ""
189 for x in range(width):
190 text, alignment = full.get((x, y)) or ("", LEFT)
191 text = align2action[alignment](text, colwidth[x])
192 if line:
193 line += '|'
194 line += text
195 print line
196 if y == 0:
197 print sep
198
199 def xml(self):
200 out = ['<spreadsheet>']
201 for (x, y), cell in self.cells.iteritems():
202 if hasattr(cell, 'xml'):
203 cellxml = cell.xml()
204 else:
205 cellxml = '<value>%s</value>' % cgi.escape(cell)
206 out.append('<cell row="%s" col="%s">\n %s\n</cell>' %
207 (y, x, cellxml))
208 out.append('</spreadsheet>')
209 return '\n'.join(out)
210
211 def save(self, filename):
212 text = self.xml()
213 f = open(filename, "w")
214 f.write(text)
215 if text and not text.endswith('\n'):
216 f.write('\n')
217 f.close()
218
219 def load(self, filename):
220 f = open(filename, 'r')
221 SheetParser(self).parsefile(f)
222 f.close()
223
224class SheetParser:
225
226 def __init__(self, sheet):
227 self.sheet = sheet
228
229 def parsefile(self, f):
230 parser = expat.ParserCreate()
231 parser.StartElementHandler = self.startelement
232 parser.EndElementHandler = self.endelement
233 parser.CharacterDataHandler = self.data
234 parser.ParseFile(f)
235
236 def startelement(self, tag, attrs):
237 method = getattr(self, 'start_'+tag, None)
238 if method:
239 for key, value in attrs.iteritems():
240 attrs[key] = str(value) # XXX Convert Unicode to 8-bit
241 method(attrs)
242 self.texts = []
243
244 def data(self, text):
245 text = str(text) # XXX Convert Unicode to 8-bit
246 self.texts.append(text)
247
248 def endelement(self, tag):
249 method = getattr(self, 'end_'+tag, None)
250 if method:
251 method("".join(self.texts))
252
253 def start_cell(self, attrs):
254 self.y = int(attrs.get("row"))
255 self.x = int(attrs.get("col"))
256
257 def start_value(self, attrs):
258 self.fmt = attrs.get('format')
259 self.alignment = xml2align.get(attrs.get('align'))
260
261 start_formula = start_value
262
263 def end_int(self, text):
264 try:
265 self.value = int(text)
266 except:
267 self.value = None
268
269 def end_long(self, text):
270 try:
271 self.value = long(text)
272 except:
273 self.value = None
274
275 def end_double(self, text):
276 try:
277 self.value = float(text)
278 except:
279 self.value = None
280
281 def end_complex(self, text):
282 try:
283 self.value = complex(text)
284 except:
285 self.value = None
286
287 def end_string(self, text):
288 try:
289 self.value = text
290 except:
291 self.value = None
292
293 def end_value(self, text):
294 if isinstance(self.value, BaseCell):
295 self.cell = self.value
296 elif isinstance(self.value, str):
297 self.cell = StringCell(self.value,
298 self.fmt or "%s",
299 self.alignment or LEFT)
300 else:
301 self.cell = NumericCell(self.value,
302 self.fmt or "%s",
303 self.alignment or RIGHT)
304
305 def end_formula(self, text):
306 self.cell = FormulaCell(text,
307 self.fmt or "%s",
308 self.alignment or RIGHT)
309
310 def end_cell(self, text):
311 self.sheet.setcell(self.x, self.y, self.cell)
312
313class BaseCell:
314 __init__ = None # Must provide
315 """Abstract base class for sheet cells.
316
317 Subclasses may but needn't provide the following APIs:
318
319 cell.reset() -- prepare for recalculation
320 cell.recalc(rexec) -> value -- recalculate formula
321 cell.format() -> (value, alignment) -- return formatted value
322 cell.xml() -> string -- return XML
323 """
324
325class NumericCell(BaseCell):
326
327 def __init__(self, value, fmt="%s", alignment=RIGHT):
328 assert isinstance(value, (int, long, float, complex))
329 assert alignment in (LEFT, CENTER, RIGHT)
330 self.value = value
331 self.fmt = fmt
332 self.alignment = alignment
333
334 def recalc(self, rexec):
335 return self.value
336
337 def format(self):
338 try:
339 text = self.fmt % self.value
340 except:
341 text = str(self.value)
342 return text, self.alignment
343
344 def xml(self):
345 method = getattr(self, '_xml_' + type(self.value).__name__)
346 return '<value align="%s" format="%s">%s</value>' % (
347 align2xml[self.alignment],
348 self.fmt,
349 method())
350
351 def _xml_int(self):
352 if -2**31 <= self.value < 2**31:
353 return '<int>%s</int>' % self.value
354 else:
355 return self._xml_long()
356
357 def _xml_long(self):
358 return '<long>%s</long>' % self.value
359
360 def _xml_float(self):
361 return '<double>%s</double>' % repr(self.value)
362
363 def _xml_complex(self):
364 return '<complex>%s</double>' % repr(self.value)
365
366class StringCell(BaseCell):
367
368 def __init__(self, text, fmt="%s", alignment=LEFT):
369 assert isinstance(text, (str, unicode))
370 assert alignment in (LEFT, CENTER, RIGHT)
371 self.text = text
372 self.fmt = fmt
373 self.alignment = alignment
374
375 def recalc(self, rexec):
376 return self.text
377
378 def format(self):
379 return self.text, self.alignment
380
381 def xml(self):
382 s = '<value align="%s" format="%s"><string>%s</string></value>'
383 return s % (
384 align2xml[self.alignment],
385 self.fmt,
386 cgi.escape(self.text))
387
388class FormulaCell(BaseCell):
389
390 def __init__(self, formula, fmt="%s", alignment=RIGHT):
391 assert alignment in (LEFT, CENTER, RIGHT)
392 self.formula = formula
393 self.translated = translate(self.formula)
394 self.fmt = fmt
395 self.alignment = alignment
396 self.reset()
397
398 def reset(self):
399 self.value = None
400
401 def recalc(self, rexec):
402 if self.value is None:
403 try:
Guido van Rossum36692422002-11-02 06:25:51 +0000404 # A hack to evaluate expressions using true division
405 rexec.r_exec("from __future__ import division\n" +
406 "__value__ = eval(%s)" % repr(self.translated))
407 self.value = rexec.r_eval("__value__")
Guido van Rossum69ccfcc2002-10-28 01:06:37 +0000408 except:
409 exc = sys.exc_info()[0]
410 if hasattr(exc, "__name__"):
411 self.value = exc.__name__
412 else:
413 self.value = str(exc)
414 return self.value
415
416 def format(self):
417 try:
418 text = self.fmt % self.value
419 except:
420 text = str(self.value)
421 return text, self.alignment
422
423 def xml(self):
424 return '<formula align="%s" format="%s">%s</formula>' % (
425 align2xml[self.alignment],
426 self.fmt,
427 self.formula)
428
429 def renumber(self, x1, y1, x2, y2, dx, dy):
430 out = []
431 for part in re.split('(\w+)', self.formula):
432 m = re.match('^([A-Z]+)([1-9][0-9]*)$', part)
433 if m is not None:
434 sx, sy = m.groups()
435 x = colname2num(sx)
436 y = int(sy)
437 if x1 <= x <= x2 and y1 <= y <= y2:
438 part = cellname(x+dx, y+dy)
439 out.append(part)
440 return FormulaCell("".join(out), self.fmt, self.alignment)
441
442def translate(formula):
443 """Translate a formula containing fancy cell names to valid Python code.
444
445 Examples:
446 B4 -> cell(2, 4)
447 B4:Z100 -> cells(2, 4, 26, 100)
448 """
449 out = []
450 for part in re.split(r"(\w+(?::\w+)?)", formula):
451 m = re.match(r"^([A-Z]+)([1-9][0-9]*)(?::([A-Z]+)([1-9][0-9]*))?$", part)
452 if m is None:
453 out.append(part)
454 else:
455 x1, y1, x2, y2 = m.groups()
456 x1 = colname2num(x1)
457 if x2 is None:
458 s = "cell(%s, %s)" % (x1, y1)
459 else:
460 x2 = colname2num(x2)
461 s = "cells(%s, %s, %s, %s)" % (x1, y1, x2, y2)
462 out.append(s)
463 return "".join(out)
464
465def cellname(x, y):
466 "Translate a cell coordinate to a fancy cell name (e.g. (1, 1)->'A1')."
467 assert x > 0 # Column 0 has an empty name, so can't use that
468 return colnum2name(x) + str(y)
469
470def colname2num(s):
471 "Translate a column name to number (e.g. 'A'->1, 'Z'->26, 'AA'->27)."
472 s = s.upper()
473 n = 0
474 for c in s:
475 assert 'A' <= c <= 'Z'
476 n = n*26 + ord(c) - ord('A') + 1
477 return n
478
479def colnum2name(n):
480 "Translate a column number to name (e.g. 1->'A', etc.)."
481 assert n > 0
482 s = ""
483 while n:
484 n, m = divmod(n-1, 26)
485 s = chr(m+ord('A')) + s
486 return s
487
488import Tkinter as Tk
489
490class SheetGUI:
491
492 """Beginnings of a GUI for a spreadsheet.
493
494 TO DO:
495 - clear multiple cells
Guido van Rossum69ccfcc2002-10-28 01:06:37 +0000496 - Insert, clear, remove rows or columns
497 - Show new contents while typing
498 - Scroll bars
499 - Grow grid when window is grown
500 - Proper menus
501 - Undo, redo
502 - Cut, copy and paste
503 - Formatting and alignment
504 """
505
506 def __init__(self, filename="sheet1.xml", rows=10, columns=5):
507 """Constructor.
508
509 Load the sheet from the filename argument.
510 Set up the Tk widget tree.
511 """
512 # Create and load the sheet
513 self.filename = filename
514 self.sheet = Sheet()
515 if os.path.isfile(filename):
516 self.sheet.load(filename)
517 # Calculate the needed grid size
518 maxx, maxy = self.sheet.getsize()
519 rows = max(rows, maxy)
520 columns = max(columns, maxx)
521 # Create the widgets
522 self.root = Tk.Tk()
523 self.root.wm_title("Spreadsheet: %s" % self.filename)
524 self.beacon = Tk.Label(self.root, text="A1",
525 font=('helvetica', 16, 'bold'))
526 self.entry = Tk.Entry(self.root)
527 self.savebutton = Tk.Button(self.root, text="Save",
528 command=self.save)
529 self.cellgrid = Tk.Frame(self.root)
530 # Configure the widget lay-out
531 self.cellgrid.pack(side="bottom", expand=1, fill="both")
532 self.beacon.pack(side="left")
533 self.savebutton.pack(side="right")
534 self.entry.pack(side="left", expand=1, fill="x")
535 # Bind some events
536 self.entry.bind("<Return>", self.return_event)
537 self.entry.bind("<Shift-Return>", self.shift_return_event)
538 self.entry.bind("<Tab>", self.tab_event)
539 self.entry.bind("<Shift-Tab>", self.shift_tab_event)
Guido van Rossum36692422002-11-02 06:25:51 +0000540 self.entry.bind("<Delete>", self.delete_event)
Guido van Rossum69ccfcc2002-10-28 01:06:37 +0000541 # Now create the cell grid
542 self.makegrid(rows, columns)
543 # Select the top-left cell
544 self.currentxy = None
545 self.cornerxy = None
546 self.setcurrent(1, 1)
547 # Copy the sheet cells to the GUI cells
548 self.sync()
549
Guido van Rossum36692422002-11-02 06:25:51 +0000550 def delete_event(self, event):
551 if self.cornerxy != self.currentxy and self.cornerxy is not None:
552 self.sheet.clearcells(*(self.currentxy + self.cornerxy))
553 else:
554 self.sheet.clearcell(*self.currentxy)
555 self.sync()
556 self.entry.delete(0, 'end')
557 return "break"
558
Guido van Rossum69ccfcc2002-10-28 01:06:37 +0000559 def makegrid(self, rows, columns):
560 """Helper to create the grid of GUI cells.
561
562 The edge (x==0 or y==0) is filled with labels; the rest is real cells.
563 """
Guido van Rossum36692422002-11-02 06:25:51 +0000564 self.rows = rows
565 self.columns = columns
Guido van Rossum69ccfcc2002-10-28 01:06:37 +0000566 self.gridcells = {}
567 # Create the top row of labels
568 for x in range(1, columns+1):
569 self.cellgrid.grid_columnconfigure(x, minsize=64)
570 cell = Tk.Label(self.cellgrid, text=colnum2name(x), relief='raised')
571 cell.grid_configure(column=x, row=0, sticky='WE')
572 self.gridcells[x, 0] = cell
Guido van Rossum36692422002-11-02 06:25:51 +0000573 cell.__x = x
574 cell.__y = 0
575 cell.bind("<ButtonPress-1>", self.selectcolumn)
576 cell.bind("<B1-Motion>", self.extendcolumn)
577 cell.bind("<ButtonRelease-1>", self.extendcolumn)
578 cell.bind("<Shift-Button-1>", self.extendcolumn)
Guido van Rossum69ccfcc2002-10-28 01:06:37 +0000579 # Create the leftmost column of labels
580 for y in range(1, rows+1):
581 cell = Tk.Label(self.cellgrid, text=str(y), relief='raised')
582 cell.grid_configure(column=0, row=y, sticky='WE')
583 self.gridcells[0, y] = cell
Guido van Rossum36692422002-11-02 06:25:51 +0000584 cell.__x = 0
585 cell.__y = y
586 cell.bind("<ButtonPress-1>", self.selectrow)
587 cell.bind("<B1-Motion>", self.extendrow)
588 cell.bind("<ButtonRelease-1>", self.extendrow)
589 cell.bind("<Shift-Button-1>", self.extendrow)
Guido van Rossum69ccfcc2002-10-28 01:06:37 +0000590 # Create the real cells
591 for x in range(1, columns+1):
592 for y in range(1, rows+1):
593 cell = Tk.Label(self.cellgrid, relief='sunken',
594 bg='white', fg='black')
595 cell.grid_configure(column=x, row=y, sticky='NWSE')
596 self.gridcells[x, y] = cell
Guido van Rossum36692422002-11-02 06:25:51 +0000597 cell.__x = x
598 cell.__y = y
599 # Bind mouse events
600 cell.bind("<ButtonPress-1>", self.press)
601 cell.bind("<B1-Motion>", self.motion)
602 cell.bind("<ButtonRelease-1>", self.release)
603 cell.bind("<Shift-Button-1>", self.release)
604
605 def selectcolumn(self, event):
606 x, y = self.whichxy(event)
607 self.setcurrent(x, 1)
608 self.setcorner(x, self.rows)
609
610 def extendcolumn(self, event):
611 x, y = self.whichxy(event)
612 if x > 0:
613 self.setcurrent(self.currentxy[0], 1)
614 self.setcorner(x, self.rows)
615
616 def selectrow(self, event):
617 x, y = self.whichxy(event)
618 self.setcurrent(1, y)
619 self.setcorner(self.columns, y)
620
621 def extendrow(self, event):
622 x, y = self.whichxy(event)
623 if y > 0:
624 self.setcurrent(1, self.currentxy[1])
625 self.setcorner(self.columns, y)
626
627 def press(self, event):
628 x, y = self.whichxy(event)
629 if x > 0 and y > 0:
630 self.setcurrent(x, y)
631
632 def motion(self, event):
633 x, y = self.whichxy(event)
634 if x > 0 and y > 0:
635 self.setcorner(x, y)
636
637 release = motion
638
639 def whichxy(self, event):
640 w = self.cellgrid.winfo_containing(event.x_root, event.y_root)
641 if w is not None and isinstance(w, Tk.Label):
642 try:
643 return w.__x, w.__y
644 except AttributeError:
645 pass
646 return 0, 0
Guido van Rossum69ccfcc2002-10-28 01:06:37 +0000647
648 def save(self):
649 self.sheet.save(self.filename)
650
651 def setcurrent(self, x, y):
652 "Make (x, y) the current cell."
653 if self.currentxy is not None:
654 self.change_cell()
655 self.clearfocus()
656 name = cellname(x, y)
657 cell = self.sheet.getcell(x, y)
658 if cell is None:
659 text = ""
660 elif isinstance(cell, FormulaCell):
661 text = '=' + cell.formula
662 else:
663 text, alignment = cell.format()
664 self.beacon['text'] = name
665 self.entry.delete(0, 'end')
666 self.entry.insert(0, text)
667 self.entry.selection_range(0, 'end')
668 self.entry.focus_set()
669 self.currentxy = x, y
670 self.cornerxy = None
671 gridcell = self.gridcells.get(self.currentxy)
672 if gridcell is not None:
Guido van Rossum36692422002-11-02 06:25:51 +0000673 gridcell['bg'] = 'yellow'
Guido van Rossum69ccfcc2002-10-28 01:06:37 +0000674
675 def setcorner(self, x, y):
676 if self.currentxy is None or self.currentxy == (x, y):
677 self.setcurrent(x, y)
678 return
679 self.clearfocus()
680 self.cornerxy = x, y
681 x1, y1 = self.currentxy
682 x2, y2 = self.cornerxy or self.currentxy
683 if x1 > x2:
684 x1, x2 = x2, x1
685 if y1 > y2:
686 y1, y2 = y2, y1
687 for x in range(x1, x2+1):
688 for y in range(y1, y2+1):
689 gridcell = self.gridcells.get((x, y))
690 if gridcell is not None:
691 gridcell['bg'] = 'lightBlue'
Guido van Rossum36692422002-11-02 06:25:51 +0000692 gridcell = self.gridcells.get(self.currentxy)
693 if gridcell is not None:
694 gridcell['bg'] = 'yellow'
Guido van Rossum69ccfcc2002-10-28 01:06:37 +0000695 name1 = cellname(*self.currentxy)
696 name2 = cellname(*self.cornerxy)
697 self.beacon['text'] = "%s:%s" % (name1, name2)
698
699
700 def clearfocus(self):
701 if self.currentxy is not None:
702 x1, y1 = self.currentxy
703 x2, y2 = self.cornerxy or self.currentxy
704 if x1 > x2:
705 x1, x2 = x2, x1
706 if y1 > y2:
707 y1, y2 = y2, y1
708 for x in range(x1, x2+1):
709 for y in range(y1, y2+1):
710 gridcell = self.gridcells.get((x, y))
711 if gridcell is not None:
712 gridcell['bg'] = 'white'
713
714 def return_event(self, event):
715 "Callback for the Return key."
716 self.change_cell()
717 x, y = self.currentxy
718 self.setcurrent(x, y+1)
719 return "break"
720
721 def shift_return_event(self, event):
722 "Callback for the Return key with Shift modifier."
723 self.change_cell()
724 x, y = self.currentxy
725 self.setcurrent(x, max(1, y-1))
726 return "break"
727
728 def tab_event(self, event):
729 "Callback for the Tab key."
730 self.change_cell()
731 x, y = self.currentxy
732 self.setcurrent(x+1, y)
733 return "break"
734
735 def shift_tab_event(self, event):
736 "Callback for the Tab key with Shift modifier."
737 self.change_cell()
738 x, y = self.currentxy
739 self.setcurrent(max(1, x-1), y)
740 return "break"
741
742 def change_cell(self):
743 "Set the current cell from the entry widget."
744 x, y = self.currentxy
745 text = self.entry.get()
746 cell = None
747 if text.startswith('='):
748 cell = FormulaCell(text[1:])
749 else:
750 for cls in int, long, float, complex:
751 try:
752 value = cls(text)
753 except:
754 continue
755 else:
756 cell = NumericCell(value)
757 break
758 if cell is None and text:
759 cell = StringCell(text)
760 if cell is None:
761 self.sheet.clearcell(x, y)
762 else:
763 self.sheet.setcell(x, y, cell)
764 self.sync()
765
766 def sync(self):
767 "Fill the GUI cells from the sheet cells."
768 self.sheet.recalc()
769 for (x, y), gridcell in self.gridcells.iteritems():
770 if x == 0 or y == 0:
771 continue
772 cell = self.sheet.getcell(x, y)
773 if cell is None:
774 gridcell['text'] = ""
775 else:
776 if hasattr(cell, 'format'):
777 text, alignment = cell.format()
778 else:
779 text, alignment = str(cell), LEFT
780 gridcell['text'] = text
781 gridcell['anchor'] = align2anchor[alignment]
782
783
784def test_basic():
785 "Basic non-gui self-test."
786 import os
787 a = Sheet()
788 for x in range(1, 11):
789 for y in range(1, 11):
790 if x == 1:
791 cell = NumericCell(y)
792 elif y == 1:
793 cell = NumericCell(x)
794 else:
795 c1 = cellname(x, 1)
796 c2 = cellname(1, y)
797 formula = "%s*%s" % (c1, c2)
798 cell = FormulaCell(formula)
799 a.setcell(x, y, cell)
800## if os.path.isfile("sheet1.xml"):
801## print "Loading from sheet1.xml"
802## a.load("sheet1.xml")
803 a.display()
804 a.save("sheet1.xml")
805
806def test_gui():
807 "GUI test."
Guido van Rossum36692422002-11-02 06:25:51 +0000808 if sys.argv[1:]:
809 filename = sys.argv[1]
810 else:
811 filename = "sheet1.xml"
812 g = SheetGUI(filename)
Guido van Rossum69ccfcc2002-10-28 01:06:37 +0000813 g.root.mainloop()
814
815if __name__ == '__main__':
816 #test_basic()
817 test_gui()