File: forgetHTML.py

package info (click to toggle)
forgethtml 0.0.20031008-5
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 56 kB
  • ctags: 171
  • sloc: python: 492; makefile: 55
file content (731 lines) | stat: -rw-r--r-- 20,970 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
"""A totally object-oriented way of writing HTML. Each
element is a object which may contain other HTML
elements (ie. objects). Only those elements allowed
in HTML to contain each other are allowed to be
inserted.

Print or str() or .output() the top (root) object
to get the final HTML."""

# $Id: forgetHTML.py,v 1.4 2003/10/08 15:03:58 stain Exp $
#
# (c) Stian Soiland <stain@nvg.org> 2001-2003
# Licence: LGPL
#
# Last changes:
# $Log: forgetHTML.py,v $
# Revision 1.4  2003/10/08 15:03:58  stain
# Dirty hack0rz.. allowing existing class for rows
#
# Revision 1.3  2003/09/11 22:37:51  stain
# a new compare-function, let things be sorted
#
# A NonIndentMixin to prevent indention on certain
# elements
#
# SimpleTable.add now supports TableCells, even with their own
# colspan - this is done in a very dirty way, but prevents
# expansion in these cases:
#
# t = SimpleTable()
# t.add("Col1", "Col2")
# t.add(html.TableCell("Both columns", colspan=2))
#
# Strong, Emphasis, Small, Big, Break added.
#
#
# Textarea and Pre now don't indent by using NonIndentMixin.
#
# Revision 1.2  2003/06/25 11:45:37  stain
# Added SimpleTable - a nice way to create a
# description-list-type table (ie. with first row
# or column as headers)
#
# TODO? Both row and column!
#
# Revision 1.1  2003/06/23 08:16:07  stain
# now getitem (ie element['blapp']) would refer to attributes on item,
# not retrieve subelements.
#
# Revision 1.1  2003/01/18 05:29:15  stain
# First import from aapningstider.no
#
# Revision 1.5  2002/10/16 11:22:22  stain
# wohoo
#
# Revision 1.4  2002/08/13 00:00:54  stain
# Now without those stupid bugs.
#
# Revision 1.3  2002/08/11 22:22:36  stain
#
# Jay. Added two classes, QuickForm and SimpleDocument.
# QuickForm is a nifty way of creating SIMPLE forms.
#
# SimpleDocument is a way of getting started with a document,
# creating <head>, <body>, <title>, <h1> and optionnally a
# stylesheet reference.
#
# Jah, and Label was added.
#
# Revision 1.2  2002/08/11 22:21:56  stain
# Jay. Added two classes, QuickForm and SimpleDocument.
#
# QuickForm is a nifty way of creating SIMPLE forms.
#
# SimpleDocument is a way of getting started with a document,
# creating <head>, <body>, <title>, <h1> and optionnally a
# stylesheet reference.
#
# Revision 1.1  2002/07/18 23:12:02  stain
# Akkai
#
# Revision 1.13  2001/11/07 01:49:47  stain
# St�tte for � sl� opp (rekursivt) id-tagger med element.get("id")
# eller element["id"].
#
# Ie.
#
#   body = html.Body()
#   div = html.Division(id="overskrift")
#   body.append(div)
#   body["overskrift"] == div
#
#   body["overskrift"].append(html.Header("Hei", id="blapp"))
#
#   body["blapp"].attributes["style"] = "align: right;"
#
# Blapp - b�r gjerne skrives om til � bruke bredde-f�rst-s�k
# istedet for dybde-f�rst for effektivitetens skyld
# (hvis man s�ker i et element man tror key-en ligger direkte
# under), p� den andre siden er dybde-f�rst tilsvarende en
# topp-til-bunn-s�k i en flat HTML-fil.
#
# Revision 1.12  2001/04/07 10:39:32  stain
# Header did not set level correct
#
# Revision 1.11  2001/04/06 19:37:20  stain
# Formfields. Support for some stuff. stylesheet. Wraps attribute lists.
#
# Revision 1.10  2001/04/02 19:22:24  stain
# St�tte for ruler <hr> og tittel <title>
#
# Revision 1.9  2001/03/20 23:22:26  stain
# Small errors in indentation fixed.
#
# Protected methods should NOT be used for __define_*, as these
# are called by superclass methods! Now uses _define_*.
#
# Use self._content instead of self.content to indicate this
# is a 'privat' (but not protected) variable.
#
# Revision 1.8  2001/03/15 00:34:53  stain
# Don't use __method__ anymore for private
# methods, this was nasty. Using __method now.
#
# As well: raising ElementNotAllowed with
# element.__class__.__name__ makes a much
# nicer output.
#
# (Previous code printed out the HTML
# of the object not allowed!)
#
# Revision 1.7  2001/03/13 23:01:29  stain
# Added some nice meta information on top
#
# 

# Note:
#  + Only a few elements are supported at this time.
#  + Currently all possible attributes are allowed
#   (modify element.attributes or simply include them
#    as keywords in constructor call)

# Todo:
# + Form elements!

import exceptions, types

indention = ' ' * 2  # Use two spaces for indention in HTML output

class HTMLError(exceptions.Exception):
  """General HTML error"""
  def __str__(self):
    args = exceptions.Exception.__str__(self) # Get our arguments
    return self.__doc__ + ': ' + args

class ElementNotAllowedError(HTMLError):
  """Element not allowed"""
  pass

class AbstractClassError(HTMLError):
  """Abstract class"""
  pass

class HeaderLevelOutOfRangeError(HTMLError):
  """Header level out of range (1-6)"""
  pass

class Element:
  tag = None # this would be 'p' for <p>, etc.
  def __init__(self, *add, **attributes):
    self._content = []
    self.attributes = attributes # might be {} :=)
    self.allowed_content = self._define_allowed()
    self.default_child = self._define_default()
    self.extend(add)

    # _class means the class attribute. We need to 
    # 'escape' this to avoid the Python keyword class
    if(self.attributes.has_key('_class')):
      # Rename it!
      self['class'] = self['_class']
      del self.attributes['_class']
  def __cmp__(self, other):
    # Sort (recursive) by content
    if isinstance(other, Element):
        return cmp(self._content, other._content)
    else: 
        return cmp(self._content, other)
  def _define_allowed(self):
    """Override this method to specify allowed content"""
    return [Flow]     # list of classes of elements 
    # The reason for using a seperate function for this
    # is to make it possible to allow classes that have
    # not yet been declared at the point of parsing
  def _define_default(self):
    """Override this method to specify an element
    class wrapper to be tried if not matched by isallowed""" 
    return None
  def _check_abstract(self):   
    """Checks if our class is capable of producing HTML"""
    # If self.tag is not set, this is not a real
    # HTML-element for use by append or __str__
    if(self.tag == None): # we allow '' as a tag (used by Text)
      raise AbstractClassError, self.__class__.__name__    
  def __str__(self):
    return self.output()
  def output(self, indent=0):
    # returns the HTML-formatted output, nicely indented
    self._check_abstract()
    result = indention * indent + '<' + self.tag
    # Each attribute in the form key="value"
    count = -1
    for (attribute,value) in self.attributes.items():
      count += 1
      if(not count % 2 and count): # Not the first time!
        result = result + '\n' + indention * indent + ' ' * (len(self.tag) + 1)
      result = result + ' %s="%s"' % (attribute,value)
    if(not self._content):
      result = result + ' />\n' # No content!
    else:
      result = result + '>\n'
      for element in self._content:
        result = result + element.output(indent+1) # increased indent level
        # end tag
      result = result + indention * indent + '</' + self.tag + '>\n'
    return result

  def get(self, key):
    """Finds a sub-element by it's id. Fun part: recursive! """
    if(key == self.attributes.get('id')):
      return self # simplest case
    for item in self._content:
      match = item.get(key)
      if(match):
        return match
    return None # No match
 
  def __getitem__(self, key):
    return self.attributes.__getitem__(key)
  def __setitem__(self, key, value):
    self.attributes.__setitem__(key, value)
    
  def isallowed(self,element):
    """Checks if the given given element is allowed within ourself"""
    for allowed in self.allowed_content:
      if(isinstance(element,allowed)):
        return 1
    return 0 # None of those allowed matched

  def extend(self, list):
    """Appends each element in the given list"""
    for element in list:
      self.append(element)
    
  def append(self, element):    
    """Appends the given element within this element"""
    self._check_abstract()
    if(type(element) in (types.StringType, types.LongType, types.IntType, types.FloatType)):
       # For easy adding of text and numbers, we make a text
       #  element
       element = Text(element)
    if(not self.isallowed(element)):
      if(type(self.default_child) == types.ClassType):
        element = self.default_child(element) # No further checks
      else:
        raise ElementNotAllowedError, repr(element)
    self._content.append(element)
  
  def set(self, element):
    """Replaces the content with this new element, if it's allowed"""
    old = self._content
    self._content = []
    try:
      self.append(element)
    except Exception, e:
      self_content = old # Restore!
      raise e

class Document(Element):
  tag = 'html'
  def _define_allowed(self):
    return [Head, Body]
  def output(self, indent=0):
    result = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
"""
    return result + Element.output(self, indent)


class Head(Element):
  tag = 'head'
  def _define_allowed(self):
    return [HeadStuff]

class HeadStuff(Element):
  pass

class Meta(HeadStuff):
  tag = 'meta'
  def _define_allowed(self):
    return []

class Link(HeadStuff):
  tag = 'link'
  def _define_allowed(self):
    return []

class NonIndentMixin:
  def output(self, indent=0):
    indent = -999
    return Element.output(self, indent)

# <link href="/stylesheet.css" rel="stylesheet" type="text/css" />

class Stylesheet(Link):
  def __init__(self, href, media=None):
    if(media):
      Link.__init__(self,
              rel='stylesheet',
              type='text/css',
              href=href,
              media=media)
    else:
      Link.__init__(self,
              rel='stylesheet',
              type='text/css',
              href=href)

class Title(HeadStuff):
  tag = 'title'
  def _define_allowed(self):
    return [Text]

class Body(Element):
  tag = 'body'

class Flow(Element):
  pass

class Block(Flow):
  pass

class Inline(Flow):
  def _define_allowed(self):
    return [Inline]

class Text(Inline):
  """Special class for plain text"""
  tag = ''
  def _define_allowed(self):
    return []
  def isallowed(self,element):
    # Only strings and numbers are allowed. Unicode not supported (yet)
    if(type(element) in (types.StringType, types.LongType, types.IntType, types.FloatType)):
      return 1
    else:
      return 0
  def get(self, key):
    """Finds a sub-element by it's id. Fun part: recursive! """
    if(key == self.attributes.get('id')):
      return self # simplest case
    else:
      return None
    # We don't want to search our _content
  def append(self, element):
    # Overriding this method is very important,
    # otherwise Text('blapp') would loop forever :)
    if(not self.isallowed(element)):
      raise ElementNotAllowedError, element
    self._content.append(element)
  def output(self, indent=0):
    result = ''
    for line in self._content:
      result = result + indention * indent + str(line) + '\n'
      # Question: What would be the right thing to do here?
      # Is it acceptable to allow several entries in self._content?
      # Shoult they be seperated by ' ', '\n' or '' in output? 
    return result

class List(Block):
  def _define_allowed(self):
    return [ListItem]
  def _define_default(self):
    return ListItem
  
class UnorderedList(List):
  tag = 'ul'

class OrderedList(List):
  tag = 'ol'

class ListItem(Element):
  tag = 'li'

class Table(Block):
  tag = 'table'
  def _define_allowed(self):
    return [TableRow]
  def _define_default(self):
    return TableRow
  def extend2(self, lists):
    """Inserts each array in lists as a row in the table"""
    for list in lists:
      row = TableRow()
      row.extend(list)
      self.append(row)

class TableRow(Element):
  tag = 'tr'
  def _define_allowed(self):
    return [TableCell]
  def _define_default(self):
    return TableCell

class TableCell(Element):
  tag = 'td'

class TableHeader(TableCell):
 tag = 'th'

class SimpleTable(Table):
    def __init__(self, header="column", *args, **kwargs):
        """header -- "column" or "row"
        if column, the first column will be indexed (TableHeader), 
        if "row", the first row will be indexed.
        if "both", both the first row and column will be indexed.
        Anything else (like None) - no index"""
        Table.__init__(self, *args, **kwargs)
        self._items = []
        self._width=0
        self.header = header
    def add(self, *args, **kwargs):
        self._content = [] # reset html version because we changed..!
        row = (kwargs,) + args
        self._width = max(self._width, self._rowWidth(row))
        rowWidth = self._rowWidth(row)
        self._items.append(row)
    def _getColSpan(self, cell):
        # Eh.. we need to substract colspans.. 
        if isinstance(cell, TableCell):
            try:
                # *cough* *cough*
                colspan = cell['colspan']
                colspan = int(colspan)
                return colspan
            except KeyError:
                return 1
            except ValueError:
                return 1
        return 1           
    def _rowWidth(self, row):
        rowWidth = 0
        for cell in row[1:]:
            rowWidth += self._getColSpan(cell)
        return rowWidth    
    def _extendRow(self, row):
        """Extends a row if needed, but skip the kwargs in pos 0"""
        rowWidth = self._rowWidth(row)
        extendWidth = self._width - rowWidth
        # skip first element, and extend
        return list(row[1:]) + [''] * extendWidth
        
    def _generateContent(self):    
        if not self._items:
            pass
        items = self._items
        if self.header in ("row", "both"):
            row=items.pop(0)
            kwargs = row[0]
            row = self._extendRow(row)
            tablerow = TableRow(**kwargs)
            self.append(tablerow)
            pos = 0
            for column in row:
                cssClass = "col%s" % pos
                if not isinstance(column, TableCell):
                    column = TableHeader(column)
                try:
                    column['class'] = column['class'] + ' ' + cssClass
                except KeyError:
                    column['class'] = cssClass
                tablerow.append(column)
                pos += self._getColSpan(column)
        even = True         
        for row in items:
            even = not even #ooo, flipz colorstylz

            kwargs = row[0]
            row = self._extendRow(row)
            tablerow = TableRow(**kwargs)
            try:
                _class = tablerow['class'] + " "
            except KeyError:
                _class = ""
            tablerow['class'] = _class + (even and 'even' or 'odd')
            self.append(tablerow)
            pos = 0
            cssClass = "col%s" % pos
            column = row[0]
            if not isinstance(column, TableCell):
                if self.header in ("column", "both"):
                    column = TableHeader(column)
                else:
                    column = TableCell(column)
            try:
                column['class'] = column['class'] + ' ' + cssClass
            except KeyError:   
                column['class'] = cssClass
            tablerow.append(column)    
            pos += self._getColSpan(column)
            for column in row[1:]:
                cssClass = "col%s" % pos
                if not isinstance(column, TableCell):
                    column = TableCell(column)
                try:
                    column['class'] = column['class'] + ' ' + cssClass
                except KeyError:   
                    column['class'] = cssClass
                tablerow.append(column)
                pos += self._getColSpan(column)
    def output(self, *args, **kwargs):
        if not self._content:
            self._generateContent()
        return Table.output(self, *args, **kwargs)
 
class Division(Block):
  tag = 'div'

class Span(Inline):
  tag = 'span'

class Strong(Inline):
  tag = 'strong'

class Emphasis(Inline):
  tag = 'em'

class Small(Inline):
  tag = 'small'

class Big(Inline):
  tag = 'big'


class Header(Block):
  def _define_allowed(self):
    return [Inline] 
  def __init__(self, add=None, level=1, **kargs):
    self.set_level(level)
    if(add):
      Block.__init__(self, add, **kargs)
    else:
      Block.__init__(self, **kargs)

  def set_level(self, level):
    if((level >= 1) and (level <= 6)):
      self.level = level
      self.tag = 'h' + str(self.level)
    else:
      raise HeaderLevelOutOfRangeError, level

class Paragraph(Block): 
  tag = 'p'
  def _define_allowed(self):
    return [Inline]

class Pre(NonIndentMixin, Block): 
  tag = 'pre'
  def _define_allowed(self):
    return [Inline]

class Break(Inline):
  tag = 'br'
  def _define_allowed(self):
    return []

class Image(Inline):
  tag = 'img'
  def _define_allowed(self):
    return []

class Anchor(Inline):
  tag = 'a'
  def _define_allowed(self):
    return [Inline]
    

class Ruler(Block):
  tag = 'hr'
  def _define_allowed(self):
    return []

class Form(Block):
  tag = 'form'
  def _define_allowed(self):
    return [Flow]

class Input(Inline):
  tag = 'input'
  def _define_allowed(self):
    return []

class Select(Inline):
  tag = 'select'
  def _define_allowed(self):
    return [OptGroup, Option]

class OptGroup(Element):
  tag = 'optgroup'
  def _define_allowed(self):
    return [Option]

class Option(Element):
  tag = 'option'
  def _define_allowed(self):
    return [Text]

class Submit(Input):
  def __init__(self, value=None, *args, **kargs):
    if(value <> None):
      Input.__init__(self, type='submit', value=value, *args, **kargs)
    else:
      Input.__init__(self, type='submit', *args, **kargs)

class Checkbox(Input):
  def __init__(self, *args, **kargs):
    Input.__init__(self, type='checkbox',  *args, **kargs)

class Radiobutton(Input):
  def __init__(self, *args, **kargs):
    Input.__init__(self, type='radiobutton',  *args, **kargs)

class Textfield(Input):
  def __init__(self, *args, **kargs):
    Input.__init__(self, type='text',  *args, **kargs)

class Hidden(Input):
  def __init__(self, *args, **kargs):
    Input.__init__(self, type='hidden',  *args, **kargs)

class Textarea(Inline, NonIndentMixin):
  tag = 'textarea'

class Label(Inline):
  tag = 'label'
  def _define_allowed(self):
    return [Inline]

class SimpleDocument(Document):
  """A handy default document with a title and
  optionally a specified external stylesheet. You
  may change the title or stylesheet later on using
  the methods setTitle() and setStylesheet()."""
  def __init__(self, title=None, stylesheet=None):
    Document.__init__(self)
    self.head = Head()
    self.body = Body()
    self.append(self.head)
    self.append(self.body)
    self.title = None
    self.header = None
    self.stylesheet = None
    if(title):
      self.setTitle(title)
    if(stylesheet):
      self.setStylesheet(stylesheet)

  def setTitle(self, title):   
    if not self.title:
      self.title = Title()
      self.head.append(self.title)
    if not self.header:
      self.header = Header()
      self.body.append(self.header)
    self.title.set(title)
    self.header.set(title)

  def setStylesheet(self, url):
    if not self.stylesheet:
      self.stylesheet = Stylesheet(url)
      self.head.append(self.stylesheet)
    self.stylesheet['href'] = url  

class SimpleForm(Form):
  """A simple way to create an easy form. 

  form = SimpleForm()
  form.addText('firstname', 'First name', 'John')
  form.addText('lastname', 'Last name')
  choices = [
    ('red', 'Red color'),
    ('blue', 'Blue color'),
    ('green', 'Greenish color')
  ]
  form.addChoices('color', choices, 'Select a color',
                  'red')
  """
  
  def __init__(self, **kwargs):
    Form.__init__(self, **kwargs)
  def addText(self, id, description=None, value=None):
    """Adds a textfield, optionallly with a label."""
    div = Division()
    self.append(div)
    if(description):
      label = Label(description)
      label['for'] = id
      div.append(label)
    if(value):
      div.append(Textfield(id=id, name=id, value=value))
    else:  
      div.append(Textfield(id=id, name=id))
  def addChoices(self, id, choices, description=None, 
                 default=None):
    """Adds a selection box for the given choices.
    Note that the choices parameter must be a sequence of 
    bi-tupples (key, description).
    """
    div = Division()
    self.append(div)
    label = Label(description)
    label['for'] = id
    select = Select(id=id, name=id)
    for (key, desc) in choices:
      option = Option(desc, id=key, value=key)
      if(key == default):
        option['selected'] = 'selected'
      select.append(option)
    div.append(label)
    div.append(select)