blob: ccbb9fc0b712a3ba92a807728fc5a8c90127743c [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:
404 self.value = rexec.r_eval(self.translated)
405 except:
406 exc = sys.exc_info()[0]
407 if hasattr(exc, "__name__"):
408 self.value = exc.__name__
409 else:
410 self.value = str(exc)
411 return self.value
412
413 def format(self):
414 try:
415 text = self.fmt % self.value
416 except:
417 text = str(self.value)
418 return text, self.alignment
419
420 def xml(self):
421 return '<formula align="%s" format="%s">%s</formula>' % (
422 align2xml[self.alignment],
423 self.fmt,
424 self.formula)
425
426 def renumber(self, x1, y1, x2, y2, dx, dy):
427 out = []
428 for part in re.split('(\w+)', self.formula):
429 m = re.match('^([A-Z]+)([1-9][0-9]*)$', part)
430 if m is not None:
431 sx, sy = m.groups()
432 x = colname2num(sx)
433 y = int(sy)
434 if x1 <= x <= x2 and y1 <= y <= y2:
435 part = cellname(x+dx, y+dy)
436 out.append(part)
437 return FormulaCell("".join(out), self.fmt, self.alignment)
438
439def translate(formula):
440 """Translate a formula containing fancy cell names to valid Python code.
441
442 Examples:
443 B4 -> cell(2, 4)
444 B4:Z100 -> cells(2, 4, 26, 100)
445 """
446 out = []
447 for part in re.split(r"(\w+(?::\w+)?)", formula):
448 m = re.match(r"^([A-Z]+)([1-9][0-9]*)(?::([A-Z]+)([1-9][0-9]*))?$", part)
449 if m is None:
450 out.append(part)
451 else:
452 x1, y1, x2, y2 = m.groups()
453 x1 = colname2num(x1)
454 if x2 is None:
455 s = "cell(%s, %s)" % (x1, y1)
456 else:
457 x2 = colname2num(x2)
458 s = "cells(%s, %s, %s, %s)" % (x1, y1, x2, y2)
459 out.append(s)
460 return "".join(out)
461
462def cellname(x, y):
463 "Translate a cell coordinate to a fancy cell name (e.g. (1, 1)->'A1')."
464 assert x > 0 # Column 0 has an empty name, so can't use that
465 return colnum2name(x) + str(y)
466
467def colname2num(s):
468 "Translate a column name to number (e.g. 'A'->1, 'Z'->26, 'AA'->27)."
469 s = s.upper()
470 n = 0
471 for c in s:
472 assert 'A' <= c <= 'Z'
473 n = n*26 + ord(c) - ord('A') + 1
474 return n
475
476def colnum2name(n):
477 "Translate a column number to name (e.g. 1->'A', etc.)."
478 assert n > 0
479 s = ""
480 while n:
481 n, m = divmod(n-1, 26)
482 s = chr(m+ord('A')) + s
483 return s
484
485import Tkinter as Tk
486
487class SheetGUI:
488
489 """Beginnings of a GUI for a spreadsheet.
490
491 TO DO:
492 - clear multiple cells
493 - Select rows or columns
494 - Insert, clear, remove rows or columns
495 - Show new contents while typing
496 - Scroll bars
497 - Grow grid when window is grown
498 - Proper menus
499 - Undo, redo
500 - Cut, copy and paste
501 - Formatting and alignment
502 """
503
504 def __init__(self, filename="sheet1.xml", rows=10, columns=5):
505 """Constructor.
506
507 Load the sheet from the filename argument.
508 Set up the Tk widget tree.
509 """
510 # Create and load the sheet
511 self.filename = filename
512 self.sheet = Sheet()
513 if os.path.isfile(filename):
514 self.sheet.load(filename)
515 # Calculate the needed grid size
516 maxx, maxy = self.sheet.getsize()
517 rows = max(rows, maxy)
518 columns = max(columns, maxx)
519 # Create the widgets
520 self.root = Tk.Tk()
521 self.root.wm_title("Spreadsheet: %s" % self.filename)
522 self.beacon = Tk.Label(self.root, text="A1",
523 font=('helvetica', 16, 'bold'))
524 self.entry = Tk.Entry(self.root)
525 self.savebutton = Tk.Button(self.root, text="Save",
526 command=self.save)
527 self.cellgrid = Tk.Frame(self.root)
528 # Configure the widget lay-out
529 self.cellgrid.pack(side="bottom", expand=1, fill="both")
530 self.beacon.pack(side="left")
531 self.savebutton.pack(side="right")
532 self.entry.pack(side="left", expand=1, fill="x")
533 # Bind some events
534 self.entry.bind("<Return>", self.return_event)
535 self.entry.bind("<Shift-Return>", self.shift_return_event)
536 self.entry.bind("<Tab>", self.tab_event)
537 self.entry.bind("<Shift-Tab>", self.shift_tab_event)
538 # Now create the cell grid
539 self.makegrid(rows, columns)
540 # Select the top-left cell
541 self.currentxy = None
542 self.cornerxy = None
543 self.setcurrent(1, 1)
544 # Copy the sheet cells to the GUI cells
545 self.sync()
546
547 def makegrid(self, rows, columns):
548 """Helper to create the grid of GUI cells.
549
550 The edge (x==0 or y==0) is filled with labels; the rest is real cells.
551 """
552 self.gridcells = {}
553 # Create the top row of labels
554 for x in range(1, columns+1):
555 self.cellgrid.grid_columnconfigure(x, minsize=64)
556 cell = Tk.Label(self.cellgrid, text=colnum2name(x), relief='raised')
557 cell.grid_configure(column=x, row=0, sticky='WE')
558 self.gridcells[x, 0] = cell
559 # Create the leftmost column of labels
560 for y in range(1, rows+1):
561 cell = Tk.Label(self.cellgrid, text=str(y), relief='raised')
562 cell.grid_configure(column=0, row=y, sticky='WE')
563 self.gridcells[0, y] = cell
564 # Create the real cells
565 for x in range(1, columns+1):
566 for y in range(1, rows+1):
567 cell = Tk.Label(self.cellgrid, relief='sunken',
568 bg='white', fg='black')
569 cell.grid_configure(column=x, row=y, sticky='NWSE')
570 self.gridcells[x, y] = cell
571 def helper(event, self=self, x=x, y=y):
572 self.setcurrent(x, y)
573 cell.bind("<Button-1>", helper)
574 def shelper(event, self=self, x=x, y=y):
575 self.setcorner(x, y)
576 cell.bind("<Shift-Button-1>", shelper)
577
578 def save(self):
579 self.sheet.save(self.filename)
580
581 def setcurrent(self, x, y):
582 "Make (x, y) the current cell."
583 if self.currentxy is not None:
584 self.change_cell()
585 self.clearfocus()
586 name = cellname(x, y)
587 cell = self.sheet.getcell(x, y)
588 if cell is None:
589 text = ""
590 elif isinstance(cell, FormulaCell):
591 text = '=' + cell.formula
592 else:
593 text, alignment = cell.format()
594 self.beacon['text'] = name
595 self.entry.delete(0, 'end')
596 self.entry.insert(0, text)
597 self.entry.selection_range(0, 'end')
598 self.entry.focus_set()
599 self.currentxy = x, y
600 self.cornerxy = None
601 gridcell = self.gridcells.get(self.currentxy)
602 if gridcell is not None:
603 gridcell['bg'] = 'lightBlue'
604
605 def setcorner(self, x, y):
606 if self.currentxy is None or self.currentxy == (x, y):
607 self.setcurrent(x, y)
608 return
609 self.clearfocus()
610 self.cornerxy = x, y
611 x1, y1 = self.currentxy
612 x2, y2 = self.cornerxy or self.currentxy
613 if x1 > x2:
614 x1, x2 = x2, x1
615 if y1 > y2:
616 y1, y2 = y2, y1
617 for x in range(x1, x2+1):
618 for y in range(y1, y2+1):
619 gridcell = self.gridcells.get((x, y))
620 if gridcell is not None:
621 gridcell['bg'] = 'lightBlue'
622 name1 = cellname(*self.currentxy)
623 name2 = cellname(*self.cornerxy)
624 self.beacon['text'] = "%s:%s" % (name1, name2)
625
626
627 def clearfocus(self):
628 if self.currentxy is not None:
629 x1, y1 = self.currentxy
630 x2, y2 = self.cornerxy or self.currentxy
631 if x1 > x2:
632 x1, x2 = x2, x1
633 if y1 > y2:
634 y1, y2 = y2, y1
635 for x in range(x1, x2+1):
636 for y in range(y1, y2+1):
637 gridcell = self.gridcells.get((x, y))
638 if gridcell is not None:
639 gridcell['bg'] = 'white'
640
641 def return_event(self, event):
642 "Callback for the Return key."
643 self.change_cell()
644 x, y = self.currentxy
645 self.setcurrent(x, y+1)
646 return "break"
647
648 def shift_return_event(self, event):
649 "Callback for the Return key with Shift modifier."
650 self.change_cell()
651 x, y = self.currentxy
652 self.setcurrent(x, max(1, y-1))
653 return "break"
654
655 def tab_event(self, event):
656 "Callback for the Tab key."
657 self.change_cell()
658 x, y = self.currentxy
659 self.setcurrent(x+1, y)
660 return "break"
661
662 def shift_tab_event(self, event):
663 "Callback for the Tab key with Shift modifier."
664 self.change_cell()
665 x, y = self.currentxy
666 self.setcurrent(max(1, x-1), y)
667 return "break"
668
669 def change_cell(self):
670 "Set the current cell from the entry widget."
671 x, y = self.currentxy
672 text = self.entry.get()
673 cell = None
674 if text.startswith('='):
675 cell = FormulaCell(text[1:])
676 else:
677 for cls in int, long, float, complex:
678 try:
679 value = cls(text)
680 except:
681 continue
682 else:
683 cell = NumericCell(value)
684 break
685 if cell is None and text:
686 cell = StringCell(text)
687 if cell is None:
688 self.sheet.clearcell(x, y)
689 else:
690 self.sheet.setcell(x, y, cell)
691 self.sync()
692
693 def sync(self):
694 "Fill the GUI cells from the sheet cells."
695 self.sheet.recalc()
696 for (x, y), gridcell in self.gridcells.iteritems():
697 if x == 0 or y == 0:
698 continue
699 cell = self.sheet.getcell(x, y)
700 if cell is None:
701 gridcell['text'] = ""
702 else:
703 if hasattr(cell, 'format'):
704 text, alignment = cell.format()
705 else:
706 text, alignment = str(cell), LEFT
707 gridcell['text'] = text
708 gridcell['anchor'] = align2anchor[alignment]
709
710
711def test_basic():
712 "Basic non-gui self-test."
713 import os
714 a = Sheet()
715 for x in range(1, 11):
716 for y in range(1, 11):
717 if x == 1:
718 cell = NumericCell(y)
719 elif y == 1:
720 cell = NumericCell(x)
721 else:
722 c1 = cellname(x, 1)
723 c2 = cellname(1, y)
724 formula = "%s*%s" % (c1, c2)
725 cell = FormulaCell(formula)
726 a.setcell(x, y, cell)
727## if os.path.isfile("sheet1.xml"):
728## print "Loading from sheet1.xml"
729## a.load("sheet1.xml")
730 a.display()
731 a.save("sheet1.xml")
732
733def test_gui():
734 "GUI test."
735 g = SheetGUI()
736 g.root.mainloop()
737
738if __name__ == '__main__':
739 #test_basic()
740 test_gui()