ttgui / tgui.py

  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
# -*- coding: utf-8 -*-
from console import Console, debug
from tcore import TSize, TPoint, TRect, TEvent, TEventLoop, TObject, dispatch


class TFocusPolicy:
    NoFocus = 0
    TabFocus = 1

    
class TEventTypes:
    KeyPress = 6
    #KeyRelease = 7
    FocusIn = 8
    FocusOut = 9
    Paint = 12
    Resize = 14
    Show = 17
    Hide = 18
    Close = 19
    User = 1000


class TKey:
    pass



class TKeyEvent(TEvent):


    def __init__(self, key, modifiers=None):
        super(TKeyEvent, self).__init__(TEventTypes.KeyPress)
        self.key = key
        self.modifiers = modifiers



class TPaintEvent(TEvent):

    
    def __init__(self, rect=None):
        super(TPaintEvent, self).__init__(TEventTypes.Paint)
        self.rect = rect

        

class TCloseEvent(TEvent):
    
    
    def __init__(self):
        super(TCloseEvent, self).__init__(TEventTypes.Close)


        
class THideEvent(TEvent):

    
    def __init__(self):
        super(THideEvent, self).__init__(TEventTypes.Hide)



class TShowEvent(TEvent):

    
    def __init__(self):
        super(TShowEvent, self).__init__(TEventTypes.Show)



class TResizeEvent(TEvent):

    
    def __init__(self, size):
        super(TResizeEvent, self).__init__(TEventTypes.Resize)
        self.size = size



class TFocusEvent(TEvent):


    def __init__(self, kind, reason=None):
        super(TFocusEvent, self).__init__(kind)
        self.reason = reason


    def gotFocus(self):
        return self.kind == TEventTypes.FocusIn


    def lostFocus(self):
        return self.kind == TEventTypes.FocusOut



        
class TPainter(object):


    def __init__(self, obj=None):
        self.stack = []
        if obj:
            self.stack.append(obj)
        self.obj = obj
        self.engine = Console.instance


    def begin(self, obj):
        self.stack.append(obj)
        self.obj = obj
        

    def end(self):
        self.stack.pop()
        if self.stack:
            self.obj = self.stack[-1]
        else:
            self.obj = None
            
            
    def drawRect(self, rect):
        gpos = self.obj.mapToGlobal(TPoint(0, 0))
        x1 = gpos.x + rect.topLeft.x
        y1 = gpos.y + rect.topLeft.y
        width = rect.size.width
        height = rect.size.height
        x2 = x1 + width - 1
        y2 = y1 + height - 1
        # topleft
        self.engine.text(x1, y1, "+")
        # topright
        self.engine.text(x2, y1, "+")
        # top line
        self.engine.text(x1 + 1, y1, "-" * (width-2))
        # bottomleft
        self.engine.text(x1, y2, "+")
        # bottomright
        self.engine.text(x2, y2, "+")
        # bottom line
        self.engine.text(x1+1, y2, "-" * (width-2))
        # side lines
        for y in range(y1+1, y2):
            self.engine.text(x1, y, "|") # left
            self.engine.text(x2, y, "|") # right


    
    def drawLine(self, start_pos, end_pos):
        x1, y1 = start_pos.x, start_pos.y
        x2, y2 = end_pos.x, end_pos.y
        if y1 == y1:
            width = x2 - x1
            self.engine.text(x1, y1, "-" * width)
        elif x1 == x2:
            for y in range(y1, y2+1):
                self.engine.text(x1, y, "|")
        else:
            raise NotImplementedError("Only horizontal and vertial lines supported right now")

        
    def drawText(self, pos, text):
        gpos = self.obj.mapToGlobal(pos)
        self.engine.text(gpos.x, gpos.y, text)
        


    def fillRect(self, rect, char):
        gpos = self.obj.mapToGlobal(TPoint(0, 0))
        x1 = gpos.x + rect.topLeft.x
        y1 = gpos.y + rect.topLeft.y
        width = rect.size.width
        height = rect.size.height
        x2 = x1 + width - 1
        y2 = y1 + height - 1
        for y in range(y1, y2):
            self.engine.text(x1, y, char*width)
    


class TInputHook(object):


    def __init__(self):
        self.xreadkeys = Console.instance.xreadkeys
    

    def poll(self):
        extended, keys = self.xreadkeys()
        if keys:
            Console.instance.text(1,1, "poll %r    " % keys)
            return TKeyEvent(keys)



class TApplication(TObject):

    instance = None

    
    def __init__(self):
        super(TApplication, self).__init__()
        self._focus_widget = None
        self._top_level_widgets = set()
        self.event_loop = TEventLoop.instance()
        TApplication.instance = self
        self._desktop = TDesktopWidget()
        self.input_hook = TInputHook()

        #self.focusChanged = Signal()


    @classmethod
    def desktop(cls):
        return cls.instance._desktop

    
    @classmethod
    def activeWindow(cls):
        return cls.focusWidget().window()


    @classmethod
    def setActiveWindow(cls, window):
        cls.setFocusWidget(window.focusNextChild())

    
    @classmethod
    def allWidgets(cls):
        found = list(cls.topLevelWidgets())
        for obj in found:
            for child in obj.children():
                if isinstance(child, TWidget) and child not in found:
                    found.append(child)
        return found

    
    @classmethod
    def _registerTopLevelWidget(cls, widget):
        if not cls.focusWidget():
            cls.setFocusWidget(widget)
        cls.instance._top_level_widgets.add(widget)

        
    @classmethod
    def _unregisterTopLevelWidget(cls, widget):
        cls.instance._top_level_widgets.remove(widget)


    @classmethod
    def topLevelWidgets(cls):
        return list(cls.instance._top_level_widgets)

    
    
    @classmethod
    def focusWidget(cls):
        return cls.instance._focus_widget
    
    
    @classmethod
    def setFocusWidget(cls, widget):
        old_focus_widget = cls.instance._focus_widget
        if widget != old_focus_widget:
            cls.instance._focus_widget = widget
            if old_focus_widget:
                cls.instance.postEvent(old_focus_widget, TFocusEvent(TEventTypes.FocusOut))
            cls.instance.postEvent(widget, TFocusEvent(TEventTypes.FocusIn))


    def postEvent(self, receiver_object, event):
        self.event_loop.postEvent(receiver_object, event)

    
    def sendEvent(self, receiver_object, event):
        self.event_loop.sendEvent(receiver_object, event)

    
    def notify(self, receiver_object, event):
        self.event_loop.notify(receiver_object, event)
        
        
    def processEvent(self):
        return self.event_loop.processEvent()
    
        
    def run(self):
        #self._desktop.show()
        win = self.activeWindow().focusNextChild()
        while True:
            if self.processEvent():
                Console.instance.refresh()
            event = self.input_hook.poll()
            if event:
                self.postEvent(self.focusWidget(), event)

            


class TWidget(TObject):

    
    def __init__(self, parent=None):
        super(TWidget, self).__init__(parent)
        self._focus_policy = TFocusPolicy.TabFocus
        self._update_geom(TPoint(0,0), self.sizeHint(), silent=True)
        self._visible = True
        if not parent:
            TApplication._registerTopLevelWidget(self)


    def _find_focusNextChild(self):
        focus_widget = TApplication.focusWidget()
        found = False
        for child in self.children():
            if not isinstance(child, TWidget):
                continue
            if child == focus_widget:
                found = True
                continue
            if found or not focus_widget:
                return child
    
            
    def focusNextChild(self):
        widget = self._find_focusNextChild()
        if widget:
            widget.setFocus()

    
    def _find_focusPreviousChild(self):
        focus_widget = TApplication.focusWidget()
        previous = None
        for child in self.children():
            if child == focus_widget:
                return previous
            if isinstance(child, TWidget):
                if not focus_widget:
                    return child
                previous = child


    def focusPreviousChild(self):
        widget = self._find_focusPreviousChild()
        if widget:
            widet.setFocus()


    def setFocusPolicy(self, policy):
        self._focus_policy = policy

        
    def focusPolicy(self):
        return self,_focus_policy

        
    def setFocus(self, reason=None):
        if self._focus_policy == TFocusPolicy.NoFocus:
            return
        TApplication.setFocusWidget(self)

        
    def hasFocus(self):
        return TApplication.focusWidget() == self


    def clearFocus(self):
        if self.hasFocus():
            self.postEvent(TFocusEvent())


    
    def sizeHint(self):
        return TSize(1,1)

        
    def window(self):
        obj = self
        parent = obj.parent()
        while parent:
            obj = parent
            parent = obj.parent()
        return obj


    def __del__(self):
        TApplication._unregisterTopLevelWidget(self)
    

    def close(self):
        if self.parent() == None:
            self.postEvent(THideEvent())
            self.postEvent(TCloseEvent())
            self.clearFocus()
            return True
        else:
            return False

 
       
    def show(self):
        self.setVisible(True)
        

    def hide(self):
        self.setVisible(False)

        
    def setVisible(self, flag):
        self._visible = flag
        self.postEvent(TPaintEvent())
        if flag:
            self.postEvent(TShowEvent())
        else:    
            self.postEvent(THideEvent())
        for child in self.children():
            child.setVisible(flag)


    def _update_geom(self, pos, size, silent=False):
        x1 = pos.x
        y1 = pos.y
        x2 = x1 + size.width
        y2 = y1 + size.height
        self._geom = (x1, y1, x2, y2)
        if not silent:
            self.postEvent(TResizeEvent(size))

        
    def size(self):
        (x1, y1, x2, y2) = self._geom
        width, height = x2 - y1, y2 - y1
        return TSize(width, height)
    
    
    def width(self):
        return self.size().width
    
    
    def height(self):
        return self.size().height

    
    def left(seft):
        return self.pos().x

    
    def top(self):
        return self.pos().y
    

    @dispatch(TSize)
    def resize(self, size):
        (x1, y1, x2, y2) = self._geom
        width, height = size.width, size.height
        self._update_geom(TPoint(x1, y1), TSize(width, height))

        
    @dispatch(int,int)
    def resize(self, width, height):
        self.resize(TSize(width, height))

        
    def pos(self):
        (x1, y1, x2, y2) = self._geom
        return TPoint(x1, y1)


    @dispatch(TPoint)
    def move(self, pos):
        self._update_geom(pos, self.size())

    
    @dispatch(int,int)
    def move(self, x, y):
        self.move(TPoint(x, y))


    def geometry(self):
        return TRect(self.pos(), self.size())

    
    @dispatch(TPoint, TSize)
    def setGeometry(self, pos, size):
        self._update_geom(pos, size)

        
    @dispatch(int,int,int,int)
    def setGeometry(self, x1, y1, width, height):
        self._update_geom(TPoint(x1, y1), TSize(width, height))
        
        
    @dispatch(TRect)
    def setGeometry(self, rect):
        self._update_geom(rect.topLeft, rect.size)

    
    def mapToParent(self, pos):
        parent = self.parent()
        if not parent:
            return TPoint(pos.x, pos.y)
        else:
            ppos = parent.pos()
            return TPoint(ppos.x + pos.x, ppos.y + pos.y)


    def mapToGlobal(self, pos):
        obj = self
        while obj:
            pos = obj.mapToParent(pos)
            obj = obj.parent()
        return pos

    
    def event(self, event):
        super(TWidget, self).event(event)
        if event.accepted or event.ignored:
            return
        if isinstance(event, TPaintEvent):
            self.paintEvent(event)
        elif isinstance(event, TKeyEvent):
            self.keyPressEvent(event)
        elif isinstance(event, TShowEvent):
            self.showEvent(event)
        elif isinstance(event, THideEvent):
            self.hideEvent(event)
        elif isinstance(event, TCloseEvent):
            self.closeEvent(event)
        elif isinstance(event, TFocusEvent):
            if event.gotFocus():
                self.focusInEvent(event)
            else:
                self.focusOutEvent(event)

                
    def showEvent(self, event):
        if not self.parent():
            TApplication.setActiveWindow(self)
        

    def focusInEvent(self, event):
        pass
            
    
    def focusOutEvent(self, event):
        pass


    def keyPressEvent(self, event):
        if event.key == Key_Tab:
            widget = self.parent().focusNextChild()
            widget.setFocus()
            event.accept()


    def paintEvent(self, event):
        painter = TPainter(self)
        if self.parent():
            painter.fillRect(self.geometry(), " ")
        else:
            rect = self.geometry()
            painter.drawRect(rect)
            painter.fillRect(rect.inner(), " ")


    def resizeEvent(self, event):
        pass

    
    def update(self, rect=None):
        self.postEvent(TPaintEvent(rect))
    
        
    def repaint(self, rect=None):
        event = TPaintEvent(rect)
        self.paintEvent(event)


        


class TDesktopWidget(TWidget):


    def __init__(self):
        self.console = Console()
        super(TDesktopWidget, self).__init__()
        self._update_geom(TPoint(0, 0), self.sizeHint())

        
    def sizeHint(self):
        return TSize(self.console.width, self.console.height)

        
    def paintEvent(self, event):
        painter = TPainter(self)
        painter.fillRect(self.geometry(), ".")



        
class AbstractTextWidgetMixin(object):

    
    def __init__(self, text=""):
        self._text = text

            
    def sizeHint(self):
        return TSize(min(70, len(self._text)), 1)


    def setText(self, text):
        self._text = text
        self.resize(self.sizeHint())
        self.update()


    def text(self):
        return self._text



class TLabel(TWidget, AbstractTextWidgetMixin):

    
    def __init__(self, parent=None, text=""):
        AbstractTextWidgetMixin.__init__(self, text)
        TWidget.__init__(self, parent)

    

    def paintEvent(self, event):
        painter = TPainter(self)
        painter.drawText(self.pos(), self.text())



        
class TAbstractButton(TWidget, AbstractTextWidgetMixin):

    
    def __init__(self, parent=None, text="", checked=False):
        AbstractTextWidgetMixin.__init__(self, text)
        self._checked = checked
        TWidget.__init__(self, parent)


    def setChecked(self, flag):
        self._checked = flag
        self.update()
        
        
    def isChecked(self):
        return self._checked


        
        
class TCheckBox(TAbstractButton):
    
    
    def paintEvent(self, event):
        painter = TPainter(self)
        checked = self._checked and "x" or " "
        painter.drawText(self.pos(), "[%s] %s" % (checked, self.text()))

        

class TRadioButton(TAbstractButton):
    
    
    def paintEvent(self, event):
        painter = TPainter(self)
        checked = self._checked and "x" or " "
        painter.drawText(self.pos(), "(%s) %s" % (checked, self.text()))



        
class TPushButton(TAbstractButton):
    
    
    def paintEvent(self, event):
        painter = TPainter(self)
        painter.drawText(self.pos(), "< %s >" % self.text())
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.