Source

codeaide / lab / wysiwym.py

Full commit
  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
# -*- coding: utf-8 -*-
from PyQt4.QtCore import SIGNAL, QString, QVariant, Qt, QUrl
from PyQt4.QtGui import (
    QApplication, QToolBar, QComboBox, QFrame, QToolButton,
    QFileDialog, QVBoxLayout, QBrush, QColor, QFont, QImage,
    QTextFormat, QTextBlockFormat, QTextCharFormat, QTextImageFormat,
    QTextFrameFormat, QTextDocument, QTextEdit, QTextCursor
    )


class jdict(dict):

    def __getattr__(self, name):
        return self.get(name, None)


object_type_map = jdict(
    text=QTextFormat.NoObject,
    image=QTextFormat.ImageObject,
    table=QTextFormat.TableObject,
    cell=QTextFormat.TableCellObject,
    link=QTextFormat.UserObject + 1,
)
reverse_object_type_map = dict(
    [(v,k) for (k,v) in object_type_map.items()])


property_format_map = dict(
    name=QTextFormat.UserProperty + 1,
    url=QTextFormat.UserProperty + 2
)





class FormatProperties(object):

    property_format_map = property_format_map


    def __init__(self, format):
        self.format = format


    def __getattr__(self, name):
        return getattr(self.format, name)


    def keys(self):
        return self.property_format_map.keys()


    def __getitem__(self, name):
        prop_id = self.property_format_map.get(name)
        if isinstance(prop_id, tuple):
            getter, setter = prop_id
            return getter(self, name)
        variant = self.format.property(prop_id)
        value = variant.toPyObject()
        if isinstance(value, QString):
            value = unicode(value)
        return value


    def __setitem__(self, name, value):
        prop_id = self.property_format_map.get(name)
        if not prop_id:
            raise TypeError, "Unknown parameter %r" % name
        elif isinstance(prop_id, tuple):
            getter, setter = prop_id
            setter(self, value)
        else:
            self.format.setProperty(prop_id, QVariant(value))



class TextCharFormat(FormatProperties):


    def get_bold(self):
        return self.format.property(
            QTextFormat.FontWeight).toPyObject() == QFont.Bold


    def set_bold(self, flag):
        if flag:
            self.format.setProperty(
                QTextFormat.FontWeight, QFont.Bold)
        else:
            self.format.setProperty(
                QTextFormat.FontWeight, QFont.Normal)


    def set_color(self, value):
        self.format.setProperty(
            QTextFormat.ForegroundBrush, QVariant(QBrush(QColor(value))))


    def get_color(self):
        return self.format.property(
            QTextFormat.ForegroundBrush).toPyObject()



    property_format_map = dict(property_format_map,
      font_family=QTextFormat.FontFamily,
      font_point_size=QTextFormat.FontPointSize,
      font_pixel_size=QTextFormat.FontPixelSize,
      font_weight=QTextFormat.FontWeight,
      italic=QTextFormat.FontItalic,
      underline=QTextFormat.FontUnderline,
      bold=(get_bold, set_bold),
      color=(get_color, set_color)
    )


class TextBlockFormat(FormatProperties):


    def set_background(self, value):
        self.format.setProperty(
            QTextFormat.BackgroundBrush, QVariant(QBrush(QColor(value))))


    def get_background(self):
        return self.format.property(
            QTextFormat.BackgroundBrush).toPyObject()



    property_format_map = dict(property_format_map,
      alignment=QTextFormat.BlockAlignment,
      margin_left=QTextFormat.BlockLeftMargin,
      margin_right=QTextFormat.BlockRightMargin,
      margin_top=QTextFormat.BlockTopMargin,
      margin_bottom=QTextFormat.BlockBottomMargin,
      indent=QTextFormat.BlockIndent,
      background=(get_background, set_background)
    )



class TextImageFormat(FormatProperties):

    property_format_map = dict(property_format_map,
      image_name=QTextFormat.ImageName,
      image_width=QTextFormat.ImageWidth,
      image_height=QTextFormat.ImageHeight
    )



class LinkCharFormat(TextCharFormat):


    def __init__(self, cf):
        TextCharFormat.__init__(self, cf)
        cf.setFontUnderline(True)



class Styles(object):


    def __init__(self):
        self.block_format_list = [
            self.create_block_format("p", font_point_size=9),
            self.create_block_format("h1", font_point_size=24,
                                     alignment=Qt.AlignCenter),
            self.create_block_format("h2", font_point_size=18),
            self.create_block_format("h3", font_point_size=14, bold=True),
            self.create_block_format("h4", font_point_size=12, bold=True),
            self.create_block_format("h5", font_point_size=10, bold=True),
            self.create_block_format("h6", font_point_size=8, bold=True),
            self.create_block_format("code", font_family="monospace",
                                     indent=1, background="lightyellow")
        ]
        self.char_format_list = [
            self.create_char_format("normal"),
            self.create_char_format("strong", bold=True),
            self.create_char_format("emphasis", italic=True),
            self.create_char_format("underline", underline=True),
        ]


    def format_name(self, format):
        return FormatProperties(format)["name"]


    def block_format(self, name):
        for bf, bcf in self.block_format_list:
            if self.format_name(bf) == name:
                return bf, bcf


    def char_format(self, name):
        for f in self.char_format_list:
            if self.format_name(f) == name:
                return f


    def create_char_format(self, name, **properties):
        cf = TextCharFormat(QTextCharFormat())
        cf["name"] = name
        for pname, pvalue in properties.items():
            cf[pname] = pvalue
        return cf.format


    def create_block_format(self, name, **properties):
        bf = TextBlockFormat(QTextBlockFormat())
        bf["name"] = name
        cf = TextCharFormat(QTextCharFormat())
        for pname, pvalue in properties.items():
            if pname in bf.keys():
                bf[pname] = pvalue
            else:
                cf[pname] = pvalue
        return bf.format, cf.format




class Document(QTextDocument):


    def __init__(self, styles=None):
        QTextDocument.__init__(self)
        self.styles = styles or Styles()


    def __iter__(self):
        block = self.begin()
        while block.isValid():
            bf_name = self.styles.format_name(block.blockFormat())
            parts = []
            fragment_iterator = block.begin()
            while not fragment_iterator.atEnd():
                frag = fragment_iterator.fragment()
                cf = frag.charFormat()
                cf_name = self.styles.format_name(cf)
                ot = reverse_object_type_map[cf.objectType()]
                if ot == "image":
                    data = TextImageFormat(cf)["image_name"]
                elif ot == "link":
                    data = LinkCharFormat(cf)["url"]
                else:
                    data = unicode(frag.text())
                parts.append((cf_name, ot, data))
                fragment_iterator += 1
            yield bf_name, parts
            block = block.next()


    def dump(self):
        for block_format, fragments in self:
            print block_format, fragments




class FormatSelectorWidget(QComboBox):

    def setCurrentValue(self, text):
        if text:
            found = self.findText(text)
            self.setCurrentIndex(found)


class ParagaphFormatSelector(FormatSelectorWidget):
    pass


class CharFormatSelector(FormatSelectorWidget):
    pass



class WysiswymFormatToolbar(QToolBar):


    def __init__(self, editor):
        QToolBar.__init__(self, editor)
        self.paragraph_formats = ParagaphFormatSelector(self)
        self.view = editor.view
        self.styles = editor.view.styles
        for bf, bcf in self.styles.block_format_list:
            self.paragraph_formats.addItem(
                self.styles.format_name(bf))
        self.connect(self.paragraph_formats,
                     SIGNAL("activated(const QString&)"),
                     self.on_change_paragraph_style)
        self.addWidget(self.paragraph_formats)
        self.char_formats = CharFormatSelector(self)
        for f in self.styles.char_format_list:
            self.char_formats.addItem(
                self.styles.format_name(f))
        self.connect(self.char_formats,
                     SIGNAL("activated(const QString&)"),
                     self.on_change_char_style)
        self.addWidget(self.char_formats)
        self.connect(editor.view,
                     SIGNAL("cursorPositionChanged()"),
                     self.cursor_pos_changed)
        self.add_image_button = QToolButton(self)
        self.add_image_button.setText("Add image...")
        self.addWidget(self.add_image_button)
        self.connect(self.add_image_button, SIGNAL("clicked()"),
                     self.on_add_image)


    def cursor_pos_changed(self):
        cursor = self.view.textCursor()
        bf_name = self.styles.format_name(
            cursor.blockFormat())
        self.paragraph_formats.setCurrentValue(bf_name)
        cf_name = self.styles.format_name(
            cursor.charFormat())
        self.char_formats.setCurrentValue(cf_name)


    def on_add_image(self):
        filename = QFileDialog.getOpenFileName(
            self, "Add image..", "", "Images (*.png *.jpg *.gif)")
        if filename:
            filename = unicode(filename)
            self.view.textCursor().insert_image(filename)


    def on_change_paragraph_style(self, name):
        self.view.textCursor().change_paragraph_style(name)


    def on_change_char_style(self, name):
        self.view.textCursor().change_char_style(name)




class TextCursor(QTextCursor):


    def __init__(self, tc_or_doc_or_block):
        QTextCursor.__init__(self, tc_or_doc_or_block)


    def insert_image(self, filename, align=QTextFrameFormat.InFlow):
        #QTextFrameFormat.FloatLeft, QTextFrameFormat.FloatRight
        img = QImage(filename)
        self.document().addResource(
            QTextDocument.ImageResource, QUrl(filename), img)
        tif = QTextImageFormat()
        tif.setName(filename)
        self.insertImage(tif, align)


    def insert_text(self, text, cf_name=None):
        styles = self.document().styles
        bf_name = TextBlockFormat(self.blockFormat())["name"]
        bf, bcf = styles.block_format(bf_name)
        cf = styles.char_format(cf_name)
        if cf:        
            merged_cf = QTextCharFormat()
            merged_cf.merge(cf)
            merged_cf.merge(bcf)
        else:
            merged_cf = bcf
        self.insertText(text, merged_cf)
        return merged_cf


    def insert_link(self, url):
        cf = self.document().styles.create_char_format("_link", underline=True, color="blue")
        LinkCharFormat(cf)["url"] = url
        cf.setObjectType(object_type_map.link)
        self.insertText(url, cf)



    def change_paragraph_style(self, name):
        bf, bcf = self.document().styles.block_format(unicode(name))
        self.setBlockFormat(bf)
        self.select(QTextCursor.BlockUnderCursor)
        format = QTextCharFormat()
        format.merge(self.charFormat())
        format.merge(bcf)
        self.setCharFormat(format)


    def change_char_style(self, name):
        styles = self.document().styles
        cf = styles.char_format(unicode(name))
        bf = TextBlockFormat(self.blockFormat())
        bf, bcf = styles.block_format(bf["name"])
        merged_cf = QTextCharFormat()
        merged_cf.merge(bcf)
        merged_cf.merge(cf)
        self.setCharFormat(merged_cf)




class WysiswymView(QTextEdit):


    def __init__(self, parent=None, styles=None):
        QTextEdit.__init__(self, parent)
        self.doc = Document(styles)
        self.styles = self.doc.styles
        self.setDocument(self.doc)


    def textCursor(self):
        return TextCursor(QTextEdit.textCursor(self))




class WysiswymEditor(QFrame):

    def __init__(self, parent=None):
        QFrame.__init__(self, parent)
        self.view = WysiswymView(self)
        self.toolbar = WysiswymFormatToolbar(self)
        self.vboxlayout = QVBoxLayout(self)
        self.setLayout(self.vboxlayout)
        self.layout().addWidget(self.toolbar)
        self.layout().addWidget(self.view)




class Formatter(object):


    def __init__(self, doc):
        if isinstance(doc, QTextEdit):
            doc = doc.document()
        self.cursor = TextCursor(doc)
        self.doc = doc


    def new_paragraph(self, format):
        bf, bcf = self.doc.styles.block_format(format)
        self.cursor.insertBlock(bf)
        self.cursor.setCharFormat(bcf)



    def end_paragraph(self):
        pass


    def insert_text(self, text, cf_name):
        self.cursor.insert_text(text, cf_name)



    def insert_image(self, filename):
        if filename.startswith("file://"):
            filename = filename[7:]
        self.cursor.insert_image(filename)


    def insert_link(self, url):
        self.cursor.insert_link(url)




class Parser(object):


    def __init__(self, formatter, data=None):
        self.formatter = formatter
        if data:
            self.feed(data)


    def feed(self, data):
        pass





import re




class WikiParser(Parser):

    paragraph_formats = [
        "^= (?P<h1>.*) =$",
        "^== (?P<h2>.*) ==$",
        "^=== (?P<h3>.*) ===$",
        "^==== (?P<h4>.*) ====$",
        "^===== (?P<h5>.*) =====$",
        "^====== (?P<h6>.*) ======$",
        #" * (?P<_list>.*)",
        "  (?P<code>.*)",
        ]
    char_formats = [
        "\*\*(?P<strong>.*?)\*\*",
        "''(?P<emphasis>.*?)''",
        "__(?P<underline>.*)__",
        "(?P<_image>(file|http)://[^ \t\n].*?\.(png|jpg|gif))",
        "(?P<_link>http://[^ \t\n]+)",
        ]


    def feed(self, data):
        self.parse(data)


    def parse(self, data):
        char_re = re.compile("|".join(self.char_formats))
        paragraph_re = re.compile("|".join(self.paragraph_formats))
        image_re = re.compile("file:/{}")
        for line in data.split("\n"):
            found = paragraph_re.match(line)
            if found:
                paragraph_format_name = found.lastgroup
                paragraph_content = found.group(paragraph_format_name)
            else:
                paragraph_format_name = "p"
                paragraph_content = line
            if not paragraph_format_name.startswith("_"):
                self.formatter.new_paragraph(paragraph_format_name)
            last_pos = 0
            for found in char_re.finditer(paragraph_content):
                start, end = found.span()
                if start > last_pos:
                    self.formatter.insert_text(
                        paragraph_content[last_pos:start], "normal")
                last_pos = end
                cf_name = found.lastgroup
                char_content = found.group(cf_name)
                if cf_name.startswith("_"):
                    if cf_name == "_image":
                        self.formatter.insert_image(char_content)
                    elif cf_name == "_link":
                        self.formatter.insert_link(char_content)
                else:
                    self.formatter.insert_text(char_content, cf_name)
            if last_pos + 1 < len(paragraph_content):
                self.formatter.insert_text(
                    paragraph_content[last_pos:], "normal")
            if not paragraph_format_name.startswith("_"):
                self.formatter.end_paragraph()






def main():
    example = """\
Sandbox

= heading 1 =
== heading 2 ==
=== heading 3 ===

This is a normal paragraph with **bold** and ''italic'' words.

Here is an image:
file:///usr/share/doc/ubuntu-artwork/html/img/headerlogo.png (Ubuntu Logo)


Example code:

  def hello():
     print 'Hello, world'

Now a list (TODO):
 * one
 * two


Visit: http://programming.reddit.com
"""

    import sys
    app = QApplication(sys.argv)
    edit = WysiswymEditor()
    edit.resize(640, 480)
    parser = WikiParser(Formatter(edit.view), example)
    edit.show()
    app.exec_()
    edit.view.document().dump()


if __name__ == "__main__":
    main()