# Created by Leo from: C:\Python23\Tom\leo\browser3.leo # # -*- coding: utf-8 -*- # #!/usr/bin/env python # << TomBrowse declarations >> import wx import wx.html as html import wx.lib.wxpTag import wx.lib.newevent import wx.lib.mixins.listctrl as listmix from wx.stc import * import wx.py as py import keyword import os,string import sys import Image import image_view import webwig import HTMLparse,cStringIO import urllib2 ,urllib, sgmllib from string import lower, replace, split, join faces = { 'times': 'Times New Roman', 'mono' : 'Courier New', 'helv' : 'Arial', 'other': 'Comic Sans MS', 'size' : 10, 'size2': 8, } # -- end -- << TomBrowse declarations >> # << TomBrowse methods >> (1 of 11) class HTML2Text(sgmllib.SGMLParser): # << class HTML2Text declarations >> from htmlentitydefs import entitydefs # replace entitydefs from sgmllib # -- end -- << class HTML2Text declarations >> # << class HTML2Text methods >> (1 of 8) def __init__(self, ignore_tags=(), indent_width=4, page_width=80): sgmllib.SGMLParser.__init__(self) self.result = "" self.indent = 0 self.ol_number = 0 self.page_width=page_width self.inde_width=indent_width self.lines=[] self.line=[] self.ignore_tags = ignore_tags # << class HTML2Text methods >> (2 of 8) def add_text(self,text): # convert text into words words = split(replace(text,'\n',' ')) self.line.extend(words) # << class HTML2Text methods >> (3 of 8) def add_break(self): self.lines.append((self.indent,self.line)) self.line=[] # << class HTML2Text methods >> (4 of 8) def generate(self): # join lines with indents indent_width = self.inde_width page_width = self.page_width out_paras=[] for indent,line in self.lines+[(self.indent,self.line)]: i=indent*indent_width indent_string = i*' ' line_width = page_width-i out_para='' out_line=[] len_out_line=0 for word in line: len_word = len(word) if len_out_line+len_word> (5 of 8) def mod_indent(self,i): self.indent = self.indent + i if self.indent < 0: self.indent = 0 # << class HTML2Text methods >> (6 of 8) def handle_data(self, data): if data: self.add_text(data) # << class HTML2Text methods >> (7 of 8) def unknown_starttag(self, tag, attrs): """ Convert HTML to something meaningful in plain text """ tag = lower(tag) if tag not in self.ignore_tags: try: if tag[0]=='h' or tag in ['br','pre','p','hr']: # insert a blank line self.add_break() elif tag =='img': # newline, text, newline src = '' for k, v in attrs: if lower(k) == 'src': src = v self.add_break() self.add_text('Image: ' + src) elif tag =='li': self.add_break() if self.ol_number: # num - text self.add_text(str(self.ol_number) + ' - ') self.ol_number = self.ol_number + 1 else: # - text self.add_text('- ') elif tag in ['dd','dt']: self.add_break() # increase indent self.mod_indent(+1) elif tag in ['ul','dl','ol']: # blank line # increase indent self.mod_indent(+1) if tag=='ol': self.ol_number = 1 except: pass # << class HTML2Text methods >> (8 of 8) def unknown_endtag(self, tag): """ Convert HTML to something meaningful in plain text """ tag = lower(tag) if tag not in self.ignore_tags: try: if tag[0]=='h' or tag in ['pre']: # newline, text, newline self.add_break() elif tag =='li': self.add_break() elif tag in ['dd','dt']: self.add_break() # descrease indent self.mod_indent(-1) elif tag in ['ul','dl','ol']: # blank line self.add_break() # decrease indent self.mod_indent(-1) self.ol_number = 0 except: pass # -- end -- << class HTML2Text methods >> # << TomBrowse methods >> (2 of 11) def html2text(s, ignore_tags=(), indent_width=4, page_width=80): ignore_tags = [t.lower() for t in ignore_tags] parser = HTML2Text(ignore_tags, indent_width, page_width) parser.feed(s) parser.close() parser.generate() return parser.result # << TomBrowse methods >> (3 of 11) class ImgS(wx.Notebook): # << class ImgFrame methods >> (1 of 5) def __init__(self, parent, id,rframe): wx.Notebook.__init__(self, parent, id) self.rframe = rframe self.ViewList = [] #self.ViewList.append(image_view.ImageView(self,id,tools = [image_view.PanTool,image_view.ZoomTool, image_view.InspectTool ,image_view.BoxTool , image_view.SharpTool , image_view.ColorTool , image_view.BrightTool , image_view.ContTool , image_view.RestoreTool , image_view.RedTool , image_view.GreenTool , image_view.BlueTool, image_view.LoadTool, image_view.SaveTool, image_view.URLTool], image = None, pos=(-1, -1), size=(-1, -1), style=0, name='ImageView')) #self.AddPage(self.ViewList[0],'') # << class ImgFrame methods >> (2 of 5) def UrlAdd(self, path): imgtxt = '' try: imgtxt = urllib2.urlopen(path).read() except: #output to self.shelllog for i in sys.exc_info(): self.rframe.shelllog.SetValue(self.rframe.shelllog.GetValue() + str(i)+ '\n') img = None try: img = Image.open(cStringIO.StringIO(imgtxt)) except: #output to self.shelllog for i in sys.exc_info(): self.rframe.shelllog.SetValue(self.rframe.shelllog.GetValue() + str(i)+ '\n') self.ViewList.append(image_view.ImageView(self,-1,tools = [image_view.PanTool,image_view.ZoomTool, image_view.InspectTool , image_view.SharpTool , image_view.ColorTool , image_view.BrightTool , image_view.ContTool , image_view.RestoreTool , image_view.RedTool , image_view.GreenTool , image_view.BlueTool, image_view.LoadTool, image_view.SaveTool, image_view.URLTool], image = img, pos=(-1, -1), size=(-1, -1), style=0, name='ImageView')) self.AddPage(self.ViewList[len(self.ViewList)-1],os.path.split(path)[1]) # << class ImgFrame methods >> (3 of 5) def ImageAdd(self,img, path): id = wxNewId() #self.ViewList.append(image_view.ImageView(self.notebook,id))#,tools = [image_view.PanTool, image_view.ZoomTool, image_view.SaveTool])) #self.ViewList[len(self.ViewList)-1].set_image(img) self.ViewList.append(image_view.ImageView(self,id,tools = [image_view.PanTool,image_view.ZoomTool, image_view.InspectTool , image_view.SharpTool , image_view.ColorTool , image_view.BrightTool , image_view.ContTool , image_view.RestoreTool , image_view.RedTool , image_view.GreenTool , image_view.BlueTool, image_view.LoadTool, image_view.SaveTool, image_view.URLTool], image = img, pos=(-1, -1), size=(-1, -1), style=0, name='ImageView')) self.AddPage(self.ViewList[len(self.ViewList)-1],os.path.split(path)[1]) # << class ImgFrame methods >> (4 of 5) def FileAdd(self, path): img = Image.open(file(path)) id = wxNewId() #self.ViewList.append(image_view.ImageView(self.notebook,id))#,tools = [image_view.PanTool, image_view.ZoomTool, image_view.SaveTool])) #self.ViewList[len(self.ViewList)-1].set_image(img) self.ViewList.append(image_view.ImageView(self,id,tools = [image_view.PanTool,image_view.ZoomTool, image_view.InspectTool , image_view.SharpTool , image_view.ColorTool , image_view.BrightTool , image_view.ContTool , image_view.RestoreTool , image_view.RedTool , image_view.GreenTool , image_view.BlueTool, image_view.LoadTool, image_view.SaveTool, image_view.URLTool], image = img, pos=(-1, -1), size=(-1, -1), style=0, name='ImageView')) self.AddPage(self.ViewList[len(self.ViewList)-1],os.path.split(path)[1]) # << class ImgFrame methods >> (5 of 5) def Refresh(self): self.DeleteAllPages() self.ViewList = [] #self.ViewList.append(image_view.ImageView(self,-1,tools = [image_view.PanTool,image_view.ZoomTool, image_view.InspectTool ,image_view.BoxTool , image_view.SharpTool , image_view.ColorTool , image_view.BrightTool , image_view.ContTool , image_view.RestoreTool , image_view.RedTool , image_view.GreenTool , image_view.BlueTool, image_view.LoadTool, image_view.SaveTool, image_view.URLTool], image = None, pos=(-1, -1), size=(-1, -1), style=0, name='ImageView')) #self.AddPage(self.ViewList[0],'') # -- end -- << class ImgFrame methods >> # << TomBrowse methods >> (4 of 11) class LinkListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin): # << class LinkListCtrl methods >> def __init__(self, parent, ID, pos=wx.DefaultPosition,size=wx.DefaultSize, style=0): wx.ListCtrl.__init__(self, parent, ID, pos, size, style) listmix.ListCtrlAutoWidthMixin.__init__(self) # -- end -- << class LinkListCtrl methods >> # << TomBrowse methods >> (5 of 11) class LinkListCtrlPanel(wx.Panel, listmix.ColumnSorterMixin): # << class LinkListCtrlPanel methods >> (1 of 21) def __init__(self, parent): wx.Panel.__init__(self, parent, -1, style=wx.WANTS_CHARS) self.parent = parent tID = wx.NewId() self.currentItem = None #self.il = wx.ImageList(16, 16) #self.idx1 = self.il.Add(images.getSmilesBitmap()) #self.sm_up = self.il.Add(images.getSmallUpArrowBitmap()) #self.sm_dn = self.il.Add(images.getSmallDnArrowBitmap()) self.list = LinkListCtrl(self, tID, style=wx.LC_REPORT | wx.SUNKEN_BORDER| wx.LC_EDIT_LABELS) #| wxLC_NO_HEADER | wxLC_VRULES | wxLC_HRULES ) #self.list.SetImageList(self.il, wx.IMAGE_LIST_SMALL) #self.PopulateList() self.list.InsertColumn(0, 'Link') self.list.InsertColumn(1,'Text' , wx.LIST_FORMAT_RIGHT) self.list.SetColumnWidth(0, 250) self.list.SetColumnWidth(1, 250) # Now that the list exists we can init the other base class, # see wxPython/lib/mixins/listctrl.py #self.itemDataMap = musicdata self.itemDataMap = {} listmix.ColumnSorterMixin.__init__(self, 2) self.SortListItems(0, True) self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self.list) self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected, self.list) self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated, self.list) self.Bind(wx.EVT_LIST_DELETE_ITEM, self.OnItemDelete, self.list) self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick, self.list) self.Bind(wx.EVT_LIST_COL_RIGHT_CLICK, self.OnColRightClick, self.list) self.Bind(wx.EVT_LIST_COL_BEGIN_DRAG, self.OnColBeginDrag, self.list) self.Bind(wx.EVT_LIST_COL_DRAGGING, self.OnColDragging, self.list) self.Bind(wx.EVT_LIST_COL_END_DRAG, self.OnColEndDrag, self.list) self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnBeginEdit, self.list) self.list.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick) self.list.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown) # for wxMSW self.list.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick) # for wxGTK self.list.Bind(wx.EVT_RIGHT_UP, self.OnRightClick) # << class LinkListCtrlPanel methods >> (2 of 21) def GetListCtrl(self): return self.list # << class LinkListCtrlPanel methods >> (3 of 21) def OnRightDown(self, event): self.x = event.GetX() self.y = event.GetY() #self.log.WriteText("x, y = %s\n" % str((self.x, self.y))) item, flags = self.list.HitTest((self.x, self.y)) if flags & wx.LIST_HITTEST_ONITEM: self.list.Select(item) event.Skip() # << class LinkListCtrlPanel methods >> (4 of 21) def getColumnText(self, index, col): item = self.list.GetItem(index, col) return item.GetText() # << class LinkListCtrlPanel methods >> (5 of 21) def OnItemSelected(self, event): ##print event.GetItem().GetTextColour() self.currentItem = event.m_itemIndex event.Skip() # << class LinkListCtrlPanel methods >> (6 of 21) def OnItemDeselected(self, evt): pass # << class LinkListCtrlPanel methods >> (7 of 21) def OnItemActivated(self, event): self.currentItem = event.m_itemIndex event.Skip() # << class LinkListCtrlPanel methods >> (8 of 21) def OnBeginEdit(self, event): #self.log.WriteText("OnBeginEdit") event.Allow() # << class LinkListCtrlPanel methods >> (9 of 21) def OnItemDelete(self, event): #self.log.WriteText("OnItemDelete\n") pass # << class LinkListCtrlPanel methods >> (10 of 21) def OnColClick(self, event): #self.log.WriteText("OnColClick: %d\n" % event.GetColumn()) event.Skip() # << class LinkListCtrlPanel methods >> (11 of 21) def OnColRightClick(self, event): item = self.list.GetColumn(event.GetColumn()) #self.log.WriteText("OnColRightClick: %d %s\n" %(event.GetColumn(), (item.GetText(), item.GetAlign(), item.GetWidth(), item.GetImage()))) # << class LinkListCtrlPanel methods >> (12 of 21) def OnColBeginDrag(self, event): #self.log.WriteText("OnColBeginDrag\n") pass ## Show how to not allow a column to be resized #if event.GetColumn() == 0: # event.Veto() # << class LinkListCtrlPanel methods >> (13 of 21) def OnColDragging(self, event): #self.log.WriteText("OnColDragging\n") pass # << class LinkListCtrlPanel methods >> (14 of 21) def OnColEndDrag(self, event): #self.log.WriteText("OnColEndDrag\n") pass # << class LinkListCtrlPanel methods >> (15 of 21) def OnDoubleClick(self, event): #self.log.WriteText("OnDoubleClick item %s\n" % self.list.GetItemText(self.currentItem)) event.Skip() # << class LinkListCtrlPanel methods >> (16 of 21) def OnRightClick(self, event): #self.log.WriteText("OnRightClick %s\n" % self.list.GetItemText(self.currentItem)) # only do this part the first time so the events are only bound once if not hasattr(self, "popupID1"): self.popupID1 = wx.NewId() self.popupID2 = wx.NewId() self.popupID3 = wx.NewId() self.popupID4 = wx.NewId() self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1) self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2) self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3) self.Bind(wx.EVT_MENU, self.OnPopupFour, id=self.popupID4) # make a menu menu = wx.Menu() # add some items menu.Append(self.popupID1, 'Let Me Go') menu.Append(self.popupID2,"Free All Fish" ) menu.Append(self.popupID3, "Set Bobber Debth" ) menu.Append(self.popupID4,"Clear All and repopulate") # Popup the menu. If an item is selected then its handler # will be called before PopupMenu returns. self.PopupMenu(menu, (self.x, self.y)) menu.Destroy() # << class LinkListCtrlPanel methods >> (17 of 21) def OnPopupOne(self, event): self.parent.LetFishGow(self.parent) # << class LinkListCtrlPanel methods >> (18 of 21) def OnPopupTwo(self, event): self.parent.BoberDebthw(self.parent) # << class LinkListCtrlPanel methods >> (19 of 21) def OnPopupThree(self, event): self.parent.BoberDebthw(self.parent) # << class LinkListCtrlPanel methods >> (20 of 21) def OnPopupFour(self, event): self.parent.PopulateListw(self.parent) # << class LinkListCtrlPanel methods >> (21 of 21) def OnSize(self, event): w,h = self.GetClientSizeTuple() self.list.SetDimensions(0, 0, w, h) # -- end -- << class LinkListCtrlPanel methods >> # << TomBrowse methods >> (6 of 11) class PyHtmlWindow(html.HtmlWindow): # << class PyHtmlWindow methods >> (1 of 2) def __init__(self, parent, id,reltedframe): html.HtmlWindow.__init__(self, parent, id, style=wx.NO_FULL_REPAINT_ON_RESIZE) self.parent = parent self.reltedframe = reltedframe self.address = '' if "gtk2" in wx.PlatformInfo: self.NormalizeFontSizes() # << class PyHtmlWindow methods >> (2 of 2) def OnLinkClicked(self, linkinfo): self.reltedframe.WebObjects = {} url = linkinfo.GetHref() self.address = url self.parent.LoadURL(url) # -- end -- << class PyHtmlWindow methods >> # << TomBrowse methods >> (7 of 11) class WebObject: # << class WebObject methods >> def __init__(self,val): # Val = [ formname,formurl,objname,data,objtyp,self.id,win] self.URL = val[1].strip() self.FormData = {} attrblist = val[0].split(',') for i in attrblist: try: self.FormData[i[0]] = i[1] except: pass self.Name = val[2].strip() #print '*%s*'%(self.Name) #if val[2] in ('text','file','password','isindex','select','int_text','int_file','int_password','int_isindex','int_select'): # self.Value = '"%s"'%( val[3]) #else: self.Value = val[3] if val[3] == True: self.WebValue = u'&%s=%s'%(self.Name,'on') elif val[3] == False: self.WebValue = u'&%s=%s'%(self.Name,'off') else: self.WebValue = u'&%s=%s'%(self.Name,val[3].strip()) self.Value = val[3].strip() self.Typ = val[4].strip() self.Id = val[5] self.Win = val[6] #print '-%s-'%(self.Typ) # -- end -- << class WebObject methods >> # << TomBrowse methods >> (8 of 11) class PythonSTC(StyledTextCtrl): # << class PythonSTC methods >> (1 of 6) def __init__(self, parent, ID): StyledTextCtrl.__init__(self, parent, ID, style = wx.NO_FULL_REPAINT_ON_RESIZE) self.CmdKeyAssign(ord('B'), STC_SCMOD_CTRL, STC_CMD_ZOOMIN) self.CmdKeyAssign(ord('N'), STC_SCMOD_CTRL, STC_CMD_ZOOMOUT) self.SetLexer(STC_LEX_PYTHON) self.SetKeyWords(0, string.join(keyword.kwlist)) self.SetProperty("fold", "1") self.SetProperty("tab.timmy.whinge.level", "1") self.SetMargins(0,0) self.SetViewWhiteSpace(False) #self.SetBufferedDraw(False) self.SetEdgeMode(STC_EDGE_BACKGROUND) self.SetEdgeColumn(200) # Setup a margin to hold fold markers #self.SetFoldFlags(16) ### WHAT IS THIS VALUE? WHAT ARE THE OTHER FLAGS? DOES IT MATTER? self.SetMarginType(2, STC_MARGIN_SYMBOL) self.SetMarginMask(2, STC_MASK_FOLDERS) self.SetMarginSensitive(2, True) self.SetMarginWidth(2, 12) if 0: # simple folder marks, like the old version self.MarkerDefine(STC_MARKNUM_FOLDER, STC_MARK_ARROW, "navy", "navy") self.MarkerDefine(STC_MARKNUM_FOLDEROPEN, STC_MARK_ARROWDOWN, "navy", "navy") # Set these to an invisible mark self.MarkerDefine(STC_MARKNUM_FOLDEROPENMID, STC_MARK_BACKGROUND, "white", "black") self.MarkerDefine(STC_MARKNUM_FOLDERMIDTAIL, STC_MARK_BACKGROUND, "white", "black") self.MarkerDefine(STC_MARKNUM_FOLDERSUB, STC_MARK_BACKGROUND, "white", "black") self.MarkerDefine(STC_MARKNUM_FOLDERTAIL, STC_MARK_BACKGROUND, "white", "black") else: # more involved "outlining" folder marks self.MarkerDefine(STC_MARKNUM_FOLDEREND, STC_MARK_BOXPLUSCONNECTED, "white", "black") self.MarkerDefine(STC_MARKNUM_FOLDEROPENMID, STC_MARK_BOXMINUSCONNECTED, "white", "black") self.MarkerDefine(STC_MARKNUM_FOLDERMIDTAIL, STC_MARK_TCORNER, "white", "black") self.MarkerDefine(STC_MARKNUM_FOLDERTAIL, STC_MARK_LCORNER, "white", "black") self.MarkerDefine(STC_MARKNUM_FOLDERSUB, STC_MARK_VLINE, "white", "black") self.MarkerDefine(STC_MARKNUM_FOLDER, STC_MARK_BOXPLUS, "white", "black") self.MarkerDefine(STC_MARKNUM_FOLDEROPEN, STC_MARK_BOXMINUS, "white", "black") EVT_STC_UPDATEUI(self, ID, self.OnUpdateUI) EVT_STC_MARGINCLICK(self, ID, self.OnMarginClick) # Make some styles, The lexer defines what each style is used for, we # just have to define what each style looks like. This set is adapted from # Scintilla sample property files. self.StyleClearAll() # Global default styles for all languages self.StyleSetSpec(STC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % faces) self.StyleSetSpec(STC_STYLE_LINENUMBER, "back:#C0C0C0,face:%(helv)s,size:%(size2)d" % faces) self.StyleSetSpec(STC_STYLE_CONTROLCHAR, "face:%(other)s" % faces) self.StyleSetSpec(STC_STYLE_BRACELIGHT, "fore:#FFFFFF,back:#0000FF,bold") self.StyleSetSpec(STC_STYLE_BRACEBAD, "fore:#000000,back:#FF0000,bold") # Python styles # White space self.StyleSetSpec(STC_P_DEFAULT, "fore:#808080,face:%(helv)s,size:%(size)d" % faces) # Comment self.StyleSetSpec(STC_P_COMMENTLINE, "fore:#007F00,face:%(other)s,size:%(size)d" % faces) # Number self.StyleSetSpec(STC_P_NUMBER, "fore:#007F7F,size:%(size)d" % faces) # String self.StyleSetSpec(STC_P_STRING, "fore:#7F007F,italic,face:%(times)s,size:%(size)d" % faces) # Single quoted string self.StyleSetSpec(STC_P_CHARACTER, "fore:#7F007F,italic,face:%(times)s,size:%(size)d" % faces) # Keyword self.StyleSetSpec(STC_P_WORD, "fore:#00007F,bold,size:%(size)d" % faces) # Triple quotes self.StyleSetSpec(STC_P_TRIPLE, "fore:#7F0000,size:%(size)d" % faces) # Triple double quotes self.StyleSetSpec(STC_P_TRIPLEDOUBLE, "fore:#7F0000,size:%(size)d" % faces) # Class name definition self.StyleSetSpec(STC_P_CLASSNAME, "fore:#0000FF,bold,underline,size:%(size)d" % faces) # Function or method name definition self.StyleSetSpec(STC_P_DEFNAME, "fore:#007F7F,bold,size:%(size)d" % faces) # Operators self.StyleSetSpec(STC_P_OPERATOR, "bold,size:%(size)d" % faces) # Identifiers self.StyleSetSpec(STC_P_IDENTIFIER, "fore:#808080,face:%(helv)s,size:%(size)d" % faces) # Comment-blocks self.StyleSetSpec(STC_P_COMMENTBLOCK, "fore:#7F7F7F,size:%(size)d" % faces) # End of line where string is not closed self.StyleSetSpec(STC_P_STRINGEOL, "fore:#000000,face:%(mono)s,back:#E0C0E0,eol,size:%(size)d" % faces) self.SetCaretForeground("BLUE") #wx.EVT_KEY_DOWN(self, self.OnKeyPressed) # << class PythonSTC methods >> (2 of 6) def OnUpdateUI(self, evt): # check for matching braces braceAtCaret = -1 braceOpposite = -1 charBefore = None caretPos = self.GetCurrentPos() if caretPos > 0: charBefore = self.GetCharAt(caretPos - 1) styleBefore = self.GetStyleAt(caretPos - 1) # check before if charBefore and chr(charBefore) in "[]{}()" and styleBefore == STC_P_OPERATOR: braceAtCaret = caretPos - 1 # check after if braceAtCaret < 0: charAfter = self.GetCharAt(caretPos) styleAfter = self.GetStyleAt(caretPos) if charAfter and chr(charAfter) in "[]{}()" and styleAfter == STC_P_OPERATOR: braceAtCaret = caretPos if braceAtCaret >= 0: braceOpposite = self.BraceMatch(braceAtCaret) if braceAtCaret != -1 and braceOpposite == -1: self.BraceBadLight(braceAtCaret) else: self.BraceHighlight(braceAtCaret, braceOpposite) #pt = self.PointFromPosition(braceOpposite) #self.Refresh(True, wx.Rect(pt.x, pt.y, 5,5)) #print pt #self.Refresh(False) # << class PythonSTC methods >> (3 of 6) def OnMarginClick(self, evt): # fold and unfold as needed if evt.GetMargin() == 2: if evt.GetShift() and evt.GetControl(): self.FoldAll() else: lineClicked = self.LineFromPosition(evt.GetPosition()) if self.GetFoldLevel(lineClicked) & STC_FOLDLEVELHEADERFLAG: if evt.GetShift(): self.SetFoldExpanded(lineClicked, True) self.Expand(lineClicked, True, True, 1) elif evt.GetControl(): if self.GetFoldExpanded(lineClicked): self.SetFoldExpanded(lineClicked, False) self.Expand(lineClicked, False, True, 0) else: self.SetFoldExpanded(lineClicked, True) self.Expand(lineClicked, True, True, 100) else: self.ToggleFold(lineClicked) # << class PythonSTC methods >> (4 of 6) def FoldAll(self): lineCount = self.GetLineCount() expanding = True # find out if we are folding or unfolding for lineNum in range(lineCount): if self.GetFoldLevel(lineNum) & STC_FOLDLEVELHEADERFLAG: expanding = not self.GetFoldExpanded(lineNum) break; lineNum = 0 while lineNum < lineCount: level = self.GetFoldLevel(lineNum) if level & STC_FOLDLEVELHEADERFLAG and \ (level & STC_FOLDLEVELNUMBERMASK) == STC_FOLDLEVELBASE: if expanding: self.SetFoldExpanded(lineNum, True) lineNum = self.Expand(lineNum, True) lineNum = lineNum - 1 else: lastChild = self.GetLastChild(lineNum, -1) self.SetFoldExpanded(lineNum, False) if lastChild > lineNum: self.HideLines(lineNum+1, lastChild) lineNum = lineNum + 1 # << class PythonSTC methods >> (5 of 6) def Expand(self, line, doExpand, force=False, visLevels=0, level=-1): lastChild = self.GetLastChild(line, level) line = line + 1 while line <= lastChild: if force: if visLevels > 0: self.ShowLines(line, line) else: self.HideLines(line, line) else: if doExpand: self.ShowLines(line, line) if level == -1: level = self.GetFoldLevel(line) if level & STC_FOLDLEVELHEADERFLAG: if force: if visLevels > 1: self.SetFoldExpanded(line, True) else: self.SetFoldExpanded(line, False) line = self.Expand(line, doExpand, force, visLevels-1) else: if doExpand and self.GetFoldExpanded(line): line = self.Expand(line, True, force, visLevels-1) else: line = self.Expand(line, False, force, visLevels-1) else: line = line + 1; return line # << class PythonSTC methods >> (6 of 6) def SetValue(self, text): self.SetText(text) # -- end -- << class PythonSTC methods >> # << TomBrowse methods >> (9 of 11) class HtmlPanel(wx.Panel): # << class HtmlPanel methods >> (1 of 12) def __init__(self, parent,reltedframe): wx.Panel.__init__(self, parent, -1, style=wx.NO_FULL_REPAINT_ON_RESIZE) self.rframe = reltedframe self.cwd = os.path.split(sys.argv[0])[0] if not self.cwd: self.cwd = os.getcwd() self.titleBase = parent.GetTitle() self.TomFilter = HTMLparse.TomFilter() self.html = PyHtmlWindow(self, -1,reltedframe) self.html.SetRelatedFrame(reltedframe, self.titleBase + "%s") self.html.SetRelatedStatusBar(0) self.printer = html.HtmlEasyPrinting() self.box = wx.BoxSizer(wx.VERTICAL) self.box.Add(self.html, 1, wx.GROW) subbox = wx.BoxSizer(wx.HORIZONTAL) btn = wx.Button(self, -1, "Load File") self.Bind(wx.EVT_BUTTON, self.OnLoadFile, btn) subbox.Add(btn, 1, wx.GROW | wx.ALL, 2) btn = wx.Button(self, -1, "Load URL") self.Bind(wx.EVT_BUTTON, self.OnLoadURL, btn) subbox.Add(btn, 1, wx.GROW | wx.ALL, 2) self.webhistory =wx.ComboBox( self, -1, '', (-1, -1),(-1, -1), [], wx.CB_DROPDOWN |wx.TE_PROCESS_ENTER) self.webhistory .SetValue('http://') self.Bind(wx.EVT_TEXT_ENTER, self.surf, self.webhistory) subbox.Add(self.webhistory, 10, wx.EXPAND| wx.ALL, 2) btn = wx.Button(self, -1, "Print") self.Bind(wx.EVT_BUTTON, self.OnPrint, btn) subbox.Add(btn, 1, wx.GROW | wx.ALL, 2) btn = wx.Button(self, -1, "View Source") self.Bind(wx.EVT_BUTTON, self.OnViewSource, btn) subbox.Add(btn, 1, wx.GROW | wx.ALL, 2) self.box.Add(subbox, 0, wx.GROW) self.SetSizer(self.box) self.SetAutoLayout(True) # A button with this ID is created on the widget test page. self.Bind(wx.EVT_BUTTON, self.OnOk, id=wx.ID_OK) self.OnShowDefault(None) # << class HtmlPanel methods >> (2 of 12) def OnShowDefault(self, event): #name = os.path.join(self.cwd, opj('data/test.htm')) #self.html.LoadPage('c:\\RBRanch\\out\\rbranch_strangness4.htm') pass # << class HtmlPanel methods >> (3 of 12) def OnLoadFile(self, event): dlg = wx.FileDialog(self, wildcard = '*.htm*', style=wx.OPEN) if dlg.ShowModal(): path = dlg.GetPath() self.html.LoadPage(path) dlg.Destroy() # << class HtmlPanel methods >> (4 of 12) def OnLoadURL(self, event): dlg = wx.TextEntryDialog(self, "Enter a URL") if dlg.ShowModal(): url = dlg.GetValue() self.LoadURL(url) dlg.Destroy() # << class HtmlPanel methods >> (5 of 12) def surf(self, event): url = event.GetString() self.LoadURL(url) # << class HtmlPanel methods >> (6 of 12) def LoadURL(self, url): #self.rframe.WebObjects = {} webtext = '' try: webtext = urllib2.urlopen(url).read() except: for i in sys.exc_info(): self.rframe.shelllog.SetValue(self.rframe.shelllog.GetValue() + str(i).decode('ascii','replace')+ '\n') self.LoadText(webtext,url) #formtxt = self.TomFilter.formfilter(webtext,url) #wx.SafeYield() #self.rframe.RefreshLinks(self.TomFilter.linklist ,self.TomFilter.linktextlist) #self.rframe.DrawBack(self.TomFilter.backgroundcolor,self.TomFilter.background) #try: # self.rframe.text_thing.SetValue(html2text(webtext).decode('ascii','replace')) #except: # self.rframe.text_thing.SetValue(html2text(webtext)) #self.rframe.scriptshell.SetValue(self.TomFilter.scripttext) #self.html.address = url #self.webhistory.Append(url) #self.html.SetPage(formtxt) #if self.rframe.image_check.GetValue() == True: # self.rframe.glob_thing2.Refresh() # for i in self.TomFilter.imagelist: # self.rframe.glob_thing2.UrlAdd(i) # << class HtmlPanel methods >> (7 of 12) def LoadText(self,webtext,url): self.rframe.WebObjects = {} formtxt = self.TomFilter.formfilter(webtext,url) #wx.SafeYield() self.rframe.RefreshLinks(self.TomFilter.linklist ,self.TomFilter.linktextlist) self.rframe.DrawBack(self.TomFilter.backgroundcolor,self.TomFilter.background) try: self.rframe.text_thing.SetValue(html2text(webtext).decode('ascii','replace')) except: self.rframe.text_thing.SetValue(html2text(webtext)) self.rframe.scriptshell.SetValue(self.TomFilter.scripttext) self.html.address = url self.webhistory.Append(url) self.html.SetPage(formtxt) if self.rframe.image_check.GetValue() == True: self.rframe.glob_thing2.Refresh() for i in self.TomFilter.imagelist: self.rframe.glob_thing2.UrlAdd(i) # << class HtmlPanel methods >> (8 of 12) def OnOk(self, event): pass # << class HtmlPanel methods >> (9 of 12) def OnBack(self, event): if not self.html.HistoryBack(): wx.MessageBox("No more items in history!") # << class HtmlPanel methods >> (10 of 12) def OnForward(self, event): if not self.html.HistoryForward(): wx.MessageBox("No more items in history!") # << class HtmlPanel methods >> (11 of 12) def OnViewSource(self, event): import wx.lib.dialogs source = self.html.GetParser().GetSource() dlg = wx.lib.dialogs.ScrolledMessageDialog(self, source, 'HTML Source') dlg.ShowModal() dlg.Destroy() # << class HtmlPanel methods >> (12 of 12) def OnPrint(self, event): self.printer.GetPrintData().SetPaperId(wx.PAPER_LETTER) self.printer.PrintFile(self.html.GetOpenedPage()) # -- end -- << class HtmlPanel methods >> # << TomBrowse methods >> (10 of 11) class PyFrame(wx.Frame): # << class PyFrame methods >> (1 of 5) def __init__(self, parent, id, title): self.thebackground = None wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.DefaultSize) self.WebEvent = [] wx.EVT_CLOSE(self, self.OnCloseWindow) self.Bind(webwig.EVT_UPDATE_WEBFORM, self.OnPyEvent) self.status = wx.StatusBar(self, -1) self.SetStatusBar(self.status) self.WebObjects = {} self.WebCodeDictionary = {} self.notebook = wx.Notebook(self, -1) self.glob_thing = HtmlPanel(self.notebook,self) self.notebook.AddPage(self.glob_thing, "Web") self.textpanel = wx.Panel(self.notebook,-1) self.text_thing = wx.TextCtrl(self.textpanel, -1,'', style=wx.TE_MULTILINE) txtbox = wx.BoxSizer(wx.HORIZONTAL) txtbox.Add(self.text_thing, 2, wx.EXPAND) self.textpanel.SetSizer(txtbox) self.textpanel.SetAutoLayout(1) txtbox.Fit(self.textpanel) self.notebook.AddPage(self.textpanel, "Text") self.imagepanel = wx.Panel(self.notebook,-1) self.glob_thing2 = ImgS(self.imagepanel, -1,self) subbox = wx.BoxSizer(wx.VERTICAL) self.image_check = wx.CheckBox(self.imagepanel, -1, "Download Images", (-1, -1), (-1, -1), wx.NO_BORDER) subbox.Add(self.image_check, 1, wx.EXPAND) subbox.Add(self.glob_thing2, 15, wx.EXPAND) self.imagepanel.SetSizer(subbox) self.imagepanel.SetAutoLayout(1) subbox.Fit(self.imagepanel) self.notebook.AddPage(self.imagepanel, "Images") # self.linkpanel = wx.Panel(self.notebook,-1) self.link_thing = LinkListCtrlPanel(self.linkpanel) txtbox = wx.BoxSizer(wx.HORIZONTAL) txtbox.Add(self.link_thing, 2, wx.EXPAND) self.linkpanel.SetSizer(txtbox) self.linkpanel.SetAutoLayout(1) txtbox.Fit(self.linkpanel) self.notebook.AddPage(self.linkpanel, "Links") # scriptbox = wx.BoxSizer(wx.VERTICAL) self.scriptpanel = wx.Panel(self.notebook,-1) self.scriptshell = PythonSTC(self.scriptpanel, -1) # scriptbox.Add(self.scriptshell, 2, wx.EXPAND ) self.scriptpanel.SetSizer(scriptbox) self.scriptpanel.SetAutoLayout(1) scriptbox.Fit(self.scriptpanel) self.notebook.AddPage(self.scriptpanel, "Scripts") # # # self.shellbook = wx.Notebook(self.notebook, -1) shellbox = wx.BoxSizer(wx.VERTICAL) eventbox = wx.BoxSizer(wx.VERTICAL) logbox = wx.BoxSizer(wx.VERTICAL) self.shellpanel = wx.Panel(self.shellbook,-1) self.shelleventpanel = wx.Panel(self.shellbook,-1) self.shelllogpanel = wx.Panel(self.shellbook,-1) #pyshellpanel = wx.Panel(self.notebook,-1) self.mainshell = py.shell.Shell(self.shellpanel, -1, introText=py.version.VERSION) #self.mainshell.SetValue('app.frame.shelllog.SetValue(app.frame.WebEvent[4])\n') self.webeventshell = PythonSTC(self.shelleventpanel, -1) text= wx.StaticText(self.shelleventpanel, -1, "def OnWebWidgetEvent(WebEvent,WebObjects):") font = wx.Font(18, wx.SWISS, wx.NORMAL, wx.NORMAL) text.SetFont(font) text.SetSize(text.GetBestSize()) eventbox.Add(text, 1, wx.EXPAND ) eventbox.Add(self.webeventshell, 4, wx.EXPAND ) starttext = """urlstr = ''\nurldict = {}\nurltext = ''\nif self.WebEvent.Typ == 'submit':\n for i in self.WebObjects.keys():\n if self.WebObjects[i].Typ not in ('submit','reset','frame'):\n urldict[self.WebObjects[i].Name] = self.WebObjects[i].Value\n try:\n urlstr = urllib.urlencode(urldict)\n urlsite = urllib.urlopen(self.WebEvent.URL,urlstr)\n urltext = urlsite.read()\n urlsite.close()\n self.shelllog.SetValue(self.shelllog.GetValue() + urltext)\n self.glob_thing.LoadText(urltext,self.WebEvent.URL)\n except:\n self.shelllog.SetValue(self.shelllog.GetValue() + repr(sys.exc_info()))""" self.webeventshell.SetValue(starttext)#"""self.shelllog.SetValue(self.shelllog.GetValue() + ' ' + self.WebEvent.Typ)\n""") self.shelllog = wx.TextCtrl(self.shelllogpanel, -1,'', style=wx.TE_MULTILINE) logbox.Add(self.shelllog, 2, wx.EXPAND ) shellbox.Add(self.mainshell, 2, wx.EXPAND ) self.shellpanel.SetSizer(shellbox) self.shellpanel.SetAutoLayout(1) shellbox.Fit(self.shellpanel) self.shelleventpanel.SetSizer(eventbox) self.shelleventpanel.SetAutoLayout(1) eventbox.Fit(self.shelleventpanel) self.shelllogpanel.SetSizer(logbox) self.shelllogpanel.SetAutoLayout(1) logbox.Fit(self.shelllogpanel) self.shellbook.AddPage(self.shelleventpanel,'Event') self.shellbook.AddPage(self.shelllogpanel,'Log') self.shellbook.AddPage(self.shellpanel, 'Shell') self.notebook.AddPage(self.shellbook, "Shell") self.main_sizer = wx.BoxSizer(wx.VERTICAL) self.main_sizer.Add(self.notebook, 1, wx.EXPAND|wx.ALL, 42) self.SetSizer(self.main_sizer) self.SetAutoLayout(1) self.main_sizer.Fit(self) # << class PyFrame methods >> (2 of 5) def OnCloseWindow(self, event): self.Destroy() # << class PyFrame methods >> (3 of 5) def RefreshLinks(self,links,text): self.link_thing.list.ClearAll() self.link_thing.list.InsertColumn(0, 'Link') self.link_thing.list.InsertColumn(1,'Text' , wx.LIST_FORMAT_RIGHT) self.link_thing.list.SetColumnWidth(0, 250) self.link_thing.list.SetColumnWidth(1, 250) for i in range(len(links)): self.link_thing.list.InsertStringItem(0, links[i]) try: self.link_thing.list.SetStringItem( 0,1,text[i]) except: pass # << class PyFrame methods >> (4 of 5) def DrawBack(self,color,source): #print source if source !='': try: fullsize = self.GetClientSizeTuple() imgtxt = urllib2.urlopen(source).read() stream = cStringIO.StringIO(imgtxt) bmp = wx.BitmapFromImage( wx.ImageFromStream( stream )) size = (bmp.GetWidth(), bmp.GetHeight()) fdc = wx.MemoryDC() bmpfull = wx.EmptyBitmap(fullsize[0], fullsize[1]) fdc.SelectObject(bmpfull) mdc = wx.MemoryDC() mdc.SelectObject(bmp) dc = wx.ClientDC(self) for j in range(0,fullsize[0],size[0]): for i in range(0,fullsize[1],size[1]): fdc.BlitPointSize( wx.Point(j,i), wx.Size(bmp.GetWidth(), bmp.GetHeight()), mdc, wx.Point(0,0)) del mdc del fdc #wx.SafeYield() dc.BeginDrawing() dc.DrawBitmapPoint(bmpfull, wx.Point(0,0), 0) dc.EndDrawing() del dc except: pass elif color: #print color if color[0] == '#': try: red = int('0x'+color[1:3], 16) green = int('0x'+color[3:5], 16) blue = int('0x'+color[5:], 16) self.SetBackgroundColour(wx.Color(red, green, blue)) self.Refresh() except: self.SetBackgroundColour(wx.Color(255, 255, 255)) # << class PyFrame methods >> (5 of 5) def OnPyEvent(self, event): self.WebEvent = event.GetVal() if self.WebEvent.Typ[:4] == 'int_': if self.WebEvent.Typ == 'int_frame': self.WebEvent.Win.SetRelatedFrame(self, "%s") self.WebEvent.Win.SetRelatedStatusBar(0) self.WebObjects[self.WebEvent.Id] = self.WebEvent self.WebObjects[self.WebEvent.Id].Typ = self.WebObjects[self.WebEvent.Id].Typ[4:] else: self.WebObjects[self.WebEvent.Id] = self.WebEvent if self.WebEvent.Typ=='frame': if self.WebEvent.Data in ('_top','_parent','_blank'): self.glob_thing.LoadURL(self.WebEvent.URL) elif self.WebEvent.Data != u'': for i in self.WebObjects.keys(): if self.WebObjects[i].Typ == 'frame' and self.WebObjects[i].Name == self.WebEvent.Data: self.WebObjects[i].Win.parent.LoadURL(self.WebEvent.URL) else: #self.WebObjects[tempobj[5]] = WebObject(tempobj) txt = self.webeventshell.GetText() newtxt = '' for i in txt: if ord(i) == 13:#self.webeventshell.GetText() newtxt = newtxt + ' ' else: newtxt = newtxt + i try: exec(newtxt) except: #output to self.shelllog for i in sys.exc_info(): self.shelllog.SetValue(self.shelllog.GetValue() + str(i)+ '\n') self.WebCodeDictionary[self.glob_thing.html.address] = newtxt # -- end -- << class PyFrame methods >> # << TomBrowse methods >> (11 of 11) class PyApp(wx.App): # << class PyApp methods >> def OnInit(self): # Create an instance of our customized Frame class frame = PyFrame(None, -1, "Web") frame.Show(True) # Tell wx.Windows that this is our main window self.SetTopWindow(frame) # Return a success flag return True # -- end -- << class PyApp methods >> # -- end -- << TomBrowse methods >> app = PyApp(0) # Create an instance of the application class app.MainLoop() # Tell it to start processing events