forked from rpedroso/gweb2py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gweb2py.py
executable file
·1354 lines (1100 loc) · 45.9 KB
/
gweb2py.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
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
import os, sys
os.putenv('WINGDB_ACTIVE', '1')
try:
USE_VTE = True
import gobject
gobject.threads_init()
import vte
import pygtk
pygtk.require('2.0')
import gtk, gtk.gdk
except ImportError:
USE_VTE = False
import wx
import wx.lib.dialogs
import wx.lib.mixins.listctrl as listmix
import wx.lib.flatnotebook as fnb
import dircache
import re
opj = os.path.join
APP_PATH = os.path.realpath(os.path.dirname(__file__))
PORT = 8000
IS_MAC = 'wxMac' in wx.PlatformInfo
IS_WIN = 'wxMSW' in wx.PlatformInfo
def get_dir_file(filepath):
filepath_list = filepath.split(os.sep)
for d in ('controllers', 'views', 'models',
'static', 'uploads', 'modules'):
if d in filepath_list:
idx = filepath_list.index(d) + 1
if filepath_list[idx:]:
return '[%s]%s' % (d[0].upper(), opj(*filepath_list[idx:]))
return filepath_list[-1]
myEVT_BPLIST_REMOVE = wx.NewEventType()
EVT_BPLIST_REMOVE = wx.PyEventBinder(myEVT_BPLIST_REMOVE, 1)
class MyEvent(wx.PyCommandEvent):
def __init__(self, evtType, id):
wx.PyCommandEvent.__init__(self, evtType, id)
self.myVal = ()
def SetMyVal(self, val):
self.myVal = val
def GetMyVal(self):
return self.myVal
class BPList(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
def __init__(self, parent):
wx.ListCtrl.__init__(self, parent,
style=wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES
)
listmix.ListCtrlAutoWidthMixin.__init__(self)
self._bp_list = []
self._tooltips = []
self.InsertColumn(0, "Line")
self.InsertColumn(1, "Filename")
self.SetColumnWidth(0, 45)
self.SetColumnWidth(1, 300)
self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
self.Bind(wx.EVT_MOTION, self.OnMotion)
self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
def OnLeaveWindow(self, evt):
self.SetToolTip(wx.ToolTip(' '))
evt.Skip()
def OnMotion(self, evt):
row, where = self.HitTest((evt.m_x, evt.m_y))
if row>-1:
tip = self._tooltips[row]
self.SetToolTip(wx.ToolTip(tip))
evt.Skip()
def OnItemActivated(self, event):
self.currentItem = event.m_itemIndex
lineno = self.GetItemText(self.currentItem)
filename = self.getColumnText(self.currentItem, 1)
self.remove((lineno, filename))
def OnGetItemText(self, item, col):
return self._bp_list[item][col]
def getColumnText(self, index, col):
item = self.GetItem(index, col)
return item.GetText()
def append(self, bp):
self._bp_list.append(bp)
self._tooltips.append(bp[1])
self.SetItemCount(len(self._bp_list))
def remove(self, bp):
self._bp_list.remove(bp)
self._tooltips.remove(bp[1])
self.SetItemCount(len(self._bp_list))
evt = MyEvent(myEVT_BPLIST_REMOVE, self.GetId())
evt.SetMyVal(bp)
self.GetEventHandler().ProcessEvent(evt)
class Web2pyServer(object):
def __init__(self, parent, app_path, w2p_path):
self.parent = parent
self.app_path = app_path
self.w2p_path = w2p_path
self.is_running = False
self.pid = 0
self.process = None
def stop(self):
if self.pid:
stream = self.process.GetOutputStream()
stream.write('__quit__\n')
stream.flush()
#wx.CallAfter(self.process.Kill, self.pid, wx.SIGTERM)
self.is_running = False
def start(self, passwd, port):
self.process = wx.Process(self.parent)
self.process.Redirect()
p = self.app_path
sys.path.insert(0, self.w2p_path)
os.chdir(self.w2p_path)
if not os.path.isfile('web2py.py'):
self.process = None
raise Exception('%s: Execution failed' % 'web2py.py')
passwd = passwd.strip()
if passwd:
from gluon.main import save_password
save_password(passwd, port)
cmd = '"%s" -u "%s" %s "%s"' % (sys.executable, opj(p, 'gw2pserver.py'), port, self.w2p_path)
self.pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process)
if self.pid == 0:
self.process = None
raise Exception('%s: Execution failed' % 'web2py.py')
self.is_running = True
class Tree(wx.Panel):
def __init__(self, parent):
# this is just setup boilerplate
wx.Panel.__init__(self, parent)
#self.SetDoubleBuffered(True)
self.includeDirs=[]
self.excludeDirs=[]
style = wx.TR_DEFAULT_STYLE
self.tree = wx.TreeCtrl(self, style=style)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.tree, 1, wx.EXPAND, 0)
self.SetSizer(sizer)
self.tree.Bind(wx.EVT_TREE_ITEM_EXPANDING, self.OnExpand)
def OnExpand(self, event):
'''onExpand is called when the user expands a node on the tree
object. It checks whether the node has been previously expanded. If
not, the extendTree function is called to build out the node, which
is then marked as expanded.'''
# get the wxID of the entry to expand and check it's validity
itemID = event.GetItem()
if not itemID.IsOk():
itemID = self.tree.GetSelection()
self.rebuild_tree(itemID)
def rebuild_tree(self, itemID=None):
if not itemID:
itemID = self.rootID
# only build that tree if not previously expanded
old_pydata = self.tree.GetPyData(itemID)
# clean the subtree and rebuild it
self.tree.DeleteChildren(itemID)
self.extendTree(itemID)
self.tree.SetPyData(itemID, old_pydata)
def buildTree(self, rootdir):
'''Add a new root element and then its children'''
self.rootID = self.tree.AddRoot(os.path.basename(rootdir))
self.tree.SetPyData(self.rootID, rootdir)
self.extendTree(self.rootID)
# on mac cannot expand hidden root
self.tree.Expand(self.rootID)
def extendTree(self, parentID):
'''extendTree is a semi-lazy directory tree builder. It takes
the ID of a tree entry and fills in the tree with its child
subdirectories and their children - updating 2 layers of the
tree. This function is called by buildTree and onExpand methods'''
# retrieve the associated absolute path of the parent
parentDir = self.tree.GetPyData(parentID)
subdirs = dircache.listdir(parentDir)
#subdirs.sort()
for child in subdirs:
child_path = opj(parentDir, child)
if not os.path.isdir(child_path) and parentID == self.rootID:
continue
if child.endswith('.pyc'): continue
if not child.startswith('.') and not os.path.islink(child):
to_include = False
if self.includeDirs and os.path.isdir(child_path):
#[child_path p for p in self.includeDirs]
for c in self.includeDirs:
n = len(c)
if c[:n] in child_path:
to_include = True
if not to_include:
continue
if self.excludeDirs and os.path.isdir(child_path) and child_path in self.excludeDirs:
continue
# add the child to the parent
childID = self.tree.AppendItem(parentID, child)
# associate the full child path with its tree entry
self.tree.SetPyData(childID, child_path)
# Now the child entry will show up, but it current has no
# known children of its own and will not have a '+' showing
# that it can be expanded to step further down the tree.
# Solution is to go ahead and register the child's children,
# meaning the grandchildren of the original parent
newParent = child
newParentID = childID
newParentPath = child_path
newsubdirs = dircache.listdir(newParentPath) if os.path.isdir(child_path) else []
for grandchild in newsubdirs:
grandchild_path = opj(newParentPath, grandchild)
if not child.startswith('.') and not os.path.islink(grandchild_path):
grandchildID = self.tree.AppendItem(newParentID, grandchild)
self.tree.SetPyData(grandchildID, grandchild_path)
if USE_VTE:
FIXED_TABS = 1
class Terminal(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
whdl = self.GetHandle()
window = gtk.gdk.window_lookup(whdl)
self.pizza = pizza = window.get_user_data()
self.scrolled_window = scrolled_window = pizza.parent
scrolled_window.remove(pizza)
self.ctrl = ctrl = vte.Terminal()
scrolled_window.add(ctrl)
scrolled_window.show_all()
self.ctrl.connect('child-exited', self.run_command_done_callback)
#self.ctrl.connect('cursor-moved', self.contents_changed_callback)
emulation = "xterm"
font = "monospace 8"
#scrollback = 100
ctrl.set_emulation(emulation)
ctrl.set_font_from_string(font)
#ctrl.set_scrollback_lines(scrollback)
self.Layout()
def SetFocus(self):
self.ctrl.grab_focus()
def Refresh(self):
self.ctrl.queue_draw()
while gtk.events_pending(): gtk.main_iteration()
wx.Panel.Refresh(self)
def run_command(self, command_string):
'''run_command runs the command_string in the terminal. This
function will only return when self.thred_running is set to
True, this is done by run_command_done_callback'''
command = command_string.split(' ')
pid = self.ctrl.fork_command(command=command[0], argv=command, directory=os.getcwd())
return pid
def _remove(self):
notebook = self.GetParent()
page_n = notebook.get_selection_by_filename(self.filename)
notebook.DeletePage(page_n)
def run_command_done_callback(self, terminal):
if self.filename == "<shell>":
self.run_command('bash')
return
if self.ctrl.get_child_exit_status() == 0:
self._remove()
#wx.CallAfter(self._remove)
#def capture_text(self, text, text2, text3, text4):
# return True
#def contents_changed_callback(self, terminal):
# terminal_text = self.ctrl.get_text(self.capture_text)
# #print repr(terminal_text)
class Editor(Terminal):
def __init__(self, parent):
Terminal.__init__(self, parent)
def quit(self):
self.ctrl.feed_child(':qall\n')
def openfile(self, filename):
current_path = os.getcwd()
os.chdir(APP_PATH)
pid = self.run_command('vim -ni NONE %s -X -U NONE' % filename)
os.chdir(current_path)
return pid
def savefile(self, filename):
self.ctrl.feed_child(':w\n')
def trace_line_clear(self):
self.ctrl.feed_child(':match\n')
def trace_line(self, lineno):
self.ctrl.feed_child(':%s\nzo' % lineno)
self.ctrl.feed_child(":nnoremap <silent> <Leader>l ml:execute 'match Search /\%'.line('.').'l/'\n\l\n")
def set_break(self, lineno, filename):
self.ctrl.feed_child(':%s\nzo' % lineno)
self.ctrl.feed_child(':sign define wholeline linehl=ErrorMsg\n')
self.ctrl.feed_child(':sign place %d name=wholeline line=%s file=%s\n' % (lineno, lineno, filename))
def clear_break(self, lineno):
self.ctrl.feed_child(':sign unplace %s\n' % lineno)
else:
FIXED_TABS = 0
from editor import Editor
class InfoPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
b = wx.BoxSizer(wx.VERTICAL)
s = wx.StaticText(self, label="Breakpoints")
self.bp_list = BPList(self)
b.Add(s, 0)
b.Add(self.bp_list, 1, wx.EXPAND, 0)
self.SetSizer(b)
class TextCtrl(wx.TextCtrl):
def __init__(self, parent,
style=wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL|wx.TE_RICH2):
wx.TextCtrl.__init__(self, parent, style=style)
if not IS_MAC and not IS_WIN:
self.SetBackgroundColour(wx.BLACK)
self.SetForegroundColour(wx.WHITE)
self.SetFont(wx.Font(8, wx.TELETYPE, wx.NORMAL, wx.NORMAL, False))
class ShellCtrl(TextCtrl):
def __init__(self, parent):
self._history = ['']
self._hist_idx = 0
self._prompt = '> '
style = wx.TE_MULTILINE|wx.HSCROLL|wx.TE_RICH2|wx.TE_PROCESS_ENTER
TextCtrl.__init__(self, parent, style)
self.set_prompt()
self.Bind(wx.EVT_KEY_DOWN , self.OnKeyDown)
self.Bind(wx.EVT_TEXT_ENTER, self.OnEnter)
def set_prompt(self):
TextCtrl.AppendText(self, self._prompt)
def send_command(self, text):
text = text.strip()
if text:
self.GetTopLevelParent().shell_command(text)
self._history.append(text)
self._hist_idx = len(self._history)
if self._hist_idx > 1000:
self._history.pop(1)
self._hist_idx = len(self._history)
else:
wx.CallAfter(self.set_prompt)
def Clear(self):
TextCtrl.ChangeValue(self, '')
self.set_prompt()
def GetNumberOfLines(self):
n = TextCtrl.GetNumberOfLines(self)
if IS_MAC:
return n - 1
return n
def GetCurrentLine(self):
curPos = self.GetInsertionPoint()
lineno = self.PositionToXY(curPos)[1]
return lineno
def GetLinePosition(self, lineno):
x = self.GetLineLength(lineno)
start = self.XYToPosition(0, lineno)
end = start + x
return (start, end)
def ClearLine(self, lineno):
start, end = self.GetLinePosition(lineno)
print start, end
self.Replace(start, end, '')
def OnKeyDown(self, evt):
text = None
key = evt.KeyCode
if key == wx.WXK_DOWN:
self._hist_idx += 1
try:
text = self._history[self._hist_idx]
except IndexError:
self._hist_idx = 0
text = self._history[self._hist_idx]
elif key == wx.WXK_UP:
self._hist_idx -= 1
try:
text = self._history[self._hist_idx]
except IndexError:
self._hist_idx = len(self._history) - 1
text = self._history[self._hist_idx]
if text is not None:
lineno = self.GetCurrentLine()
self.ClearLine(lineno)
self.set_prompt()
TextCtrl.AppendText(self, text)
else:
evt.Skip()
def OnEnter(self, evt):
self.SetInsertionPointEnd()
text = self.GetLineText(self.GetNumberOfLines()).lstrip(self._prompt)
self.send_command(text.strip())
evt.Skip()
def AppendText(self, text):
text = text.strip()
if (text.startswith('<Storage {')
or text.startswith('<Row {')
or text.startswith('<DAL {')):
text = text.split(', ')
text = ',\n'.join(text)
text = "%s\n" % text
if IS_MAC:
text = text.replace('\n', '\r')
TextCtrl.AppendText(self, text)
wx.CallAfter(self.set_prompt)
# Monkey patch: do not draw a focus rectangle on tabs
NBRendererDefault_original = fnb.FNBRendererDefault
class FNBRendererDefaultPatched(NBRendererDefault_original):
def DrawFocusRectangle(self, dc, pageContainer, page):
pass
fnb.FNBRendererDefault = FNBRendererDefaultPatched
if IS_WIN:
NotebookBase = wx.Notebook
else:
NotebookBase = fnb.FlatNotebook
class Notebook(NotebookBase):
def __init__(self, parent, style):
NotebookBase.__init__(self, parent, wx.ID_ANY, style=style)
#class Notebook(wx.Notebook):
# def __init__(self, parent):
# wx.Notebook.__init__(self, parent, style=wx.NB_MULTILINE)
def GetChildren(self):
return [c for c in NotebookBase.GetChildren(self) \
if not isinstance(c, fnb.PageContainer)]
def __contains__(self, o):
for c in self.GetChildren():
if c.filename == o:
return True
return False
def get_selection_by_filename(self, name):
for i, c in enumerate(self.GetChildren()):
if c.filename == name:
return i
return -1
def set_selection_by_filename(self, name):
i = self.get_selection_by_filename(name)
if i > -1:
self.SetSelection(i)
def SetFocus(self):
idx = self.GetSelection()
self.GetChildren()[idx].SetFocus()
def DeletePage(self, idx):
#print idx
if idx < 0:
return
w = self.GetPage(idx)
if w.filename in ('<shell>',):
return
#wx.Notebook.DeletePage(self, idx)
NotebookBase.DeletePage(self, idx)
class LogPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, style=wx.WANTS_CHARS)
if IS_WIN:
style = 0
else:
style = (fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_SMART_TABS
| fnb.FNB_NODRAG | fnb.FNB_NO_X_BUTTON)
self.notebook = nb = Notebook(self, style=style)
self.t_ws = t = TextCtrl(nb)
nb.AddPage(t, "WebServer Logs")
self.t_stdout = t = TextCtrl(nb)
nb.AddPage(t, "stdout", select=False)
self.t_stderr = t = TextCtrl(nb)
nb.AddPage(t, "stderr", select=False)
self.t_request = t = TextCtrl(nb)
nb.AddPage(t, "request", select=False)
self.t_response = t = TextCtrl(nb)
nb.AddPage(t, "response", select=False)
self.t_shell = t = ShellCtrl(nb)
nb.AddPage(t, "eval shell", select=False)
b = wx.BoxSizer(wx.HORIZONTAL)
b.Add(nb, 1, wx.EXPAND, 0)
self.SetSizer(b)
self.RE_WS = re.compile("HTTP/\d.\d +(\w+)")
self.default_text_attr = wx.TextAttr(wx.LIGHT_GREY, wx.NullColour)
self.t_ws.SetDefaultStyle(wx.TextAttr(wx.LIGHT_GREY, wx.NullColour))
#wx.Log_SetActiveTarget(wx.LogTextCtrl(t))
def ws_write(self, t):
t = t.decode('utf-8', 'replace')
styles = {
200: wx.TextAttr(wx.GREEN, wx.NullColour),
304: wx.TextAttr(wx.BLUE, wx.NullColour),
404: wx.TextAttr(wx.RED, wx.NullColour),
}
s = self.RE_WS.search(t)
attr = self.default_text_attr
if s:
try:
code = int(s.group(1))
attr = styles[code]
except (ValueError, KeyError):
pass
self.t_ws.SetDefaultStyle(attr)
self.t_ws.AppendText(t)
def stdout_write(self, t):
t = t.decode('utf-8', 'replace')
self.t_stdout.AppendText(t)
def stderr_write(self, t):
t = t.decode('utf-8', 'replace')
self.t_stderr.AppendText(t)
def request_write(self, t):
t = t.decode('utf-8', 'replace')
self.t_request.AppendText(t.replace('\r', ''))
def response_write(self, t):
t = t.decode('utf-8', 'replace')
self.t_response.AppendText(t)
def shell_write(self, t):
t = t.decode('utf-8', 'replace')
self.t_shell.AppendText(t)
class BitmapWindow(wx.Window):
def __init__(self, parent):
wx.Window.__init__(self, parent, style=wx.FULL_REPAINT_ON_RESIZE)
self.img = None
self.Bind(wx.EVT_PAINT, self.OnPaint)
def OnPaint(self, evt):
if not self.img:
return
dc = wx.PaintDC(self)
dc.SetBackground(wx.Brush("WHITE"))
dc.Clear()
img = self.img.Copy()
iw, ih = img.GetSize()
w, h = self.GetSize()
factor = min(float(w)/iw, float(h)/ih)
if factor > 1:
factor = 1
rw = iw * factor
rh = ih * factor
img.Rescale(iw*factor, ih*factor, wx.IMAGE_QUALITY_HIGH)
bmp = img.ConvertToBitmap()
dc.DrawBitmap(bmp, (w-rw)/2., (h-rh)/2., True)
def SetFilenameBitmap(self, filename):
self.img = wx.Image(filename)
self.Refresh()
class BitmapInfoPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
b = wx.FlexGridSizer(3, 2)
#st_filename = wx.StaticText(self, label="filename")
st_width = wx.StaticText(self, label="width")
st_height = wx.StaticText(self, label="height")
#t_filename = wx.TextCtrl(self, style=wx.TE_READONLY)
t_width = wx.TextCtrl(self, style=wx.TE_READONLY)
t_height = wx.TextCtrl(self, style=wx.TE_READONLY)
#self.t_filename = t_filename
self.t_width = t_width
self.t_height = t_height
#b.Add(st_filename)
#b.Add(t_filename, 1, wx.EXPAND, 0)
b.Add(st_width)
b.Add(t_width, 1, wx.EXPAND, 0)
b.Add(st_height)
b.Add(t_height, 1, wx.EXPAND, 0)
b.AddGrowableCol(1)
self.SetSizer(b)
def SetInfo(self, img):
#self.t_filename.SetValue(repr(img))
w, h = img.GetSize()
self.t_width.SetValue(str(w))
self.t_height.SetValue(str(h))
class BitmapPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
b = wx.BoxSizer(wx.VERTICAL)
self.bmp_win = BitmapWindow(self)
self.bmp_info = BitmapInfoPanel(self)
b.Add(self.bmp_win, 1, wx.EXPAND, 0)
b.Add(self.bmp_info, 0, wx.EXPAND, 0)
self.SetSizer(b)
def SetFilenameBitmap(self, filename):
self.bmp_win.SetFilenameBitmap(filename)
self.bmp_info.SetInfo(self.bmp_win.img)
class MainPanel(wx.Panel):
def __init__(self, parent, w2p_path):
wx.Panel.__init__(self, parent)
self.Freeze()
winids = []
leftwin = wx.SashLayoutWindow( self,
style=wx.NO_BORDER | wx.SW_3D
)
leftwin.SetDefaultSize((160, -1))
leftwin.SetOrientation(wx.LAYOUT_VERTICAL)
leftwin.SetAlignment(wx.LAYOUT_LEFT)
leftwin.SetSashVisible(wx.SASH_RIGHT, True)
leftwin.SetExtraBorderSize(0)
self.leftwin = leftwin
winids.append(leftwin.GetId())
self.tree = t = Tree(leftwin)
t.buildTree(opj(w2p_path, 'applications'))
t.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivated)
rightwin = wx.SashLayoutWindow(self,
style=wx.NO_BORDER | wx.SW_3D
)
rightwin.SetDefaultSize((160, -1))
rightwin.SetOrientation(wx.LAYOUT_VERTICAL)
rightwin.SetAlignment(wx.LAYOUT_RIGHT)
rightwin.SetSashVisible(wx.SASH_LEFT, True)
self.rightwin = rightwin
winids.append(rightwin.GetId())
self.info = InfoPanel(rightwin)
rightwin.Hide()
bottomwin = wx.SashLayoutWindow(self,
style=wx.NO_BORDER | wx.SW_3D
)
bottomwin.SetDefaultSize((-1, 150))
bottomwin.SetOrientation(wx.LAYOUT_HORIZONTAL)
bottomwin.SetAlignment(wx.LAYOUT_BOTTOM)
bottomwin.SetSashVisible(wx.SASH_TOP, True)
self.bottomwin = bottomwin
winids.append(bottomwin.GetId())
self.log = LogPanel(bottomwin)
if IS_WIN:
style = 0
else:
style = (fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_MOUSE_MIDDLE_CLOSES_TABS
| fnb.FNB_X_ON_TAB | fnb.FNB_SMART_TABS
| fnb.FNB_DROPDOWN_TABS_LIST | fnb.FNB_NODRAG)
self.notebook = nb = Notebook(self, style=style)
if USE_VTE:
self.terminal = Terminal(nb)
self.terminal.page_idx = self.notebook.GetPageCount()
self.terminal.filename = '<shell>'
self.terminal.run_command('bash')
self.terminal.ctrl.feed_child('PS1="web2py@\W\$ "\n')
self.terminal.ctrl.feed_child('')
nb.AddPage(self.terminal, "Shell")
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(
wx.EVT_SASH_DRAGGED_RANGE, self.OnSashDrag,
id=min(winids), id2=max(winids)
)
self.Thaw()
def Layout(self):
wx.LayoutAlgorithm().LayoutWindow(self, self.notebook)
def OnSize(self, event):
wx.LayoutAlgorithm().LayoutWindow(self, self.notebook)
event.Skip()
def OnSashDrag(self, event):
if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE:
return
eobj = event.GetEventObject()
if eobj is self.leftwin:
self.leftwin.SetDefaultSize((event.GetDragRect().width, -1))
elif eobj is self.rightwin:
self.rightwin.SetDefaultSize((event.GetDragRect().width, -1))
elif eobj is self.bottomwin:
self.bottomwin.SetDefaultSize((-1, event.GetDragRect().height))
wx.LayoutAlgorithm().LayoutWindow(self, self.notebook)
self.notebook.Refresh()
def ClosePanel(self, cb):
vims = list(self.notebook.GetChildren())
for i, vim in enumerate(vims):
if isinstance(vim, Editor):
vim.quit()
else:
self.notebook.DeletePage(i)
wx.SafeYield()
import time
time.sleep(.2)
wx.SafeYield()
if USE_VTE:
while gtk.events_pending(): gtk.main_iteration()
if self.notebook.GetPageCount() <= FIXED_TABS:
cb(True)
else:
cb(False)
def OnActivated(self, evt):
t = evt.GetEventObject()
item = evt.GetItem()
if item:
ndir = t.GetPyData(item)
self.open_tab(ndir, get_dir_file(ndir))
evt.Skip()
def open_tab(self, ndir, itemtext):
ndir = os.path.abspath(ndir)
if IS_WIN:
ndir = ndir.lower()
ndir_isfile = os.path.isfile(ndir)
if ndir_isfile and os.path.splitext(ndir.lower())[-1] in ('.py', '.html', '.css', '.js', '.load', '.xml', '.json', '.rss'):
if ndir in self.notebook:
self.notebook.set_selection_by_filename(ndir)
else:
editor = Editor(self.notebook)
editor.page_idx = self.notebook.GetPageCount()
editor.filename = ndir
self.notebook.AddPage(editor, itemtext)
self.notebook.set_selection_by_filename(ndir)
pid = editor.openfile(ndir)
editor.pid = pid
editor.Refresh()
editor.SetFocus()
elif ndir_isfile and os.path.splitext(ndir.lower())[-1] in ('.png', '.jpg', '.gif', '.ico'):
self.open_image(ndir, itemtext)
elif os.path.isdir(ndir):
if USE_VTE:
self.terminal.ctrl.feed_child('\ncd %s\n' % ndir)
def open_image(self, ndir, itemtext):
if '<image>' in self.notebook:
self.notebook.set_selection_by_filename('<image>')
sbmp = self.notebook.GetCurrentPage()
sbmp.SetFilenameBitmap(ndir)
sbmp.filename = '<image>'
self.notebook.SetPageText(sbmp.page_idx, itemtext)
else:
sbmp = BitmapPanel(self.notebook)
sbmp.SetFilenameBitmap(ndir)
sbmp.page_idx = self.notebook.GetPageCount()
sbmp.filename = '<image>'
self.notebook.AddPage(sbmp, itemtext)
self.notebook.SetSelection(sbmp.page_idx)
class Frame(wx.Frame):
def __init__(self, parent , size, w2p_path=None):
wx.Frame.__init__(self, parent, size=size, title="gweb2py",
style=(wx.DEFAULT_FRAME_STYLE | wx.CLIP_CHILDREN))
self.SetDoubleBuffered(True)
self.server = None
self.panel = None
self.w2p_path = w2p_path
self.previous_editor = None
#Build menus
menuBar = wx.MenuBar()
menu = wx.Menu()
self.menu_item_w2p_open = menu.Append(wx.ID_ANY, "&Open", "")
self.menu_item_w2p_close = menu.Append(wx.ID_ANY, "&Close", "")
menu.AppendSeparator()
self.menu_item_w2p_quit = menu.Append(wx.ID_ANY, "&Quit", "")
menuBar.Append(menu, "&Web2py")
self.menu_w2p = menu
self.Bind(wx.EVT_MENU, self.OnMenuW2pOpen, self.menu_item_w2p_open)
self.Bind(wx.EVT_MENU, self.OnMenuW2pClose, self.menu_item_w2p_close)
self.Bind(wx.EVT_MENU, self.OnMenuW2pQuit, self.menu_item_w2p_quit)
menu = wx.Menu()
self.menu_item_app_new = menu.Append(wx.ID_ANY, "&New", "")
menuBar.Append(menu, "&Application")
self.menu_app = menu
self.Bind(wx.EVT_MENU, self.OnMenuAppNew, self.menu_item_app_new)
menu = wx.Menu()
#item1 = menu.Append(wx.ID_ANY, "&New", "")
#item2 = menu.Append(wx.ID_ANY, "&Open", "")
self.menu_item_file_save = menu.Append(wx.ID_ANY, "&Save\tCtrl-S", "Save current file")
#item4 = menu.Append(wx.ID_ANY, "&Close", "")
menuBar.Append(menu, "&File")
self.menu_file = menu
#self.Bind(wx.EVT_MENU, self.OnMenuFileNew, item1)
#self.Bind(wx.EVT_MENU, self.OnMenuFileOpen, item2)
self.Bind(wx.EVT_MENU, self.OnMenuFileSave, self.menu_item_file_save)
#self.Bind(wx.EVT_MENU, self.OnMenuFileClose, item4)
menu = wx.Menu()
item1 = menu.Append(wx.ID_ANY, "Focus file &browser\tCtrl+1", "Set focus to file browser window")
item2 = menu.Append(wx.ID_ANY, "Focus &editor\tCtrl+2", "Set focus to current editor window")
menu.AppendSeparator()
item3 = menu.Append(wx.ID_ANY, "&Previous tab\tCtrl+PageUp", "Previous tab")
item4 = menu.Append(wx.ID_ANY, "&Next tab\tCtrl+PageDown", "Next tab")
item5 = menu.Append(wx.ID_ANY, "&Close tab\tCtrl+w", "Close current tab.")
ID6=wx.NewId()
menu.AppendSeparator()
item6 = menu.Append(ID6, "&Clear current output window\tCtrl+K", "Clear contents of current output window")
menuBar.Append(menu, "&Windows")
self.menu_windows = menu
self.Bind(wx.EVT_MENU, self.OnMenuFocusFileBrowser, item1)
self.Bind(wx.EVT_MENU, self.OnMenuFocusNotebook, item2)
self.Bind(wx.EVT_MENU, self.OnMenuWindowsPrev, item3)
self.Bind(wx.EVT_MENU, self.OnMenuWindowsNext, item4)
self.Bind(wx.EVT_MENU, self.OnMenuCloseTab, item5)
self.Bind(wx.EVT_MENU, self.OnMenuWindowClear, item6)
self.menu_debug = wx.Menu()
if IS_MAC:
self.f2 = self.menu_debug.Append(wx.ID_ANY, "&Enable/Disable debug\tCtrl+F2", "Turn debugger on or off")
self.f3 = self.menu_debug.Append(wx.ID_ANY, "&Add/Remove breakpoint...\tCtrl+F3", "Add or remove breakpoint...")
self.f4 = self.menu_debug.Append(wx.ID_ANY, "&Enable/Disable gluon debug \tCtrl+F4", "Allow debugging web2py gluon code")
self.menu_debug.AppendSeparator()
self.f6 = self.menu_debug.Append(wx.ID_ANY, "&Continue\tCtrl+F6", "Continue to next breakpoint or until the end")
self.f7 = self.menu_debug.Append(wx.ID_ANY, "&Debug step\tCtrl+F7", "Stop after one line of code.")
self.f8 = self.menu_debug.Append(wx.ID_ANY, "&Debug next\tCtrl+F8", "Stop on the next line in or below the given frame.")
self.f9 = self.menu_debug.Append(wx.ID_ANY, "&Debug until\tCtrl+F9", "Stop when the line with the line number greater than the current one is reached or when returning from current frame")
else:
self.f2 = self.menu_debug.Append(wx.ID_ANY, "&Enable/Disable debug\tF2", "Turn debugger on or off")
self.f3 = self.menu_debug.Append(wx.ID_ANY, "&Add/Remove breakpoint...\tF3", "Add or remove breakpoint...")
self.f4 = self.menu_debug.Append(wx.ID_ANY, "&Enable/Disable gluon debug \tF4", "Allow debugging web2py gluon code")
self.menu_debug.AppendSeparator()
self.f6 = self.menu_debug.Append(wx.ID_ANY, "&Continue\tF6", "Continue to next breakpoint or until the end")
self.f7 = self.menu_debug.Append(wx.ID_ANY, "&Debug step\tF7", "Stop after one line of code.")
self.f8 = self.menu_debug.Append(wx.ID_ANY, "&Debug next\tF8", "Stop on the next line in or below the given frame.")
self.f9 = self.menu_debug.Append(wx.ID_ANY, "&Debug until\tF9", "Stop when the line with the line number greater than the current one is reached or when returning from current frame")
#item6 = self.menu_debug.Append(wx.ID_ANY, "&Eval \tF9", "")
menuBar.Append(self.menu_debug, "&Debug")
self.SetMenuBar(menuBar)
# Status bar
self.sb = wx.StatusBar(self)
self.SetStatusBar(self.sb)
# Timer
self.timer = wx.Timer(self)
# Bind menus events
self.Bind(wx.EVT_MENU, self.OnMenuDebugUntil, self.f9)
self.Bind(wx.EVT_MENU, self.OnMenuDebugToggle, self.f2)
self.Bind(wx.EVT_MENU, self.OnMenuDebugContinue, self.f6)
self.Bind(wx.EVT_MENU, self.OnMenuDebugStep, self.f7)
self.Bind(wx.EVT_MENU, self.OnMenuDebugNext, self.f8)
self.Bind(wx.EVT_MENU, self.OnMenuDebugAllowGluon, self.f4)
self.Bind(wx.EVT_MENU, self.OnMenuDebugAddBP, self.f3)
# Bind breakpoint event to remove breakpoints on double click
self.Bind(EVT_BPLIST_REMOVE, self.OnBPRemove)
self.Bind(wx.EVT_CLOSE, self.OnClose)
self.Bind(wx.EVT_TIMER, self.OnTimer)
self.Bind(wx.EVT_IDLE, self.OnTimer)
self.Bind(wx.EVT_END_PROCESS, self.OnProcessEnded)
#self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI)
self.Show()
if self.w2p_path:
self.AppOpen()
def SendSizeEvent(self):
if IS_MAC:
w, h = self.GetSize()
self.SetSize((w-1, h-1))
self.SetSize((w, h))
else:
wx.Frame.SendSizeEvent(self)