Source

codeaide / codeaide / main.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
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
# -*- coding: utf-8 -*-
import sys
import os
from PyQt4.QtCore import QObject, SIGNAL, QTimer, QRect
from PyQt4.QtGui import (
    qApp,
    QPlainTextEdit, QPainter, QColor,
    QTextBlockUserData, QTextDocument, QPlainTextDocumentLayout, 
    QAbstractSlider, QScrollBar,
    QMenu)


from codeaide.base import ModeBase, TextCursor
from codeaide.utils import jdict
from codeaide.fileio import FileIO


FileIO.instance = FileIO()



class ScrollBar(QScrollBar):


    def __init__(self, parent):
        QScrollBar.__init__(self, parent)


    def sliderChange(self, change):
        if self.signalsBlocked() and change == QAbstractSlider.SliderValueChange:
            self.blockSignals(False)
        return QScrollBar.sliderChange(self, change)



class TextBlockUserData(QTextBlockUserData):

    def __init__(self):
        QTextBlockUserData.__init__(self)
        self.attrs = {}


    def __getitem__(self, name):
        return self.attrs[name]


    def get(self, name, default=None):
        return self.attrs.get(name, default)


    def __setitem__(self, name, value):
        self.attrs[name] = value



class VisibleBlock(object):
    """
    This class contains the geometry of currently visible blocks
    """

    def __init__(self, row, block, rect):
        self.row = row
        self.block = block
        (self.left, self.top, self.width, self.height) = rect
        self.rect = QRect(*rect)


class Configurable(object):
    

    def __init__(self):
        self.connect(self, SIGNAL("settings_changed()"), self.on_reconfigure)


    def reconfigure(self, **settings):
        try:
            self.settings.update(settings)
        except AttributeError, e:
            try:
                self.settings = jdict(self.default_settings)
            except AttributeError, e:
                self.settings = jdict()
            self.settings.update(settings)
        self.emit(SIGNAL("settings_changed()"))


    def on_reconfigure(self):
        pass



        
class Hookable(object):
    
    
    def setup_hooks(self):
        self.state = 0
        self.commands = {}
        self.keyboard_hooks = {}
        self.mouse_press_hooks = {}
        self.mouse_double_click_hooks = {}
        self.paint_hooks = self.paint_hooks_before = {}
        self.paint_hooks_after = {}
        self.resize_hooks = {}
        self.contents_change_hooks = {}
        self.cursor_movement_hooks = {}
        self.row_change_hooks = {}
        # These variables fill be filled with hooks for current state
        self._commands = []
        self.active_paint_hooks_before = self.active_paint_hooks_after = ()
        self.active_resize_hooks = ()
        self.active_cursor_movement_hooks = ()
        self.active_row_change_hooks = ()

        
        self.state = -1
        self.installed_modes = []

        
    def prepare_hooks(self):
        for cmd in self._commands:
            self.removeAction(cmd)

        self._commands = self.commands.get(self.state, [])
        for cmd in self._commands:
            self.addAction(cmd)

        def filter_active_state(hooks):
            return list(hooks.get(self.state, []) + hooks.get(-1, []))

        self._mouse_press_hooks = filter_active_state(self.mouse_press_hooks)
        
        self._mouse_double_click_hooks = filter_active_state(self.mouse_double_click_hooks)
        self._paint_hooks_before = filter_active_state(self.paint_hooks_before)
        self._paint_hooks_after = filter_active_state(self.paint_hooks_after)
        self._contents_change_hooks = filter_active_state(self.contents_change_hooks)
        self._cursor_movement_hooks = filter_active_state(self.cursor_movement_hooks)
        self._row_change_hooks = filter_active_state(self.row_change_hooks)
        self._resize_hooks = filter_active_state(self.resize_hooks)

        h = self._keyboard_hooks = dict()
        for state in (self.state, -1):
            for keys, callbacks in self.keyboard_hooks.get(state, {}).items():
                h.setdefault(keys, []).extend(callbacks)
   

    def find_mode(self, cls):
        for mode in self.installed_modes:
            if isinstance(mode, cls):
                return mode


    def is_installed(self, mode):
        for installed in self.installed_modes:
            if installed.__class__ is mode:
                return True
        return False


    def _find_modes(self, *mode_args):
        for m in mode_args:
            mode = ModeBase.find_implementation(m)
            if not mode:
                raise ValueError, "Installing mode %r failed: Not found." % m
            yield mode


    def install(self, *mode_list):
        for mode in self._find_modes(*mode_list):
            if not self.is_installed(mode):
                mode_instance = mode(self)
                self.installed_modes.append(mode_instance)
                setattr(self, mode.__name__, mode_instance)
        self.switch_state(0)

    require = install #alias for emacs fans ;)

    
    def install_on_idle(self, *mode_list, **kwargs):
        callback = kwargs.pop("callback", None)
        self.idle_install = IdleCall(self, self.install, callback, *mode_list, **kwargs)


    def uninstall(self, *mode_list):
        for mode in self._find_modes(*mode_list):
            for instance in self.installed_modes:
                if isinstance(instance, mode):
                    instance.uninstall()
                    delattr(self, instance.__class__.__name__)
                    self.installed_modes.remove(instance)
                    break


    def switch_state(self, state):
        """
        changes the state and set hooks for current state
        """
        self.emit(SIGNAL("state_change(int)"), state)
        self.state = state
        self.prepare_hooks()
        self.update_hooks()
        self.emit(SIGNAL("new_state()"))



class Buffer(QTextDocument, Hookable, Configurable):

    killring = []
    registers = []
    instances =  []
    file_io = None

    @classmethod
    def get(cls, idx):
        if isinstance(idx, basestring):
            for buf in cls.instances:
                if buf.filename == idx:
                    return buf
        return cls.instances[idx]


    def __init__(self, text=None, filename=None):
        QTextDocument.__init__(self)
        Hookable.__init__(self)
        Configurable.__init__(self)
        self.filename = filename
        if text is None and filename and os.path.exists(filename):
            text = FileIO.instance.load(filename)
        self.plain_text_layout = QPlainTextDocumentLayout(self)
        self.setDocumentLayout(self.plain_text_layout)
        if text:
            self.setPlainText(text)
        self.setModified(False)
        Buffer.instances.append(self)
        self.setup_hooks()
        #self.install("Autosave")



    def document(self):
        return self # work-around...


    def close(self):
        Buffer.instances.remove(self)


    def max_line_length(self):
        lines = unicode(self.toPlainText()).splitlines()
        return max([len(l) for l in lines])


    def row_col2position(self, row, col):
        """
        index starts with 0
        """
        block = self.findBlockByNumber(row)
        return block.position() + col


    def row2position(self, row):
        return self.row_col2position(row, 0)



if sys.platform == "win32":
    editor_default_font = "Lucida Console"
else:
    editor_default_font = "monospace"


default_scheme = jdict(
      color="black",
      background="white",
      selection_color="white",
      selection_background="#437DCD",
      font_name=editor_default_font,
      font_size=9,
      line_number_color="#866D71",
      line_number_active_color="black",
      line_number_background="#E1E1E1",
      highlight_line_background="#E4EDF8",
      wrap_indicator_color="#D8D8D8",
      wrap_indicator_background="#F7F7F7",
      occurrence_color="black",
      occurrence_background="yellow",
      paren_color="red",
      paren_background="#b4eeb4",
      space_color="lightgrey",
      tab_color="lightblue",
      all_space_color="darkred",
      status_new="darkgreen",
      status_modified="red",
      syntax_keyword="#808000", # darkYellow
      syntax_builtin="brown", 
      syntax_magic="magenta",
      syntax_self="darkMagenta",
      syntax_comment="darkGray",
      syntax_string="darkGreen",
      syntax_number="darkBlue",
      css = """
        QPlainTextEdit {
          font-family: %(font_name)s;
          font-size: %(font_size)spt;
          color: %(color)s;
          background-color: %(background)s;
          selection-color: %(selection_color)s;
          selection-background-color: %(selection_background)s;
        }"""
)
    


class Idler(QObject):
    # XXX make seconds configurable?


    def __init__(self, textedit):
        QObject.__init__(self, textedit)
        self.textedit = textedit
        self.idle_timer_id = self.startTimer(1000)


    def busy(self):
        self.killTimer(self.idle_timer_id)
        self.idle_timer_id = self.startTimer(1000)


    def timerEvent(self, event):
        self.killTimer(self.idle_timer_id)
        QTimer.singleShot(0, self._emit_idle)
        self.idle_timer_id = self.startTimer(1000)


    def _emit_idle(self):
        self.textedit.emit(SIGNAL("idle()"))



    
class CodeAide(QPlainTextEdit, Hookable, Configurable):
    """
    new signals:
      newText()
      documentChanged()
      state_change(old_state)
      new_state()
      visible_blocks_changed()

    """


    def __init__(self, parent=None):
        QPlainTextEdit.__init__(self, parent)
        self.connect(qApp.clipboard(), SIGNAL("dataChanged()"), self.on_clipboard_changed)
        Hookable.__init__(self)
        Configurable.__init__(self)
        self.vbar = ScrollBar(self)
        self.setVerticalScrollBar(self.vbar)
        self.setFrameStyle(0)

        self.fm = self.fontMetrics()
        self.reconfigure()
        
        self.setup_vars()
        self.setup_hooks()
        self.setup_signals()

        self.busy = Idler(self).busy
        self.update_hooks()
        self.setFocus()
        
        self.new_buffer()
    

    @property
    def default_settings(self):
        return dict(
           line_wraps=True,
           scheme=default_scheme,
        )
        


    def on_reconfigure(self):
        if self.settings.line_wraps:
            self.setLineWrapMode(QPlainTextEdit.WidgetWidth)
        else:
            self.setLineWrapMode(QPlainTextEdit.NoWrap)
        self.set_scheme(self.settings.scheme)
        self.on_blocks_changed()


    def setup_vars(self):
        self.row = self.column = -1
        self.contents_changed = True
        self.visible_blocks = []
        self.extra_selections = []


    def setup_signals(self):
        self.connect(
            self, SIGNAL("blockCountChanged(int)"), self.on_blocks_changed)
        self.connect(self.verticalScrollBar(),
                     SIGNAL("valueChanged(int)"), self.on_blocks_changed)
        self.connect(self, SIGNAL("newText()"), self.on_blocks_changed)
        self.connect(self, SIGNAL("blockVisibiblityChanged()"),
                     self.on_blocks_changed)
        self.connect(self, SIGNAL("documentChanged()"),
                     self.on_document_changed)
        self.connect(self, SIGNAL("cursorPositionChanged()"),
                     self.on_cursor_position_changed)


    def clone(self, parent=None):
        te = self.__class__(parent)
        for mode in self.installed_modes:
            te.install(mode)
        te.state = self.state
        te.setDocument(te.document)
        te.setTextCursor(QTextCursor(self.textCursor()))


    def on_document_changed(self):
        self.update_hooks()

        
    def update_hooks(self):
        doc = self.document()
        if not isinstance(doc, Buffer):
            return
        doc.prepare_hooks()
        self.prepare_hooks()

        self.active_mouse_press_hooks = doc._mouse_press_hooks + self._mouse_press_hooks
        self.active_mouse_double_click_hooks = doc._mouse_double_click_hooks + self._mouse_double_click_hooks
        self.active_paint_hooks_before = doc._paint_hooks_before + self._paint_hooks_before
        self.active_paint_hooks_after = doc._paint_hooks_after + self._paint_hooks_after
        self.active_contents_change_hooks = doc._contents_change_hooks + self._contents_change_hooks
        self.active_cursor_movement_hooks = doc._cursor_movement_hooks + self._cursor_movement_hooks
        self.active_row_change_hooks = doc._row_change_hooks + self._row_change_hooks
        self.active_resize_hooks = doc._resize_hooks + self._resize_hooks
        self.active_keyboard_hooks = dict(self._keyboard_hooks, **doc._keyboard_hooks)


    def new_buffer(self, text=None):
        doc = Buffer(text=text)
        doc.state = self.state
        self.setDocument(doc)
        self.connect(doc, SIGNAL("modificationChanged(bool)"), self.window().setWindowModified)
        return doc

    
    def load_buffer(self, filename):
        doc = Buffer(filename=filename)
        self.setDocument(doc)
        self.connect(doc, SIGNAL("modificationChanged(bool)"), self.window().setWindowModified)
        return doc

    
    def save_buffer(self, filename=None):
        doc = self.document()
        filename = filename or doc.filename
        FileIO.instance.save(filename, unicode(doc.toPlainText()))
        doc.setModified(False)


    def rename_buffer(self, filename):
        doc = self.document()
        doc.filename = filename
        

    def switch_buffer(self, num):
        doc = Buffer[num]
        self.setDocument(doc)
        self.connect(doc, SIGNAL("modificationChanged(bool)"), self.window().setWindowModified)
        return doc

    
    def close_buffer(self):
        self.document().close()
        self.new_buffer()


    def set_scheme(self, scheme):
        scheme = jdict(default_scheme, **scheme)
        css = scheme.css % scheme
        self.setStyleSheet(css)
        pal = self.palette()
        pal.setColor(self.backgroundRole(), QColor(scheme.background))
        self.setPalette(pal)
        font = self.font()
        font.setFamily(scheme.font_name)
        font.setPointSize(scheme.font_size)
        self.setFont(font)
        #format = self.currentCharFormat()
        #format.setFont(font)
        #self.setCurrentCharFormat(format)
        self.document().setDefaultFont(font)
        self.fm = self.fontMetrics()
        self.scheme = scheme

        
    def setFocus(self):
        QPlainTextEdit.setFocus(self)
        self.ensureCursorVisible()


    def paintEvent(self, event):
        # callbacks to paint background (wrap indicator etc)
        viewport = self.viewport()
        before = self.active_paint_hooks_before
        if before:
            painter = QPainter(viewport)
            for callback in before:
                if callback(event, painter, viewport):
                    return
            painter.end()
        # render text
        QPlainTextEdit.paintEvent(self, event)
        # callbacks to render foreground (whitespace etc)
        after = self.active_paint_hooks_after
        if after:
            painter = QPainter(viewport)
            for callback in after:
                if callback(event, painter, viewport):
                    return
            painter.end()


    def mousePressEvent(self, event):
        for callback in self.active_mouse_press_hooks:
            if callback(event):
                return
        self.busy()
        return QPlainTextEdit.mousePressEvent(self, event)



    def mouseDoubleClickEvent (self, event):
        for callback in self.active_mouse_double_click_hooks:
            if callback(event):
                return
        self.busy() # XXX really?
        return QPlainTextEdit.mouseDoubleClickEvent(self, event)



    def keyPressEvent(self, event):
        key = event.key()
        text = event.text()
        modifiers = event.modifiers()
        m = int(modifiers)
        keyboard_hooks = self.active_keyboard_hooks
        
        if keyboard_hooks:
            h = keyboard_hooks.get((key, m), []) + \
                keyboard_hooks.get((key, -1), []) + \
                keyboard_hooks.get((-1, m), []) + \
                keyboard_hooks.get((-1, -1), [])
            for callback in h:
                if callback(event, key, modifiers, text):
                    return
        self.busy()
        return QPlainTextEdit.keyPressEvent(self, event)


    def resizeEvent(self, event):
        for callback in self.active_resize_hooks:
            if callback(event):
                return
        if self.lineWrapMode() == QPlainTextEdit.WidgetWidth:
            self.on_blocks_changed()
        return QPlainTextEdit.resizeEvent(self, event)


    def user_data(self, block=None):
        if not block:
            block = self.textCursor().block()
        user_data = block.userData()
        if not user_data:
            user_data = TextBlockUserData()
            block.setUserData(user_data)
        return user_data


    def remove_extra_selections(self, selections):
        extras = self.extra_selections
        for sel in selections:
            if sel in extras:
                extras.remove(sel)
        self.setExtraSelections(extras)



    def add_extra_selections(self, selections):
        self.extra_selections.extend(selections)
        self.setExtraSelections(self.extra_selections)


    def on_blocks_changed(self, num=-1):        
        visible_blocks = []
        block = self.firstVisibleBlock()
        row = block.blockNumber() + 1
        width = self.width()
        w  = width -2
        h = self.fm.height()

        bbgeom = self.blockBoundingGeometry(block)
        top = bbgeom.translated(self.contentOffset()).top()
        bottom = top + bbgeom.height()
        ebottom_top = 0 #event.rect().top()
        ebottom_bottom = self.height() #event.rect().bottom()
        visible_blocks_append = visible_blocks.append
        while block.isValid() and top <= ebottom_bottom:
            if block.isVisible() and bottom >= ebottom_top:
                visible_blocks_append(
                   VisibleBlock(row, block, (0, top, w, h))
                   )
            block = block.next()
            row += 1
            top = bottom
            bottom = top + self.blockBoundingRect(block).height()
        self.visible_blocks = visible_blocks
        self.emit(SIGNAL("visible_blocks_changed()"))


    def on_cursor_position_changed(self):
        cursor = self.textCursor()
        row = cursor.blockNumber()
        col = cursor.columnNumber()
        old_row = self.row
        old_col = self.column
        for callback in self.active_cursor_movement_hooks:
            if callback(row, col, cursor):
                return
        if row != old_row and self.contents_changed:
            self.contents_changed = False
            for callback in self.active_row_change_hooks:
                if callback(row, col, cursor):
                    return
        self.row = row
        self.column = col


    def on_contents_changed(self, pos, chars_removed, chars_added):
        if chars_removed == 0 and chars_added == 0:
            # style changes (highlighting, ..)
            return

        self.contents_changed = True
        doc = self.document()
        start_block = doc.findBlock(pos - chars_removed)
        end_block = doc.findBlock(pos + chars_added)
        block = start_block
        block_number = start_block.blockNumber()
        end_block_number = end_block.blockNumber()
        get_user_data = self.user_data
        while block and block.isValid() and block_number <= end_block_number:
            text = unicode(block.text())
            user_data = get_user_data(block)
            for callback in self.active_contents_change_hooks:
                if callback(block_number, block, text, user_data):
                    return
            block = block.next()
            block_number += 1


    def contextMenuEvent(self, event):
        menu = QMenu(self)
        for cmd in self._commands:
            if cmd.context_menu():
                menu.addAction(cmd)
        menu.exec_(event.globalPos())


    def setDocument(self, doc):
        self.disconnect(self.document(),
                        SIGNAL("contentsChange(int,int,int)"),
                        self.on_contents_changed)
        QPlainTextEdit.setDocument(self, doc)
        self.connect(doc, SIGNAL("contentsChange(int,int,int)"),
          self.on_contents_changed)
        self.emit(SIGNAL("documentChanged()"))
        self.emit(SIGNAL("newText()"))


    def setPlainText(self, text):
        QPlainTextEdit.setPlainText(self, text)
        self.emit(SIGNAL("newText()"))


    def set_position(self, pos):
        cursor = self.textCursor()
        cursor.setPosition(pos)
        self.setTextCursor(cursor)


    def set_row_col(self, row, col):
        pos = self.document().row_col2position(row, col)
        cursor = self.textCursor()
        cursor.setPosition(pos)
        self.setTextCursor(cursor)

        
        
    def set_row_start(self, row):
        pos = self.document().row_col2position(row, 0)
        cursor = self.text_cursor()
        cursor.setPosition(pos)
        col = cursor.indention()
        cursor.setPosition(pos+col)
        self.setTextCursor(cursor)

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


    
    def on_clipboard_changed(self):
        self.emit(SIGNAL("pasteAvailable"), self.canPaste())