From f83ca04634f654130452aa8a6f091c531c1b096a Mon Sep 17 00:00:00 2001 From: Robin Dunn Date: Wed, 15 Jan 2003 23:07:21 +0000 Subject: [PATCH] Removed TABs git-svn-id: https://svn.wxwidgets.org/svn/wx/wxWidgets/branches/WX_2_4_BRANCH@18755 c3d73ce0-8a6f-49c7-b76d-6d57e0e08775 --- wxPython/demo/Sizers.py | 12 +- wxPython/demo/SlashDot.py | 122 +- wxPython/demo/wxListCtrl.py | 1 + wxPython/demo/wxStyledTextCtrl_2.py | 4 +- wxPython/demo/wxTextCtrl.py | 11 + wxPython/my_distutils.py | 6 +- wxPython/samples/pySketch/pySketch.py | 3464 ++++++++++++------------- wxPython/scripts/CreateBatchFiles.py | 2 +- wxPython/scripts/CreateMacScripts.py | 2 +- wxPython/src/_extras.py | 2 +- wxPython/src/wx.i | 1 + wxPython/tests/hangman.py | 616 ++--- wxPython/tests/test7.py | 19 +- wxPython/tests/test8.py | 58 +- wxPython/tests/testDlg.py | 44 +- wxPython/tests/testTree.py | 170 +- wxPython/tests/wxPlotCanvas.py | 514 ++-- wxPython/tests/wxSlash.py | 126 +- wxPython/wxPython/lib/CDate.py | 10 +- wxPython/wxPython/lib/grids.py | 4 +- wxPython/wxPython/lib/imagebrowser.py | 66 +- wxPython/wxPython/lib/printout.py | 2 +- wxPython/wxPython/lib/pyshell.py | 2 +- wxPython/wxPython/lib/vtk.py | 4 +- wxPython/wxPython/lib/wxpTag.py | 42 +- 25 files changed, 2665 insertions(+), 2639 deletions(-) diff --git a/wxPython/demo/Sizers.py b/wxPython/demo/Sizers.py index 8278bd0db4..fdbbb5a25c 100644 --- a/wxPython/demo/Sizers.py +++ b/wxPython/demo/Sizers.py @@ -555,12 +555,12 @@ if __name__ == '__main__': def __init__(self): wxFrame.__init__(self, None, -1, "Testing...") - self.CreateStatusBar() - mainmenu = wxMenuBar() - menu = wxMenu() - menu.Append(200, 'E&xit', 'Get the heck outta here!') - mainmenu.Append(menu, "&File") - self.SetMenuBar(mainmenu) + self.CreateStatusBar() + mainmenu = wxMenuBar() + menu = wxMenu() + menu.Append(200, 'E&xit', 'Get the heck outta here!') + mainmenu.Append(menu, "&File") + self.SetMenuBar(mainmenu) EVT_MENU(self, 200, self.OnExit) self.panel = TestSelectionPanel(self, self) self.SetSize(wxSize(400, 380)) diff --git a/wxPython/demo/SlashDot.py b/wxPython/demo/SlashDot.py index 03fc98011f..b6eb280f0c 100644 --- a/wxPython/demo/SlashDot.py +++ b/wxPython/demo/SlashDot.py @@ -170,22 +170,22 @@ class AppStatusBar(wxStatusBar): # This is a simple timer class to start a function after a short delay; class QuickTimer(wxTimer): def __init__(self, func, wait=100): - wxTimer.__init__(self) - self.callback = func - self.Start(wait); # wait .1 second (.001 second doesn't work. why?) + wxTimer.__init__(self) + self.callback = func + self.Start(wait); # wait .1 second (.001 second doesn't work. why?) def Notify(self): - self.Stop(); - apply(self.callback, ()); + self.Stop(); + apply(self.callback, ()); class AppFrame(wxFrame): def __init__(self, parent, id, title): wxFrame.__init__(self, parent, id, title, wxPyDefaultPosition, wxSize(650, 250)) - # if the window manager closes the window: - EVT_CLOSE(self, self.OnCloseWindow); + # if the window manager closes the window: + EVT_CLOSE(self, self.OnCloseWindow); - # Now Create the menu bar and items + # Now Create the menu bar and items self.mainmenu = wxMenuBar() menu = wxMenu() @@ -208,45 +208,45 @@ class AppFrame(wxFrame): menu.Append(222, '&Settings...', 'External browser Settings') EVT_MENU(self, 222, self.OnBrowserSettings) self.mainmenu.Append(menu, '&Browser') - menu = wxMenu() - menu.Append(230, '&About', 'Some documentation'); - EVT_MENU(self, 230, self.OnAbout) - self.mainmenu.Append(menu, '&Help') + menu = wxMenu() + menu.Append(230, '&About', 'Some documentation'); + EVT_MENU(self, 230, self.OnAbout) + self.mainmenu.Append(menu, '&Help') self.SetMenuBar(self.mainmenu) - if wxPlatform == '__WXGTK__': - # I like lynx. Also Netscape 4.5 doesn't react to my cmdline opts - self.BrowserSettings = "xterm -e lynx %s &" - elif wxPlatform == '__WXMSW__': - # netscape 4.x likes to hang out here... - self.BrowserSettings = '\\progra~1\\Netscape\\Communicator\\Program\\netscape.exe %s' - else: - # a wild guess... - self.BrowserSettings = 'netscape %s' + if wxPlatform == '__WXGTK__': + # I like lynx. Also Netscape 4.5 doesn't react to my cmdline opts + self.BrowserSettings = "xterm -e lynx %s &" + elif wxPlatform == '__WXMSW__': + # netscape 4.x likes to hang out here... + self.BrowserSettings = '\\progra~1\\Netscape\\Communicator\\Program\\netscape.exe %s' + else: + # a wild guess... + self.BrowserSettings = 'netscape %s' - # A status bar to tell people what's happening - self.sb = AppStatusBar(self) + # A status bar to tell people what's happening + self.sb = AppStatusBar(self) self.SetStatusBar(self.sb) self.list = wxListCtrl(self, 1100, style=wxLC_REPORT) - self.list.InsertColumn(0, 'Subject') - self.list.InsertColumn(1, 'Date') - self.list.InsertColumn(2, 'Posted by') - self.list.InsertColumn(3, 'Comments') + self.list.InsertColumn(0, 'Subject') + self.list.InsertColumn(1, 'Date') + self.list.InsertColumn(2, 'Posted by') + self.list.InsertColumn(3, 'Comments') self.list.SetColumnWidth(0, 300) self.list.SetColumnWidth(1, 150) self.list.SetColumnWidth(2, 100) self.list.SetColumnWidth(3, 100) EVT_LIST_ITEM_SELECTED(self, 1100, self.OnItemSelected) - EVT_LEFT_DCLICK(self.list, self.OnLeftDClick) + EVT_LEFT_DCLICK(self.list, self.OnLeftDClick) - self.logprint("Connecting to slashdot... Please wait.") - # wxYield doesn't yet work here. That's why we use a timer - # to make sure that we see some GUI stuff before the slashdot - # file is transfered. - self.timer = QuickTimer(self.DoRefresh, 1000) + self.logprint("Connecting to slashdot... Please wait.") + # wxYield doesn't yet work here. That's why we use a timer + # to make sure that we see some GUI stuff before the slashdot + # file is transfered. + self.timer = QuickTimer(self.DoRefresh, 1000) def logprint(self, x): self.sb.logprint(x) @@ -268,12 +268,12 @@ class AppFrame(wxFrame): self.list.SetStringItem(i, 3, article[6]) self.url.append(article[1]) i = i + 1 - self.logprint("File retrieved OK.") + self.logprint("File retrieved OK.") def OnViewRefresh(self, event): - self.logprint("Connecting to slashdot... Please wait."); - wxYield() - self.DoRefresh() + self.logprint("Connecting to slashdot... Please wait."); + wxYield() + self.DoRefresh() def DoViewIndex(self): if self.UseInternal: @@ -284,12 +284,12 @@ class AppFrame(wxFrame): self.logprint(self.BrowserSettings % ('http://slashdot.org')) #os.system(self.BrowserSettings % ('http://slashdot.org')) wxExecute(self.BrowserSettings % ('http://slashdot.org')) - self.logprint("OK") + self.logprint("OK") def OnViewIndex(self, event): - self.logprint("Starting browser... Please wait.") - wxYield() - self.DoViewIndex() + self.logprint("Starting browser... Please wait.") + wxYield() + self.DoViewIndex() def DoViewArticle(self): if self.current<0: return @@ -300,12 +300,12 @@ class AppFrame(wxFrame): else: self.logprint(self.BrowserSettings % (url)) os.system(self.BrowserSettings % (url)) - self.logprint("OK") + self.logprint("OK") def OnViewArticle(self, event): - self.logprint("Starting browser... Please wait.") - wxYield() - self.DoViewArticle() + self.logprint("Starting browser... Please wait.") + wxYield() + self.DoViewArticle() def OnBrowserInternal(self, event): if self.mainmenu.Checked(220): @@ -319,28 +319,28 @@ class AppFrame(wxFrame): self.BrowserSettings = dlg.GetValue() def OnAbout(self, event): - dlg = wxMessageDialog(self, __doc__, "wxSlash", wxOK | wxICON_INFORMATION) - dlg.ShowModal() + dlg = wxMessageDialog(self, __doc__, "wxSlash", wxOK | wxICON_INFORMATION) + dlg.ShowModal() def OnItemSelected(self, event): self.current = event.m_itemIndex self.logprint("URL: %s" % (self.url[self.current])) def OnLeftDClick(self, event): - (x,y) = event.Position(); - # Actually, we should convert x,y to logical coords using - # a dc, but only for a wxScrolledWindow widget. - # Now wxGTK derives wxListCtrl from wxScrolledWindow, - # and wxMSW from wxControl... So that doesn't work. - #dc = wxClientDC(self.list) - ##self.list.PrepareDC(dc) - #x = dc.DeviceToLogicalX( event.GetX() ) - #y = dc.DeviceToLogicalY( event.GetY() ) - id = self.list.HitTest(wxPoint(x,y)) - #print "Double click at %d %d" % (x,y), id - # Okay, we got a double click. Let's assume it's the current selection - wxYield() - self.OnViewArticle(event) + (x,y) = event.Position(); + # Actually, we should convert x,y to logical coords using + # a dc, but only for a wxScrolledWindow widget. + # Now wxGTK derives wxListCtrl from wxScrolledWindow, + # and wxMSW from wxControl... So that doesn't work. + #dc = wxClientDC(self.list) + ##self.list.PrepareDC(dc) + #x = dc.DeviceToLogicalX( event.GetX() ) + #y = dc.DeviceToLogicalY( event.GetY() ) + id = self.list.HitTest(wxPoint(x,y)) + #print "Double click at %d %d" % (x,y), id + # Okay, we got a double click. Let's assume it's the current selection + wxYield() + self.OnViewArticle(event) def OnCloseWindow(self, event): self.Destroy() diff --git a/wxPython/demo/wxListCtrl.py b/wxPython/demo/wxListCtrl.py index 85d3c97acc..685daac9c1 100644 --- a/wxPython/demo/wxListCtrl.py +++ b/wxPython/demo/wxListCtrl.py @@ -203,6 +203,7 @@ class TestListCtrlPanel(wxPanel, wxColumnSorterMixin): def OnItemSelected(self, event): + print event.GetItem().GetTextColour() self.currentItem = event.m_itemIndex self.log.WriteText("OnItemSelected: %s, %s, %s, %s\n" % (self.currentItem, diff --git a/wxPython/demo/wxStyledTextCtrl_2.py b/wxPython/demo/wxStyledTextCtrl_2.py index 70b9d48b2f..1b0eabb37e 100644 --- a/wxPython/demo/wxStyledTextCtrl_2.py +++ b/wxPython/demo/wxStyledTextCtrl_2.py @@ -175,7 +175,7 @@ class PythonSTC(wxStyledTextCtrl): def OnUpdateUI(self, evt): # check for matching braces braceAtCaret = -1 - braceOpposite = -1 + braceOpposite = -1 charBefore = None caretPos = self.GetCurrentPos() if caretPos > 0: @@ -260,7 +260,7 @@ class PythonSTC(wxStyledTextCtrl): def Expand(self, line, doExpand, force=false, visLevels=0, level=-1): lastChild = self.GetLastChild(line, level) - line = line + 1 + line = line + 1 while line <= lastChild: if force: if visLevels > 0: diff --git a/wxPython/demo/wxTextCtrl.py b/wxPython/demo/wxTextCtrl.py index 369498b8dd..17376fa053 100644 --- a/wxPython/demo/wxTextCtrl.py +++ b/wxPython/demo/wxTextCtrl.py @@ -47,6 +47,9 @@ class TestPanel(wxPanel): b3 = wxButton(self, -1, "Test WriteText") EVT_BUTTON(self, b3.GetId(), self.OnTestWriteText) self.tc = t3 + b4 = wxButton(self, -1, "Test Simulated Event") + EVT_BUTTON(self, b4.GetId(), self.OnTestEvent) + l4 = wxStaticText(self, -1, "Rich Text") t4 = wxTextCtrl(self, -1, "If supported by the native control, this is red, and this is a different font.", @@ -71,6 +74,7 @@ class TestPanel(wxPanel): bsizer.Add(b, 0, wxGROW|wxALL, 4) bsizer.Add(b2, 0, wxGROW|wxALL, 4) bsizer.Add(b3, 0, wxGROW|wxALL, 4) + bsizer.Add(b4, 0, wxGROW|wxALL, 4) sizer = wxFlexGridSizer(cols=3, hgap=6, vgap=6) sizer.AddMany([ l1, t1, (0,0), @@ -129,6 +133,13 @@ class TestPanel(wxPanel): % (ip, text[ip], lp, len(text))) + def OnTestEvent(self, evt): + ke = wxKeyEvent(wxEVT_CHAR) + ke.SetEventObject(self.tc1) + ke.SetId(self.tc1.GetId()) + ke.m_keyCode = ord('A') + self.tc1.GetEventHandler().ProcessEvent(ke) + #--------------------------------------------------------------------------- diff --git a/wxPython/my_distutils.py b/wxPython/my_distutils.py index c19ef541d5..f74e987908 100644 --- a/wxPython/my_distutils.py +++ b/wxPython/my_distutils.py @@ -185,7 +185,7 @@ class MyBCPPCompiler(BCPPCompiler): # This needs to be compiled to a .res file -- do it now. try: self.spawn (["brcc32"] + pp_opts + ["-fo"] + - [obj] + [src]) ### RPD changed this lines only + [obj] + [src]) ### RPD changed this lines only except DistutilsExecError, msg: raise CompileError, msg continue # the 'for' loop @@ -222,7 +222,7 @@ class MyBCPPCompiler(BCPPCompiler): # with cw32mti library as in wxWindows DLL make file # Othervise we obtain Windows "Core dump" ;-). # - # Evgeny A Cherkashin + # Evgeny A Cherkashin # #################################################################### @@ -335,7 +335,7 @@ class MyBCPPCompiler(BCPPCompiler): # some default libraries ld_args.append ('import32') - ld_args.append ('cw32mti') ### mt->mti (as in wx2) + ld_args.append ('cw32mti') ### mt->mti (as in wx2) # def file for export symbols ld_args.extend([',',def_file]) diff --git a/wxPython/samples/pySketch/pySketch.py b/wxPython/samples/pySketch/pySketch.py index 57edf205fd..3e783da5ea 100644 --- a/wxPython/samples/pySketch/pySketch.py +++ b/wxPython/samples/pySketch/pySketch.py @@ -36,11 +36,11 @@ Known Bugs: * Scrolling the window causes the drawing panel to be mucked up until you - refresh it. I've got no idea why. + refresh it. I've got no idea why. * I suspect that the reference counting for some wxPoint objects is getting mucked up; when the user quits, we get errors about being - unable to call del on a 'None' object. + unable to call del on a 'None' object. """ import string, cPickle, os.path from wxPython.wx import * @@ -143,2146 +143,2146 @@ class DrawingFrame(wxFrame): # ========================================== def __init__(self, parent, id, title, fileName=None): - """ Standard constructor. + """ Standard constructor. - 'parent', 'id' and 'title' are all passed to the standard wxFrame - constructor. 'fileName' is the name and path of a saved file to - load into this frame, if any. - """ + 'parent', 'id' and 'title' are all passed to the standard wxFrame + constructor. 'fileName' is the name and path of a saved file to + load into this frame, if any. + """ wxFrame.__init__(self, parent, id, title, - style = wxDEFAULT_FRAME_STYLE | wxWANTS_CHARS | - wxNO_FULL_REPAINT_ON_RESIZE) + style = wxDEFAULT_FRAME_STYLE | wxWANTS_CHARS | + wxNO_FULL_REPAINT_ON_RESIZE) - # Setup our menu bar. + # Setup our menu bar. - menuBar = wxMenuBar() + menuBar = wxMenuBar() - self.fileMenu = wxMenu() - self.fileMenu.Append(wxID_NEW, "New\tCTRL-N") - self.fileMenu.Append(wxID_OPEN, "Open...\tCTRL-O") - self.fileMenu.Append(wxID_CLOSE, "Close\tCTRL-W") - self.fileMenu.AppendSeparator() - self.fileMenu.Append(wxID_SAVE, "Save\tCTRL-S") - self.fileMenu.Append(wxID_SAVEAS, "Save As...") - self.fileMenu.Append(wxID_REVERT, "Revert...") - self.fileMenu.AppendSeparator() - self.fileMenu.Append(wxID_EXIT, "Quit\tCTRL-Q") + self.fileMenu = wxMenu() + self.fileMenu.Append(wxID_NEW, "New\tCTRL-N") + self.fileMenu.Append(wxID_OPEN, "Open...\tCTRL-O") + self.fileMenu.Append(wxID_CLOSE, "Close\tCTRL-W") + self.fileMenu.AppendSeparator() + self.fileMenu.Append(wxID_SAVE, "Save\tCTRL-S") + self.fileMenu.Append(wxID_SAVEAS, "Save As...") + self.fileMenu.Append(wxID_REVERT, "Revert...") + self.fileMenu.AppendSeparator() + self.fileMenu.Append(wxID_EXIT, "Quit\tCTRL-Q") - menuBar.Append(self.fileMenu, "File") + menuBar.Append(self.fileMenu, "File") - self.editMenu = wxMenu() - self.editMenu.Append(menu_UNDO, "Undo\tCTRL-Z") - self.editMenu.AppendSeparator() - self.editMenu.Append(menu_SELECT_ALL, "Select All\tCTRL-A") - self.editMenu.AppendSeparator() - self.editMenu.Append(menu_DUPLICATE, "Duplicate\tCTRL-D") - self.editMenu.Append(menu_EDIT_TEXT, "Edit...\tCTRL-E") - self.editMenu.Append(menu_DELETE, "Delete\tDEL") + self.editMenu = wxMenu() + self.editMenu.Append(menu_UNDO, "Undo\tCTRL-Z") + self.editMenu.AppendSeparator() + self.editMenu.Append(menu_SELECT_ALL, "Select All\tCTRL-A") + self.editMenu.AppendSeparator() + self.editMenu.Append(menu_DUPLICATE, "Duplicate\tCTRL-D") + self.editMenu.Append(menu_EDIT_TEXT, "Edit...\tCTRL-E") + self.editMenu.Append(menu_DELETE, "Delete\tDEL") - menuBar.Append(self.editMenu, "Edit") + menuBar.Append(self.editMenu, "Edit") - self.toolsMenu = wxMenu() - self.toolsMenu.Append(menu_SELECT, "Selection", kind=wxITEM_CHECK) - self.toolsMenu.Append(menu_LINE, "Line", kind=wxITEM_CHECK) - self.toolsMenu.Append(menu_RECT, "Rectangle", kind=wxITEM_CHECK) - self.toolsMenu.Append(menu_ELLIPSE, "Ellipse", kind=wxITEM_CHECK) - self.toolsMenu.Append(menu_TEXT, "Text", kind=wxITEM_CHECK) + self.toolsMenu = wxMenu() + self.toolsMenu.Append(menu_SELECT, "Selection", kind=wxITEM_CHECK) + self.toolsMenu.Append(menu_LINE, "Line", kind=wxITEM_CHECK) + self.toolsMenu.Append(menu_RECT, "Rectangle", kind=wxITEM_CHECK) + self.toolsMenu.Append(menu_ELLIPSE, "Ellipse", kind=wxITEM_CHECK) + self.toolsMenu.Append(menu_TEXT, "Text", kind=wxITEM_CHECK) - menuBar.Append(self.toolsMenu, "Tools") + menuBar.Append(self.toolsMenu, "Tools") - self.objectMenu = wxMenu() - self.objectMenu.Append(menu_MOVE_FORWARD, "Move Forward") - self.objectMenu.Append(menu_MOVE_TO_FRONT, "Move to Front\tCTRL-F") - self.objectMenu.Append(menu_MOVE_BACKWARD, "Move Backward") - self.objectMenu.Append(menu_MOVE_TO_BACK, "Move to Back\tCTRL-B") + self.objectMenu = wxMenu() + self.objectMenu.Append(menu_MOVE_FORWARD, "Move Forward") + self.objectMenu.Append(menu_MOVE_TO_FRONT, "Move to Front\tCTRL-F") + self.objectMenu.Append(menu_MOVE_BACKWARD, "Move Backward") + self.objectMenu.Append(menu_MOVE_TO_BACK, "Move to Back\tCTRL-B") - menuBar.Append(self.objectMenu, "Object") + menuBar.Append(self.objectMenu, "Object") - self.helpMenu = wxMenu() - self.helpMenu.Append(menu_ABOUT, "About pySketch...") + self.helpMenu = wxMenu() + self.helpMenu.Append(menu_ABOUT, "About pySketch...") - menuBar.Append(self.helpMenu, "Help") + menuBar.Append(self.helpMenu, "Help") - self.SetMenuBar(menuBar) + self.SetMenuBar(menuBar) - # Create our toolbar. + # Create our toolbar. - self.toolbar = self.CreateToolBar(wxTB_HORIZONTAL | - wxNO_BORDER | wxTB_FLAT) + self.toolbar = self.CreateToolBar(wxTB_HORIZONTAL | + wxNO_BORDER | wxTB_FLAT) - self.toolbar.AddSimpleTool(wxID_NEW, - wxBitmap("images/new.bmp", - wxBITMAP_TYPE_BMP), - "New") - self.toolbar.AddSimpleTool(wxID_OPEN, - wxBitmap("images/open.bmp", - wxBITMAP_TYPE_BMP), - "Open") - self.toolbar.AddSimpleTool(wxID_SAVE, - wxBitmap("images/save.bmp", - wxBITMAP_TYPE_BMP), - "Save") - self.toolbar.AddSeparator() - self.toolbar.AddSimpleTool(menu_UNDO, - wxBitmap("images/undo.bmp", - wxBITMAP_TYPE_BMP), - "Undo") - self.toolbar.AddSeparator() - self.toolbar.AddSimpleTool(menu_DUPLICATE, - wxBitmap("images/duplicate.bmp", - wxBITMAP_TYPE_BMP), - "Duplicate") - self.toolbar.AddSeparator() - self.toolbar.AddSimpleTool(menu_MOVE_FORWARD, - wxBitmap("images/moveForward.bmp", - wxBITMAP_TYPE_BMP), - "Move Forward") - self.toolbar.AddSimpleTool(menu_MOVE_BACKWARD, - wxBitmap("images/moveBack.bmp", - wxBITMAP_TYPE_BMP), - "Move Backward") + self.toolbar.AddSimpleTool(wxID_NEW, + wxBitmap("images/new.bmp", + wxBITMAP_TYPE_BMP), + "New") + self.toolbar.AddSimpleTool(wxID_OPEN, + wxBitmap("images/open.bmp", + wxBITMAP_TYPE_BMP), + "Open") + self.toolbar.AddSimpleTool(wxID_SAVE, + wxBitmap("images/save.bmp", + wxBITMAP_TYPE_BMP), + "Save") + self.toolbar.AddSeparator() + self.toolbar.AddSimpleTool(menu_UNDO, + wxBitmap("images/undo.bmp", + wxBITMAP_TYPE_BMP), + "Undo") + self.toolbar.AddSeparator() + self.toolbar.AddSimpleTool(menu_DUPLICATE, + wxBitmap("images/duplicate.bmp", + wxBITMAP_TYPE_BMP), + "Duplicate") + self.toolbar.AddSeparator() + self.toolbar.AddSimpleTool(menu_MOVE_FORWARD, + wxBitmap("images/moveForward.bmp", + wxBITMAP_TYPE_BMP), + "Move Forward") + self.toolbar.AddSimpleTool(menu_MOVE_BACKWARD, + wxBitmap("images/moveBack.bmp", + wxBITMAP_TYPE_BMP), + "Move Backward") - self.toolbar.Realize() + self.toolbar.Realize() - # Associate each menu/toolbar item with the method that handles that - # item. + # Associate each menu/toolbar item with the method that handles that + # item. - EVT_MENU(self, wxID_NEW, self.doNew) - EVT_MENU(self, wxID_OPEN, self.doOpen) - EVT_MENU(self, wxID_CLOSE, self.doClose) - EVT_MENU(self, wxID_SAVE, self.doSave) - EVT_MENU(self, wxID_SAVEAS, self.doSaveAs) - EVT_MENU(self, wxID_REVERT, self.doRevert) - EVT_MENU(self, wxID_EXIT, self.doExit) + EVT_MENU(self, wxID_NEW, self.doNew) + EVT_MENU(self, wxID_OPEN, self.doOpen) + EVT_MENU(self, wxID_CLOSE, self.doClose) + EVT_MENU(self, wxID_SAVE, self.doSave) + EVT_MENU(self, wxID_SAVEAS, self.doSaveAs) + EVT_MENU(self, wxID_REVERT, self.doRevert) + EVT_MENU(self, wxID_EXIT, self.doExit) - EVT_MENU(self, menu_UNDO, self.doUndo) - EVT_MENU(self, menu_SELECT_ALL, self.doSelectAll) - EVT_MENU(self, menu_DUPLICATE, self.doDuplicate) - EVT_MENU(self, menu_EDIT_TEXT, self.doEditText) - EVT_MENU(self, menu_DELETE, self.doDelete) + EVT_MENU(self, menu_UNDO, self.doUndo) + EVT_MENU(self, menu_SELECT_ALL, self.doSelectAll) + EVT_MENU(self, menu_DUPLICATE, self.doDuplicate) + EVT_MENU(self, menu_EDIT_TEXT, self.doEditText) + EVT_MENU(self, menu_DELETE, self.doDelete) - EVT_MENU(self, menu_SELECT, self.doChooseSelectTool) - EVT_MENU(self, menu_LINE, self.doChooseLineTool) - EVT_MENU(self, menu_RECT, self.doChooseRectTool) - EVT_MENU(self, menu_ELLIPSE, self.doChooseEllipseTool) - EVT_MENU(self, menu_TEXT, self.doChooseTextTool) + EVT_MENU(self, menu_SELECT, self.doChooseSelectTool) + EVT_MENU(self, menu_LINE, self.doChooseLineTool) + EVT_MENU(self, menu_RECT, self.doChooseRectTool) + EVT_MENU(self, menu_ELLIPSE, self.doChooseEllipseTool) + EVT_MENU(self, menu_TEXT, self.doChooseTextTool) - EVT_MENU(self, menu_MOVE_FORWARD, self.doMoveForward) - EVT_MENU(self, menu_MOVE_TO_FRONT, self.doMoveToFront) - EVT_MENU(self, menu_MOVE_BACKWARD, self.doMoveBackward) - EVT_MENU(self, menu_MOVE_TO_BACK, self.doMoveToBack) + EVT_MENU(self, menu_MOVE_FORWARD, self.doMoveForward) + EVT_MENU(self, menu_MOVE_TO_FRONT, self.doMoveToFront) + EVT_MENU(self, menu_MOVE_BACKWARD, self.doMoveBackward) + EVT_MENU(self, menu_MOVE_TO_BACK, self.doMoveToBack) - EVT_MENU(self, menu_ABOUT, self.doShowAbout) + EVT_MENU(self, menu_ABOUT, self.doShowAbout) - # Install our own method to handle closing the window. This allows us - # to ask the user if he/she wants to save before closing the window, as - # well as keeping track of which windows are currently open. + # Install our own method to handle closing the window. This allows us + # to ask the user if he/she wants to save before closing the window, as + # well as keeping track of which windows are currently open. - EVT_CLOSE(self, self.doClose) + EVT_CLOSE(self, self.doClose) - # Install our own method for handling keystrokes. We use this to let - # the user move the selected object(s) around using the arrow keys. + # Install our own method for handling keystrokes. We use this to let + # the user move the selected object(s) around using the arrow keys. - EVT_CHAR_HOOK(self, self.onKeyEvent) + EVT_CHAR_HOOK(self, self.onKeyEvent) - # Setup our top-most panel. This holds the entire contents of the - # window, excluding the menu bar. + # Setup our top-most panel. This holds the entire contents of the + # window, excluding the menu bar. - self.topPanel = wxPanel(self, -1, style=wxSIMPLE_BORDER) + self.topPanel = wxPanel(self, -1, style=wxSIMPLE_BORDER) - # Setup our tool palette, with all our drawing tools and option icons. + # Setup our tool palette, with all our drawing tools and option icons. - self.toolPalette = wxBoxSizer(wxVERTICAL) + self.toolPalette = wxBoxSizer(wxVERTICAL) - self.selectIcon = ToolPaletteIcon(self.topPanel, id_SELECT, - "select", "Selection Tool") - self.lineIcon = ToolPaletteIcon(self.topPanel, id_LINE, - "line", "Line Tool") - self.rectIcon = ToolPaletteIcon(self.topPanel, id_RECT, - "rect", "Rectangle Tool") - self.ellipseIcon = ToolPaletteIcon(self.topPanel, id_ELLIPSE, - "ellipse", "Ellipse Tool") - self.textIcon = ToolPaletteIcon(self.topPanel, id_TEXT, - "text", "Text Tool") + self.selectIcon = ToolPaletteIcon(self.topPanel, id_SELECT, + "select", "Selection Tool") + self.lineIcon = ToolPaletteIcon(self.topPanel, id_LINE, + "line", "Line Tool") + self.rectIcon = ToolPaletteIcon(self.topPanel, id_RECT, + "rect", "Rectangle Tool") + self.ellipseIcon = ToolPaletteIcon(self.topPanel, id_ELLIPSE, + "ellipse", "Ellipse Tool") + self.textIcon = ToolPaletteIcon(self.topPanel, id_TEXT, + "text", "Text Tool") - toolSizer = wxGridSizer(0, 2, 5, 5) - toolSizer.Add(self.selectIcon) - toolSizer.Add(0, 0) # Gap to make tool icons line up nicely. - toolSizer.Add(self.lineIcon) - toolSizer.Add(self.rectIcon) - toolSizer.Add(self.ellipseIcon) - toolSizer.Add(self.textIcon) + toolSizer = wxGridSizer(0, 2, 5, 5) + toolSizer.Add(self.selectIcon) + toolSizer.Add(0, 0) # Gap to make tool icons line up nicely. + toolSizer.Add(self.lineIcon) + toolSizer.Add(self.rectIcon) + toolSizer.Add(self.ellipseIcon) + toolSizer.Add(self.textIcon) - self.optionIndicator = ToolOptionIndicator(self.topPanel) - self.optionIndicator.SetToolTip( - wxToolTip("Shows Current Pen/Fill/Line Size Settings")) + self.optionIndicator = ToolOptionIndicator(self.topPanel) + self.optionIndicator.SetToolTip( + wxToolTip("Shows Current Pen/Fill/Line Size Settings")) - optionSizer = wxBoxSizer(wxHORIZONTAL) + optionSizer = wxBoxSizer(wxHORIZONTAL) - self.penOptIcon = ToolPaletteIcon(self.topPanel, id_PEN_OPT, - "penOpt", "Set Pen Colour") - self.fillOptIcon = ToolPaletteIcon(self.topPanel, id_FILL_OPT, - "fillOpt", "Set Fill Colour") - self.lineOptIcon = ToolPaletteIcon(self.topPanel, id_LINE_OPT, - "lineOpt", "Set Line Size") + self.penOptIcon = ToolPaletteIcon(self.topPanel, id_PEN_OPT, + "penOpt", "Set Pen Colour") + self.fillOptIcon = ToolPaletteIcon(self.topPanel, id_FILL_OPT, + "fillOpt", "Set Fill Colour") + self.lineOptIcon = ToolPaletteIcon(self.topPanel, id_LINE_OPT, + "lineOpt", "Set Line Size") - margin = wxLEFT | wxRIGHT - optionSizer.Add(self.penOptIcon, 0, margin, 1) - optionSizer.Add(self.fillOptIcon, 0, margin, 1) - optionSizer.Add(self.lineOptIcon, 0, margin, 1) + margin = wxLEFT | wxRIGHT + optionSizer.Add(self.penOptIcon, 0, margin, 1) + optionSizer.Add(self.fillOptIcon, 0, margin, 1) + optionSizer.Add(self.lineOptIcon, 0, margin, 1) - margin = wxTOP | wxLEFT | wxRIGHT | wxALIGN_CENTRE - self.toolPalette.Add(toolSizer, 0, margin, 5) - self.toolPalette.Add(0, 0, 0, margin, 5) # Spacer. - self.toolPalette.Add(self.optionIndicator, 0, margin, 5) - self.toolPalette.Add(optionSizer, 0, margin, 5) + margin = wxTOP | wxLEFT | wxRIGHT | wxALIGN_CENTRE + self.toolPalette.Add(toolSizer, 0, margin, 5) + self.toolPalette.Add(0, 0, 0, margin, 5) # Spacer. + self.toolPalette.Add(self.optionIndicator, 0, margin, 5) + self.toolPalette.Add(optionSizer, 0, margin, 5) - # Make the tool palette icons respond when the user clicks on them. + # Make the tool palette icons respond when the user clicks on them. - EVT_LEFT_DOWN(self.selectIcon, self.onToolIconClick) - EVT_LEFT_DOWN(self.lineIcon, self.onToolIconClick) - EVT_LEFT_DOWN(self.rectIcon, self.onToolIconClick) - EVT_LEFT_DOWN(self.ellipseIcon, self.onToolIconClick) - EVT_LEFT_DOWN(self.textIcon, self.onToolIconClick) - EVT_LEFT_DOWN(self.penOptIcon, self.onPenOptionIconClick) - EVT_LEFT_DOWN(self.fillOptIcon, self.onFillOptionIconClick) - EVT_LEFT_DOWN(self.lineOptIcon, self.onLineOptionIconClick) + EVT_LEFT_DOWN(self.selectIcon, self.onToolIconClick) + EVT_LEFT_DOWN(self.lineIcon, self.onToolIconClick) + EVT_LEFT_DOWN(self.rectIcon, self.onToolIconClick) + EVT_LEFT_DOWN(self.ellipseIcon, self.onToolIconClick) + EVT_LEFT_DOWN(self.textIcon, self.onToolIconClick) + EVT_LEFT_DOWN(self.penOptIcon, self.onPenOptionIconClick) + EVT_LEFT_DOWN(self.fillOptIcon, self.onFillOptionIconClick) + EVT_LEFT_DOWN(self.lineOptIcon, self.onLineOptionIconClick) - # Setup the main drawing area. + # Setup the main drawing area. - self.drawPanel = wxScrolledWindow(self.topPanel, -1, - style=wxSUNKEN_BORDER) - self.drawPanel.SetBackgroundColour(wxWHITE) + self.drawPanel = wxScrolledWindow(self.topPanel, -1, + style=wxSUNKEN_BORDER) + self.drawPanel.SetBackgroundColour(wxWHITE) - self.drawPanel.EnableScrolling(true, true) - self.drawPanel.SetScrollbars(20, 20, PAGE_WIDTH / 20, PAGE_HEIGHT / 20) + self.drawPanel.EnableScrolling(true, true) + self.drawPanel.SetScrollbars(20, 20, PAGE_WIDTH / 20, PAGE_HEIGHT / 20) - EVT_LEFT_DOWN(self.drawPanel, self.onMouseEvent) - EVT_LEFT_DCLICK(self.drawPanel, self.onDoubleClickEvent) - EVT_RIGHT_DOWN(self.drawPanel, self.onRightClick) - EVT_MOTION(self.drawPanel, self.onMouseEvent) - EVT_LEFT_UP(self.drawPanel, self.onMouseEvent) - EVT_PAINT(self.drawPanel, self.onPaintEvent) + EVT_LEFT_DOWN(self.drawPanel, self.onMouseEvent) + EVT_LEFT_DCLICK(self.drawPanel, self.onDoubleClickEvent) + EVT_RIGHT_DOWN(self.drawPanel, self.onRightClick) + EVT_MOTION(self.drawPanel, self.onMouseEvent) + EVT_LEFT_UP(self.drawPanel, self.onMouseEvent) + EVT_PAINT(self.drawPanel, self.onPaintEvent) - # Position everything in the window. + # Position everything in the window. - topSizer = wxBoxSizer(wxHORIZONTAL) - topSizer.Add(self.toolPalette, 0) - topSizer.Add(self.drawPanel, 1, wxEXPAND) + topSizer = wxBoxSizer(wxHORIZONTAL) + topSizer.Add(self.toolPalette, 0) + topSizer.Add(self.drawPanel, 1, wxEXPAND) - self.topPanel.SetAutoLayout(true) - self.topPanel.SetSizer(topSizer) + self.topPanel.SetAutoLayout(true) + self.topPanel.SetSizer(topSizer) - self.SetSizeHints(minW=250, minH=200) - self.SetSize(wxSize(600, 400)) + self.SetSizeHints(minW=250, minH=200) + self.SetSize(wxSize(600, 400)) - # Select an initial tool. + # Select an initial tool. - self.curTool = None - self._setCurrentTool(self.selectIcon) + self.curTool = None + self._setCurrentTool(self.selectIcon) - # Setup our frame to hold the contents of a sketch document. + # Setup our frame to hold the contents of a sketch document. - self.dirty = false - self.fileName = fileName - self.contents = [] # front-to-back ordered list of DrawingObjects. - self.selection = [] # List of selected DrawingObjects. - self.undoInfo = None # Saved contents for undo. - self.dragMode = drag_NONE # Current mouse-drag mode. + self.dirty = false + self.fileName = fileName + self.contents = [] # front-to-back ordered list of DrawingObjects. + self.selection = [] # List of selected DrawingObjects. + self.undoInfo = None # Saved contents for undo. + self.dragMode = drag_NONE # Current mouse-drag mode. - if self.fileName != None: - self.loadContents() + if self.fileName != None: + self.loadContents() - self._adjustMenus() + self._adjustMenus() - # Finally, set our initial pen, fill and line options. + # Finally, set our initial pen, fill and line options. - self.penColour = wxBLACK - self.fillColour = wxWHITE - self.lineSize = 1 + self.penColour = wxBLACK + self.fillColour = wxWHITE + self.lineSize = 1 # ============================ # == Event Handling Methods == # ============================ def onToolIconClick(self, event): - """ Respond to the user clicking on one of our tool icons. - """ - iconID = wxPyTypeCast(event.GetEventObject(), "wxWindow").GetId() - if iconID == id_SELECT: self.doChooseSelectTool() - elif iconID == id_LINE: self.doChooseLineTool() - elif iconID == id_RECT: self.doChooseRectTool() - elif iconID == id_ELLIPSE: self.doChooseEllipseTool() - elif iconID == id_TEXT: self.doChooseTextTool() - else: wxBell() + """ Respond to the user clicking on one of our tool icons. + """ + iconID = wxPyTypeCast(event.GetEventObject(), "wxWindow").GetId() + if iconID == id_SELECT: self.doChooseSelectTool() + elif iconID == id_LINE: self.doChooseLineTool() + elif iconID == id_RECT: self.doChooseRectTool() + elif iconID == id_ELLIPSE: self.doChooseEllipseTool() + elif iconID == id_TEXT: self.doChooseTextTool() + else: wxBell() def onPenOptionIconClick(self, event): - """ Respond to the user clicking on the "Pen Options" icon. - """ - data = wxColourData() - if len(self.selection) == 1: - data.SetColour(self.selection[0].getPenColour()) - else: - data.SetColour(self.penColour) + """ Respond to the user clicking on the "Pen Options" icon. + """ + data = wxColourData() + if len(self.selection) == 1: + data.SetColour(self.selection[0].getPenColour()) + else: + data.SetColour(self.penColour) - dialog = wxColourDialog(self, data) - if dialog.ShowModal() == wxID_OK: - c = dialog.GetColourData().GetColour() - self._setPenColour(wxColour(c.Red(), c.Green(), c.Blue())) + dialog = wxColourDialog(self, data) + if dialog.ShowModal() == wxID_OK: + c = dialog.GetColourData().GetColour() + self._setPenColour(wxColour(c.Red(), c.Green(), c.Blue())) dialog.Destroy() def onFillOptionIconClick(self, event): - """ Respond to the user clicking on the "Fill Options" icon. - """ - data = wxColourData() - if len(self.selection) == 1: - data.SetColour(self.selection[0].getFillColour()) - else: - data.SetColour(self.fillColour) + """ Respond to the user clicking on the "Fill Options" icon. + """ + data = wxColourData() + if len(self.selection) == 1: + data.SetColour(self.selection[0].getFillColour()) + else: + data.SetColour(self.fillColour) - dialog = wxColourDialog(self, data) - if dialog.ShowModal() == wxID_OK: - c = dialog.GetColourData().GetColour() - self._setFillColour(wxColour(c.Red(), c.Green(), c.Blue())) + dialog = wxColourDialog(self, data) + if dialog.ShowModal() == wxID_OK: + c = dialog.GetColourData().GetColour() + self._setFillColour(wxColour(c.Red(), c.Green(), c.Blue())) dialog.Destroy() def onLineOptionIconClick(self, event): - """ Respond to the user clicking on the "Line Options" icon. - """ - if len(self.selection) == 1: - menu = self._buildLineSizePopup(self.selection[0].getLineSize()) - else: - menu = self._buildLineSizePopup(self.lineSize) + """ Respond to the user clicking on the "Line Options" icon. + """ + if len(self.selection) == 1: + menu = self._buildLineSizePopup(self.selection[0].getLineSize()) + else: + menu = self._buildLineSizePopup(self.lineSize) - pos = self.lineOptIcon.GetPosition() - pos.y = pos.y + self.lineOptIcon.GetSize().height + pos = self.lineOptIcon.GetPosition() + pos.y = pos.y + self.lineOptIcon.GetSize().height self.PopupMenu(menu, pos) menu.Destroy() def onKeyEvent(self, event): - """ Respond to a keypress event. + """ Respond to a keypress event. - We make the arrow keys move the selected object(s) by one pixel in - the given direction. - """ - if event.GetKeyCode() == WXK_UP: - self._moveObject(0, -1) - elif event.GetKeyCode() == WXK_DOWN: - self._moveObject(0, 1) - elif event.GetKeyCode() == WXK_LEFT: - self._moveObject(-1, 0) - elif event.GetKeyCode() == WXK_RIGHT: - self._moveObject(1, 0) - else: - event.Skip() + We make the arrow keys move the selected object(s) by one pixel in + the given direction. + """ + if event.GetKeyCode() == WXK_UP: + self._moveObject(0, -1) + elif event.GetKeyCode() == WXK_DOWN: + self._moveObject(0, 1) + elif event.GetKeyCode() == WXK_LEFT: + self._moveObject(-1, 0) + elif event.GetKeyCode() == WXK_RIGHT: + self._moveObject(1, 0) + else: + event.Skip() def onMouseEvent(self, event): - """ Respond to the user clicking on our main drawing panel. + """ Respond to the user clicking on our main drawing panel. - How we respond depends on the currently selected tool. - """ - if not (event.LeftDown() or event.Dragging() or event.LeftUp()): - return # Ignore mouse movement without click/drag. + How we respond depends on the currently selected tool. + """ + if not (event.LeftDown() or event.Dragging() or event.LeftUp()): + return # Ignore mouse movement without click/drag. - if self.curTool == self.selectIcon: - feedbackType = feedback_RECT - action = self.selectByRectangle - actionParam = param_RECT - selecting = true - dashedLine = true - elif self.curTool == self.lineIcon: - feedbackType = feedback_LINE - action = self.createLine - actionParam = param_LINE - selecting = false - dashedLine = false - elif self.curTool == self.rectIcon: - feedbackType = feedback_RECT - action = self.createRect - actionParam = param_RECT - selecting = false - dashedLine = false - elif self.curTool == self.ellipseIcon: - feedbackType = feedback_ELLIPSE - action = self.createEllipse - actionParam = param_RECT - selecting = false - dashedLine = false - elif self.curTool == self.textIcon: - feedbackType = feedback_RECT - action = self.createText - actionParam = param_RECT - selecting = false - dashedLine = true - else: - wxBell() - return + if self.curTool == self.selectIcon: + feedbackType = feedback_RECT + action = self.selectByRectangle + actionParam = param_RECT + selecting = true + dashedLine = true + elif self.curTool == self.lineIcon: + feedbackType = feedback_LINE + action = self.createLine + actionParam = param_LINE + selecting = false + dashedLine = false + elif self.curTool == self.rectIcon: + feedbackType = feedback_RECT + action = self.createRect + actionParam = param_RECT + selecting = false + dashedLine = false + elif self.curTool == self.ellipseIcon: + feedbackType = feedback_ELLIPSE + action = self.createEllipse + actionParam = param_RECT + selecting = false + dashedLine = false + elif self.curTool == self.textIcon: + feedbackType = feedback_RECT + action = self.createText + actionParam = param_RECT + selecting = false + dashedLine = true + else: + wxBell() + return - if event.LeftDown(): - mousePt = self._getEventCoordinates(event) - if selecting: - obj, handle = self._getObjectAndSelectionHandleAt(mousePt) + if event.LeftDown(): + mousePt = self._getEventCoordinates(event) + if selecting: + obj, handle = self._getObjectAndSelectionHandleAt(mousePt) - if selecting and (obj != None) and (handle != handle_NONE): + if selecting and (obj != None) and (handle != handle_NONE): - # The user clicked on an object's selection handle. Let the - # user resize the clicked-on object. + # The user clicked on an object's selection handle. Let the + # user resize the clicked-on object. - self.dragMode = drag_RESIZE - self.resizeObject = obj + self.dragMode = drag_RESIZE + self.resizeObject = obj - if obj.getType() == obj_LINE: - self.resizeFeedback = feedback_LINE - pos = obj.getPosition() - startPt = wxPoint(pos.x + obj.getStartPt().x, - pos.y + obj.getStartPt().y) - endPt = wxPoint(pos.x + obj.getEndPt().x, - pos.y + obj.getEndPt().y) - if handle == handle_START_POINT: - self.resizeAnchor = endPt - self.resizeFloater = startPt - else: - self.resizeAnchor = startPt - self.resizeFloater = endPt - else: - self.resizeFeedback = feedback_RECT - pos = obj.getPosition() - size = obj.getSize() - topLeft = wxPoint(pos.x, pos.y) - topRight = wxPoint(pos.x + size.width, pos.y) - botLeft = wxPoint(pos.x, pos.y + size.height) - botRight = wxPoint(pos.x + size.width, pos.y + size.height) + if obj.getType() == obj_LINE: + self.resizeFeedback = feedback_LINE + pos = obj.getPosition() + startPt = wxPoint(pos.x + obj.getStartPt().x, + pos.y + obj.getStartPt().y) + endPt = wxPoint(pos.x + obj.getEndPt().x, + pos.y + obj.getEndPt().y) + if handle == handle_START_POINT: + self.resizeAnchor = endPt + self.resizeFloater = startPt + else: + self.resizeAnchor = startPt + self.resizeFloater = endPt + else: + self.resizeFeedback = feedback_RECT + pos = obj.getPosition() + size = obj.getSize() + topLeft = wxPoint(pos.x, pos.y) + topRight = wxPoint(pos.x + size.width, pos.y) + botLeft = wxPoint(pos.x, pos.y + size.height) + botRight = wxPoint(pos.x + size.width, pos.y + size.height) - if handle == handle_TOP_LEFT: - self.resizeAnchor = botRight - self.resizeFloater = topLeft - elif handle == handle_TOP_RIGHT: - self.resizeAnchor = botLeft - self.resizeFloater = topRight - elif handle == handle_BOTTOM_LEFT: - self.resizeAnchor = topRight - self.resizeFloater = botLeft - elif handle == handle_BOTTOM_RIGHT: - self.resizeAnchor = topLeft - self.resizeFloater = botRight + if handle == handle_TOP_LEFT: + self.resizeAnchor = botRight + self.resizeFloater = topLeft + elif handle == handle_TOP_RIGHT: + self.resizeAnchor = botLeft + self.resizeFloater = topRight + elif handle == handle_BOTTOM_LEFT: + self.resizeAnchor = topRight + self.resizeFloater = botLeft + elif handle == handle_BOTTOM_RIGHT: + self.resizeAnchor = topLeft + self.resizeFloater = botRight - self.curPt = mousePt - self.resizeOffsetX = self.resizeFloater.x - mousePt.x - self.resizeOffsetY = self.resizeFloater.y - mousePt.y - endPt = wxPoint(self.curPt.x + self.resizeOffsetX, - self.curPt.y + self.resizeOffsetY) - self._drawVisualFeedback(self.resizeAnchor, endPt, - self.resizeFeedback, false) + self.curPt = mousePt + self.resizeOffsetX = self.resizeFloater.x - mousePt.x + self.resizeOffsetY = self.resizeFloater.y - mousePt.y + endPt = wxPoint(self.curPt.x + self.resizeOffsetX, + self.curPt.y + self.resizeOffsetY) + self._drawVisualFeedback(self.resizeAnchor, endPt, + self.resizeFeedback, false) - elif selecting and (self._getObjectAt(mousePt) != None): + elif selecting and (self._getObjectAt(mousePt) != None): - # The user clicked on an object to select it. If the user - # drags, he/she will move the object. + # The user clicked on an object to select it. If the user + # drags, he/she will move the object. - self.select(self._getObjectAt(mousePt)) - self.dragMode = drag_MOVE - self.moveOrigin = mousePt - self.curPt = mousePt - self._drawObjectOutline(0, 0) + self.select(self._getObjectAt(mousePt)) + self.dragMode = drag_MOVE + self.moveOrigin = mousePt + self.curPt = mousePt + self._drawObjectOutline(0, 0) - else: + else: - # The user is dragging out a selection rect or new object. + # The user is dragging out a selection rect or new object. - self.dragOrigin = mousePt - self.curPt = mousePt - self.drawPanel.SetCursor(wxCROSS_CURSOR) - self.drawPanel.CaptureMouse() - self._drawVisualFeedback(mousePt, mousePt, feedbackType, - dashedLine) - self.dragMode = drag_DRAG + self.dragOrigin = mousePt + self.curPt = mousePt + self.drawPanel.SetCursor(wxCROSS_CURSOR) + self.drawPanel.CaptureMouse() + self._drawVisualFeedback(mousePt, mousePt, feedbackType, + dashedLine) + self.dragMode = drag_DRAG - event.Skip() - return + event.Skip() + return - if event.Dragging(): - if self.dragMode == drag_RESIZE: + if event.Dragging(): + if self.dragMode == drag_RESIZE: - # We're resizing an object. + # We're resizing an object. - mousePt = self._getEventCoordinates(event) - if (self.curPt.x != mousePt.x) or (self.curPt.y != mousePt.y): - # Erase previous visual feedback. - endPt = wxPoint(self.curPt.x + self.resizeOffsetX, - self.curPt.y + self.resizeOffsetY) - self._drawVisualFeedback(self.resizeAnchor, endPt, - self.resizeFeedback, false) - self.curPt = mousePt - # Draw new visual feedback. - endPt = wxPoint(self.curPt.x + self.resizeOffsetX, - self.curPt.y + self.resizeOffsetY) - self._drawVisualFeedback(self.resizeAnchor, endPt, - self.resizeFeedback, false) + mousePt = self._getEventCoordinates(event) + if (self.curPt.x != mousePt.x) or (self.curPt.y != mousePt.y): + # Erase previous visual feedback. + endPt = wxPoint(self.curPt.x + self.resizeOffsetX, + self.curPt.y + self.resizeOffsetY) + self._drawVisualFeedback(self.resizeAnchor, endPt, + self.resizeFeedback, false) + self.curPt = mousePt + # Draw new visual feedback. + endPt = wxPoint(self.curPt.x + self.resizeOffsetX, + self.curPt.y + self.resizeOffsetY) + self._drawVisualFeedback(self.resizeAnchor, endPt, + self.resizeFeedback, false) - elif self.dragMode == drag_MOVE: + elif self.dragMode == drag_MOVE: - # We're moving a selected object. + # We're moving a selected object. - mousePt = self._getEventCoordinates(event) - if (self.curPt.x != mousePt.x) or (self.curPt.y != mousePt.y): - # Erase previous visual feedback. - self._drawObjectOutline(self.curPt.x - self.moveOrigin.x, - self.curPt.y - self.moveOrigin.y) - self.curPt = mousePt - # Draw new visual feedback. - self._drawObjectOutline(self.curPt.x - self.moveOrigin.x, - self.curPt.y - self.moveOrigin.y) + mousePt = self._getEventCoordinates(event) + if (self.curPt.x != mousePt.x) or (self.curPt.y != mousePt.y): + # Erase previous visual feedback. + self._drawObjectOutline(self.curPt.x - self.moveOrigin.x, + self.curPt.y - self.moveOrigin.y) + self.curPt = mousePt + # Draw new visual feedback. + self._drawObjectOutline(self.curPt.x - self.moveOrigin.x, + self.curPt.y - self.moveOrigin.y) - elif self.dragMode == drag_DRAG: + elif self.dragMode == drag_DRAG: - # We're dragging out a new object or selection rect. + # We're dragging out a new object or selection rect. - mousePt = self._getEventCoordinates(event) - if (self.curPt.x != mousePt.x) or (self.curPt.y != mousePt.y): - # Erase previous visual feedback. - self._drawVisualFeedback(self.dragOrigin, self.curPt, - feedbackType, dashedLine) - self.curPt = mousePt - # Draw new visual feedback. - self._drawVisualFeedback(self.dragOrigin, self.curPt, - feedbackType, dashedLine) + mousePt = self._getEventCoordinates(event) + if (self.curPt.x != mousePt.x) or (self.curPt.y != mousePt.y): + # Erase previous visual feedback. + self._drawVisualFeedback(self.dragOrigin, self.curPt, + feedbackType, dashedLine) + self.curPt = mousePt + # Draw new visual feedback. + self._drawVisualFeedback(self.dragOrigin, self.curPt, + feedbackType, dashedLine) - event.Skip() - return + event.Skip() + return - if event.LeftUp(): - if self.dragMode == drag_RESIZE: + if event.LeftUp(): + if self.dragMode == drag_RESIZE: - # We're resizing an object. + # We're resizing an object. - mousePt = self._getEventCoordinates(event) - # Erase last visual feedback. - endPt = wxPoint(self.curPt.x + self.resizeOffsetX, - self.curPt.y + self.resizeOffsetY) - self._drawVisualFeedback(self.resizeAnchor, endPt, - self.resizeFeedback, false) + mousePt = self._getEventCoordinates(event) + # Erase last visual feedback. + endPt = wxPoint(self.curPt.x + self.resizeOffsetX, + self.curPt.y + self.resizeOffsetY) + self._drawVisualFeedback(self.resizeAnchor, endPt, + self.resizeFeedback, false) - resizePt = wxPoint(mousePt.x + self.resizeOffsetX, - mousePt.y + self.resizeOffsetY) + resizePt = wxPoint(mousePt.x + self.resizeOffsetX, + mousePt.y + self.resizeOffsetY) - if (self.resizeFloater.x != resizePt.x) or \ - (self.resizeFloater.y != resizePt.y): - self._resizeObject(self.resizeObject, - self.resizeAnchor, - self.resizeFloater, - resizePt) - else: - self.drawPanel.Refresh() # Clean up after empty resize. + if (self.resizeFloater.x != resizePt.x) or \ + (self.resizeFloater.y != resizePt.y): + self._resizeObject(self.resizeObject, + self.resizeAnchor, + self.resizeFloater, + resizePt) + else: + self.drawPanel.Refresh() # Clean up after empty resize. - elif self.dragMode == drag_MOVE: + elif self.dragMode == drag_MOVE: - # We're moving a selected object. + # We're moving a selected object. - mousePt = self._getEventCoordinates(event) - # Erase last visual feedback. - self._drawObjectOutline(self.curPt.x - self.moveOrigin.x, - self.curPt.y - self.moveOrigin.y) - if (self.moveOrigin.x != mousePt.x) or \ - (self.moveOrigin.y != mousePt.y): - self._moveObject(mousePt.x - self.moveOrigin.x, - mousePt.y - self.moveOrigin.y) - else: - self.drawPanel.Refresh() # Clean up after empty drag. + mousePt = self._getEventCoordinates(event) + # Erase last visual feedback. + self._drawObjectOutline(self.curPt.x - self.moveOrigin.x, + self.curPt.y - self.moveOrigin.y) + if (self.moveOrigin.x != mousePt.x) or \ + (self.moveOrigin.y != mousePt.y): + self._moveObject(mousePt.x - self.moveOrigin.x, + mousePt.y - self.moveOrigin.y) + else: + self.drawPanel.Refresh() # Clean up after empty drag. - elif self.dragMode == drag_DRAG: + elif self.dragMode == drag_DRAG: - # We're dragging out a new object or selection rect. + # We're dragging out a new object or selection rect. - mousePt = self._getEventCoordinates(event) - # Erase last visual feedback. - self._drawVisualFeedback(self.dragOrigin, self.curPt, - feedbackType, dashedLine) - self.drawPanel.ReleaseMouse() - self.drawPanel.SetCursor(wxSTANDARD_CURSOR) - # Perform the appropriate action for the current tool. - if actionParam == param_RECT: - x1 = min(self.dragOrigin.x, self.curPt.x) - y1 = min(self.dragOrigin.y, self.curPt.y) - x2 = max(self.dragOrigin.x, self.curPt.x) - y2 = max(self.dragOrigin.y, self.curPt.y) + mousePt = self._getEventCoordinates(event) + # Erase last visual feedback. + self._drawVisualFeedback(self.dragOrigin, self.curPt, + feedbackType, dashedLine) + self.drawPanel.ReleaseMouse() + self.drawPanel.SetCursor(wxSTANDARD_CURSOR) + # Perform the appropriate action for the current tool. + if actionParam == param_RECT: + x1 = min(self.dragOrigin.x, self.curPt.x) + y1 = min(self.dragOrigin.y, self.curPt.y) + x2 = max(self.dragOrigin.x, self.curPt.x) + y2 = max(self.dragOrigin.y, self.curPt.y) - startX = x1 - startY = y1 - width = x2 - x1 - height = y2 - y1 + startX = x1 + startY = y1 + width = x2 - x1 + height = y2 - y1 - if not selecting: - if ((x2-x1) < 8) or ((y2-y1) < 8): return # Too small. + if not selecting: + if ((x2-x1) < 8) or ((y2-y1) < 8): return # Too small. - action(x1, y1, x2-x1, y2-y1) - elif actionParam == param_LINE: - action(self.dragOrigin.x, self.dragOrigin.y, - self.curPt.x, self.curPt.y) + action(x1, y1, x2-x1, y2-y1) + elif actionParam == param_LINE: + action(self.dragOrigin.x, self.dragOrigin.y, + self.curPt.x, self.curPt.y) - self.dragMode = drag_NONE # We've finished with this mouse event. - event.Skip() + self.dragMode = drag_NONE # We've finished with this mouse event. + event.Skip() def onDoubleClickEvent(self, event): - """ Respond to a double-click within our drawing panel. - """ - mousePt = self._getEventCoordinates(event) - obj = self._getObjectAt(mousePt) - if obj == None: return + """ Respond to a double-click within our drawing panel. + """ + mousePt = self._getEventCoordinates(event) + obj = self._getObjectAt(mousePt) + if obj == None: return - # Let the user edit the given object. + # Let the user edit the given object. - if obj.getType() == obj_TEXT: - editor = EditTextObjectDialog(self, "Edit Text Object") - editor.objectToDialog(obj) - if editor.ShowModal() == wxID_CANCEL: - editor.Destroy() - return + if obj.getType() == obj_TEXT: + editor = EditTextObjectDialog(self, "Edit Text Object") + editor.objectToDialog(obj) + if editor.ShowModal() == wxID_CANCEL: + editor.Destroy() + return - self._saveUndoInfo() + self._saveUndoInfo() - editor.dialogToObject(obj) - editor.Destroy() + editor.dialogToObject(obj) + editor.Destroy() - self.dirty = true - self.drawPanel.Refresh() - self._adjustMenus() - else: - wxBell() + self.dirty = true + self.drawPanel.Refresh() + self._adjustMenus() + else: + wxBell() def onRightClick(self, event): - """ Respond to the user right-clicking within our drawing panel. + """ Respond to the user right-clicking within our drawing panel. - We select the clicked-on item, if necessary, and display a pop-up - menu of available options which can be applied to the selected - item(s). - """ - mousePt = self._getEventCoordinates(event) - obj = self._getObjectAt(mousePt) + We select the clicked-on item, if necessary, and display a pop-up + menu of available options which can be applied to the selected + item(s). + """ + mousePt = self._getEventCoordinates(event) + obj = self._getObjectAt(mousePt) - if obj == None: return # Nothing selected. + if obj == None: return # Nothing selected. - # Select the clicked-on object. + # Select the clicked-on object. - self.select(obj) + self.select(obj) - # Build our pop-up menu. + # Build our pop-up menu. - menu = wxMenu() - menu.Append(menu_DUPLICATE, "Duplicate") - menu.Append(menu_EDIT_TEXT, "Edit...") - menu.Append(menu_DELETE, "Delete") - menu.AppendSeparator() - menu.Append(menu_MOVE_FORWARD, "Move Forward") - menu.Append(menu_MOVE_TO_FRONT, "Move to Front") - menu.Append(menu_MOVE_BACKWARD, "Move Backward") - menu.Append(menu_MOVE_TO_BACK, "Move to Back") + menu = wxMenu() + menu.Append(menu_DUPLICATE, "Duplicate") + menu.Append(menu_EDIT_TEXT, "Edit...") + menu.Append(menu_DELETE, "Delete") + menu.AppendSeparator() + menu.Append(menu_MOVE_FORWARD, "Move Forward") + menu.Append(menu_MOVE_TO_FRONT, "Move to Front") + menu.Append(menu_MOVE_BACKWARD, "Move Backward") + menu.Append(menu_MOVE_TO_BACK, "Move to Back") - menu.Enable(menu_EDIT_TEXT, obj.getType() == obj_TEXT) - menu.Enable(menu_MOVE_FORWARD, obj != self.contents[0]) - menu.Enable(menu_MOVE_TO_FRONT, obj != self.contents[0]) - menu.Enable(menu_MOVE_BACKWARD, obj != self.contents[-1]) - menu.Enable(menu_MOVE_TO_BACK, obj != self.contents[-1]) + menu.Enable(menu_EDIT_TEXT, obj.getType() == obj_TEXT) + menu.Enable(menu_MOVE_FORWARD, obj != self.contents[0]) + menu.Enable(menu_MOVE_TO_FRONT, obj != self.contents[0]) + menu.Enable(menu_MOVE_BACKWARD, obj != self.contents[-1]) + menu.Enable(menu_MOVE_TO_BACK, obj != self.contents[-1]) - EVT_MENU(self, menu_DUPLICATE, self.doDuplicate) - EVT_MENU(self, menu_EDIT_TEXT, self.doEditText) - EVT_MENU(self, menu_DELETE, self.doDelete) - EVT_MENU(self, menu_MOVE_FORWARD, self.doMoveForward) - EVT_MENU(self, menu_MOVE_TO_FRONT, self.doMoveToFront) - EVT_MENU(self, menu_MOVE_BACKWARD, self.doMoveBackward) - EVT_MENU(self, menu_MOVE_TO_BACK, self.doMoveToBack) + EVT_MENU(self, menu_DUPLICATE, self.doDuplicate) + EVT_MENU(self, menu_EDIT_TEXT, self.doEditText) + EVT_MENU(self, menu_DELETE, self.doDelete) + EVT_MENU(self, menu_MOVE_FORWARD, self.doMoveForward) + EVT_MENU(self, menu_MOVE_TO_FRONT, self.doMoveToFront) + EVT_MENU(self, menu_MOVE_BACKWARD, self.doMoveBackward) + EVT_MENU(self, menu_MOVE_TO_BACK, self.doMoveToBack) - # Show the pop-up menu. + # Show the pop-up menu. - clickPt = wxPoint(mousePt.x + self.drawPanel.GetPosition().x, - mousePt.y + self.drawPanel.GetPosition().y) - self.drawPanel.PopupMenu(menu, clickPt) - menu.Destroy() + clickPt = wxPoint(mousePt.x + self.drawPanel.GetPosition().x, + mousePt.y + self.drawPanel.GetPosition().y) + self.drawPanel.PopupMenu(menu, clickPt) + menu.Destroy() def onPaintEvent(self, event): - """ Respond to a request to redraw the contents of our drawing panel. - """ - dc = wxPaintDC(self.drawPanel) - self.drawPanel.PrepareDC(dc) - dc.BeginDrawing() + """ Respond to a request to redraw the contents of our drawing panel. + """ + dc = wxPaintDC(self.drawPanel) + self.drawPanel.PrepareDC(dc) + dc.BeginDrawing() - for i in range(len(self.contents)-1, -1, -1): - obj = self.contents[i] - if obj in self.selection: - obj.draw(dc, true) - else: - obj.draw(dc, false) + for i in range(len(self.contents)-1, -1, -1): + obj = self.contents[i] + if obj in self.selection: + obj.draw(dc, true) + else: + obj.draw(dc, false) - dc.EndDrawing() + dc.EndDrawing() # ========================== # == Menu Command Methods == # ========================== def doNew(self, event): - """ Respond to the "New" menu command. - """ - global _docList - newFrame = DrawingFrame(None, -1, "Untitled") - newFrame.Show(TRUE) - _docList.append(newFrame) + """ Respond to the "New" menu command. + """ + global _docList + newFrame = DrawingFrame(None, -1, "Untitled") + newFrame.Show(TRUE) + _docList.append(newFrame) def doOpen(self, event): - """ Respond to the "Open" menu command. - """ - global _docList + """ Respond to the "Open" menu command. + """ + global _docList - curDir = os.getcwd() - fileName = wxFileSelector("Open File", default_extension="psk", - flags = wxOPEN | wxFILE_MUST_EXIST) - if fileName == "": return - fileName = os.path.join(os.getcwd(), fileName) - os.chdir(curDir) + curDir = os.getcwd() + fileName = wxFileSelector("Open File", default_extension="psk", + flags = wxOPEN | wxFILE_MUST_EXIST) + if fileName == "": return + fileName = os.path.join(os.getcwd(), fileName) + os.chdir(curDir) - title = os.path.basename(fileName) + title = os.path.basename(fileName) - if (self.fileName == None) and (len(self.contents) == 0): - # Load contents into current (empty) document. - self.fileName = fileName - self.SetTitle(os.path.basename(fileName)) - self.loadContents() - else: - # Open a new frame for this document. - newFrame = DrawingFrame(None, -1, os.path.basename(fileName), - fileName=fileName) - newFrame.Show(true) - _docList.append(newFrame) + if (self.fileName == None) and (len(self.contents) == 0): + # Load contents into current (empty) document. + self.fileName = fileName + self.SetTitle(os.path.basename(fileName)) + self.loadContents() + else: + # Open a new frame for this document. + newFrame = DrawingFrame(None, -1, os.path.basename(fileName), + fileName=fileName) + newFrame.Show(true) + _docList.append(newFrame) def doClose(self, event): - """ Respond to the "Close" menu command. - """ - global _docList + """ Respond to the "Close" menu command. + """ + global _docList - if self.dirty: - if not self.askIfUserWantsToSave("closing"): return + if self.dirty: + if not self.askIfUserWantsToSave("closing"): return - _docList.remove(self) - self.Destroy() + _docList.remove(self) + self.Destroy() def doSave(self, event): - """ Respond to the "Save" menu command. - """ - if self.fileName != None: - self.saveContents() + """ Respond to the "Save" menu command. + """ + if self.fileName != None: + self.saveContents() def doSaveAs(self, event): - """ Respond to the "Save As" menu command. - """ - if self.fileName == None: - default = "" - else: - default = self.fileName + """ Respond to the "Save As" menu command. + """ + if self.fileName == None: + default = "" + else: + default = self.fileName - curDir = os.getcwd() - fileName = wxFileSelector("Save File As", "Saving", - default_filename=default, - default_extension="psk", - wildcard="*.psk", - flags = wxSAVE | wxOVERWRITE_PROMPT) - if fileName == "": return # User cancelled. - fileName = os.path.join(os.getcwd(), fileName) - os.chdir(curDir) + curDir = os.getcwd() + fileName = wxFileSelector("Save File As", "Saving", + default_filename=default, + default_extension="psk", + wildcard="*.psk", + flags = wxSAVE | wxOVERWRITE_PROMPT) + if fileName == "": return # User cancelled. + fileName = os.path.join(os.getcwd(), fileName) + os.chdir(curDir) - title = os.path.basename(fileName) - self.SetTitle(title) + title = os.path.basename(fileName) + self.SetTitle(title) - self.fileName = fileName - self.saveContents() + self.fileName = fileName + self.saveContents() def doRevert(self, event): - """ Respond to the "Revert" menu command. - """ - if not self.dirty: return + """ Respond to the "Revert" menu command. + """ + if not self.dirty: return - if wxMessageBox("Discard changes made to this document?", "Confirm", - style = wxOK | wxCANCEL | wxICON_QUESTION, - parent=self) == wxCANCEL: return - self.loadContents() + if wxMessageBox("Discard changes made to this document?", "Confirm", + style = wxOK | wxCANCEL | wxICON_QUESTION, + parent=self) == wxCANCEL: return + self.loadContents() def doExit(self, event): - """ Respond to the "Quit" menu command. - """ - global _docList, _app - for doc in _docList: - if not doc.dirty: continue - doc.Raise() - if not doc.askIfUserWantsToSave("quitting"): return - _docList.remove(doc) - doc.Destroy() + """ Respond to the "Quit" menu command. + """ + global _docList, _app + for doc in _docList: + if not doc.dirty: continue + doc.Raise() + if not doc.askIfUserWantsToSave("quitting"): return + _docList.remove(doc) + doc.Destroy() - _app.ExitMainLoop() + _app.ExitMainLoop() def doUndo(self, event): - """ Respond to the "Undo" menu command. - """ - if self.undoInfo == None: return + """ Respond to the "Undo" menu command. + """ + if self.undoInfo == None: return - undoData = self.undoInfo - self._saveUndoInfo() # For undoing the undo... + undoData = self.undoInfo + self._saveUndoInfo() # For undoing the undo... - self.contents = [] + self.contents = [] - for type, data in undoData["contents"]: - obj = DrawingObject(type) - obj.setData(data) - self.contents.append(obj) + for type, data in undoData["contents"]: + obj = DrawingObject(type) + obj.setData(data) + self.contents.append(obj) - self.selection = [] - for i in undoData["selection"]: - self.selection.append(self.contents[i]) + self.selection = [] + for i in undoData["selection"]: + self.selection.append(self.contents[i]) - self.dirty = true - self.drawPanel.Refresh() - self._adjustMenus() + self.dirty = true + self.drawPanel.Refresh() + self._adjustMenus() def doSelectAll(self, event): - """ Respond to the "Select All" menu command. - """ - self.selectAll() + """ Respond to the "Select All" menu command. + """ + self.selectAll() def doDuplicate(self, event): - """ Respond to the "Duplicate" menu command. - """ - self._saveUndoInfo() + """ Respond to the "Duplicate" menu command. + """ + self._saveUndoInfo() - objs = [] - for obj in self.contents: - if obj in self.selection: - newObj = DrawingObject(obj.getType()) - newObj.setData(obj.getData()) - pos = obj.getPosition() - newObj.setPosition(wxPoint(pos.x + 10, pos.y + 10)) - objs.append(newObj) + objs = [] + for obj in self.contents: + if obj in self.selection: + newObj = DrawingObject(obj.getType()) + newObj.setData(obj.getData()) + pos = obj.getPosition() + newObj.setPosition(wxPoint(pos.x + 10, pos.y + 10)) + objs.append(newObj) - self.contents = objs + self.contents + self.contents = objs + self.contents - self.selectMany(objs) + self.selectMany(objs) def doEditText(self, event): - """ Respond to the "Edit Text" menu command. - """ - if len(self.selection) != 1: return + """ Respond to the "Edit Text" menu command. + """ + if len(self.selection) != 1: return - obj = self.selection[0] - if obj.getType() != obj_TEXT: return + obj = self.selection[0] + if obj.getType() != obj_TEXT: return - editor = EditTextObjectDialog(self, "Edit Text Object") - editor.objectToDialog(obj) - if editor.ShowModal() == wxID_CANCEL: - editor.Destroy() - return + editor = EditTextObjectDialog(self, "Edit Text Object") + editor.objectToDialog(obj) + if editor.ShowModal() == wxID_CANCEL: + editor.Destroy() + return - self._saveUndoInfo() + self._saveUndoInfo() - editor.dialogToObject(obj) - editor.Destroy() + editor.dialogToObject(obj) + editor.Destroy() - self.dirty = true - self.drawPanel.Refresh() - self._adjustMenus() + self.dirty = true + self.drawPanel.Refresh() + self._adjustMenus() def doDelete(self, event): - """ Respond to the "Delete" menu command. - """ - self._saveUndoInfo() + """ Respond to the "Delete" menu command. + """ + self._saveUndoInfo() - for obj in self.selection: - self.contents.remove(obj) - del obj - self.deselectAll() + for obj in self.selection: + self.contents.remove(obj) + del obj + self.deselectAll() def doChooseSelectTool(self, event=None): - """ Respond to the "Select Tool" menu command. - """ - self._setCurrentTool(self.selectIcon) - self.drawPanel.SetCursor(wxSTANDARD_CURSOR) - self._adjustMenus() + """ Respond to the "Select Tool" menu command. + """ + self._setCurrentTool(self.selectIcon) + self.drawPanel.SetCursor(wxSTANDARD_CURSOR) + self._adjustMenus() def doChooseLineTool(self, event=None): - """ Respond to the "Line Tool" menu command. - """ - self._setCurrentTool(self.lineIcon) - self.drawPanel.SetCursor(wxCROSS_CURSOR) - self.deselectAll() - self._adjustMenus() + """ Respond to the "Line Tool" menu command. + """ + self._setCurrentTool(self.lineIcon) + self.drawPanel.SetCursor(wxCROSS_CURSOR) + self.deselectAll() + self._adjustMenus() def doChooseRectTool(self, event=None): - """ Respond to the "Rect Tool" menu command. - """ - self._setCurrentTool(self.rectIcon) - self.drawPanel.SetCursor(wxCROSS_CURSOR) - self.deselectAll() - self._adjustMenus() + """ Respond to the "Rect Tool" menu command. + """ + self._setCurrentTool(self.rectIcon) + self.drawPanel.SetCursor(wxCROSS_CURSOR) + self.deselectAll() + self._adjustMenus() def doChooseEllipseTool(self, event=None): - """ Respond to the "Ellipse Tool" menu command. - """ - self._setCurrentTool(self.ellipseIcon) - self.drawPanel.SetCursor(wxCROSS_CURSOR) - self.deselectAll() - self._adjustMenus() + """ Respond to the "Ellipse Tool" menu command. + """ + self._setCurrentTool(self.ellipseIcon) + self.drawPanel.SetCursor(wxCROSS_CURSOR) + self.deselectAll() + self._adjustMenus() def doChooseTextTool(self, event=None): - """ Respond to the "Text Tool" menu command. - """ - self._setCurrentTool(self.textIcon) - self.drawPanel.SetCursor(wxCROSS_CURSOR) - self.deselectAll() - self._adjustMenus() + """ Respond to the "Text Tool" menu command. + """ + self._setCurrentTool(self.textIcon) + self.drawPanel.SetCursor(wxCROSS_CURSOR) + self.deselectAll() + self._adjustMenus() def doMoveForward(self, event): - """ Respond to the "Move Forward" menu command. - """ - if len(self.selection) != 1: return + """ Respond to the "Move Forward" menu command. + """ + if len(self.selection) != 1: return - self._saveUndoInfo() + self._saveUndoInfo() - obj = self.selection[0] - index = self.contents.index(obj) - if index == 0: return + obj = self.selection[0] + index = self.contents.index(obj) + if index == 0: return - del self.contents[index] - self.contents.insert(index-1, obj) + del self.contents[index] + self.contents.insert(index-1, obj) - self.drawPanel.Refresh() - self._adjustMenus() + self.drawPanel.Refresh() + self._adjustMenus() def doMoveToFront(self, event): - """ Respond to the "Move to Front" menu command. - """ - if len(self.selection) != 1: return + """ Respond to the "Move to Front" menu command. + """ + if len(self.selection) != 1: return - self._saveUndoInfo() + self._saveUndoInfo() - obj = self.selection[0] - self.contents.remove(obj) - self.contents.insert(0, obj) + obj = self.selection[0] + self.contents.remove(obj) + self.contents.insert(0, obj) - self.drawPanel.Refresh() - self._adjustMenus() + self.drawPanel.Refresh() + self._adjustMenus() def doMoveBackward(self, event): - """ Respond to the "Move Backward" menu command. - """ - if len(self.selection) != 1: return + """ Respond to the "Move Backward" menu command. + """ + if len(self.selection) != 1: return - self._saveUndoInfo() + self._saveUndoInfo() - obj = self.selection[0] - index = self.contents.index(obj) - if index == len(self.contents) - 1: return + obj = self.selection[0] + index = self.contents.index(obj) + if index == len(self.contents) - 1: return - del self.contents[index] - self.contents.insert(index+1, obj) + del self.contents[index] + self.contents.insert(index+1, obj) - self.drawPanel.Refresh() - self._adjustMenus() + self.drawPanel.Refresh() + self._adjustMenus() def doMoveToBack(self, event): - """ Respond to the "Move to Back" menu command. - """ - if len(self.selection) != 1: return + """ Respond to the "Move to Back" menu command. + """ + if len(self.selection) != 1: return - self._saveUndoInfo() + self._saveUndoInfo() - obj = self.selection[0] - self.contents.remove(obj) - self.contents.append(obj) + obj = self.selection[0] + self.contents.remove(obj) + self.contents.append(obj) - self.drawPanel.Refresh() - self._adjustMenus() + self.drawPanel.Refresh() + self._adjustMenus() def doShowAbout(self, event): - """ Respond to the "About pySketch" menu command. - """ - dialog = wxDialog(self, -1, "About pySketch") # , - #style=wxDIALOG_MODAL | wxSTAY_ON_TOP) - dialog.SetBackgroundColour(wxWHITE) + """ Respond to the "About pySketch" menu command. + """ + dialog = wxDialog(self, -1, "About pySketch") # , + #style=wxDIALOG_MODAL | wxSTAY_ON_TOP) + dialog.SetBackgroundColour(wxWHITE) - panel = wxPanel(dialog, -1) - panel.SetBackgroundColour(wxWHITE) + panel = wxPanel(dialog, -1) + panel.SetBackgroundColour(wxWHITE) - panelSizer = wxBoxSizer(wxVERTICAL) + panelSizer = wxBoxSizer(wxVERTICAL) - boldFont = wxFont(panel.GetFont().GetPointSize(), - panel.GetFont().GetFamily(), - wxNORMAL, wxBOLD) + boldFont = wxFont(panel.GetFont().GetPointSize(), + panel.GetFont().GetFamily(), + wxNORMAL, wxBOLD) - logo = wxStaticBitmap(panel, -1, wxBitmap("images/logo.bmp", - wxBITMAP_TYPE_BMP)) + logo = wxStaticBitmap(panel, -1, wxBitmap("images/logo.bmp", + wxBITMAP_TYPE_BMP)) - lab1 = wxStaticText(panel, -1, "pySketch") - lab1.SetFont(wxFont(36, boldFont.GetFamily(), wxITALIC, wxBOLD)) - lab1.SetSize(lab1.GetBestSize()) + lab1 = wxStaticText(panel, -1, "pySketch") + lab1.SetFont(wxFont(36, boldFont.GetFamily(), wxITALIC, wxBOLD)) + lab1.SetSize(lab1.GetBestSize()) - imageSizer = wxBoxSizer(wxHORIZONTAL) - imageSizer.Add(logo, 0, wxALL | wxALIGN_CENTRE_VERTICAL, 5) - imageSizer.Add(lab1, 0, wxALL | wxALIGN_CENTRE_VERTICAL, 5) + imageSizer = wxBoxSizer(wxHORIZONTAL) + imageSizer.Add(logo, 0, wxALL | wxALIGN_CENTRE_VERTICAL, 5) + imageSizer.Add(lab1, 0, wxALL | wxALIGN_CENTRE_VERTICAL, 5) - lab2 = wxStaticText(panel, -1, "A simple object-oriented drawing " + \ - "program.") - lab2.SetFont(boldFont) - lab2.SetSize(lab2.GetBestSize()) + lab2 = wxStaticText(panel, -1, "A simple object-oriented drawing " + \ + "program.") + lab2.SetFont(boldFont) + lab2.SetSize(lab2.GetBestSize()) - lab3 = wxStaticText(panel, -1, "pySketch is completely free " + \ - "software; please") - lab3.SetFont(boldFont) - lab3.SetSize(lab3.GetBestSize()) + lab3 = wxStaticText(panel, -1, "pySketch is completely free " + \ + "software; please") + lab3.SetFont(boldFont) + lab3.SetSize(lab3.GetBestSize()) - lab4 = wxStaticText(panel, -1, "feel free to adapt or use this " + \ - "in any way you like.") - lab4.SetFont(boldFont) - lab4.SetSize(lab4.GetBestSize()) + lab4 = wxStaticText(panel, -1, "feel free to adapt or use this " + \ + "in any way you like.") + lab4.SetFont(boldFont) + lab4.SetSize(lab4.GetBestSize()) - lab5 = wxStaticText(panel, -1, "Author: Erik Westra " + \ - "(ewestra@wave.co.nz)") - lab5.SetFont(boldFont) - lab5.SetSize(lab5.GetBestSize()) + lab5 = wxStaticText(panel, -1, "Author: Erik Westra " + \ + "(ewestra@wave.co.nz)") + lab5.SetFont(boldFont) + lab5.SetSize(lab5.GetBestSize()) - btnOK = wxButton(panel, wxID_OK, "OK") + btnOK = wxButton(panel, wxID_OK, "OK") - panelSizer.Add(imageSizer, 0, wxALIGN_CENTRE) - panelSizer.Add(10, 10) # Spacer. - panelSizer.Add(lab2, 0, wxALIGN_CENTRE) - panelSizer.Add(10, 10) # Spacer. - panelSizer.Add(lab3, 0, wxALIGN_CENTRE) - panelSizer.Add(lab4, 0, wxALIGN_CENTRE) - panelSizer.Add(10, 10) # Spacer. - panelSizer.Add(lab5, 0, wxALIGN_CENTRE) - panelSizer.Add(10, 10) # Spacer. - panelSizer.Add(btnOK, 0, wxALL | wxALIGN_CENTRE, 5) + panelSizer.Add(imageSizer, 0, wxALIGN_CENTRE) + panelSizer.Add(10, 10) # Spacer. + panelSizer.Add(lab2, 0, wxALIGN_CENTRE) + panelSizer.Add(10, 10) # Spacer. + panelSizer.Add(lab3, 0, wxALIGN_CENTRE) + panelSizer.Add(lab4, 0, wxALIGN_CENTRE) + panelSizer.Add(10, 10) # Spacer. + panelSizer.Add(lab5, 0, wxALIGN_CENTRE) + panelSizer.Add(10, 10) # Spacer. + panelSizer.Add(btnOK, 0, wxALL | wxALIGN_CENTRE, 5) - panel.SetAutoLayout(true) - panel.SetSizer(panelSizer) - panelSizer.Fit(panel) + panel.SetAutoLayout(true) + panel.SetSizer(panelSizer) + panelSizer.Fit(panel) - topSizer = wxBoxSizer(wxHORIZONTAL) - topSizer.Add(panel, 0, wxALL, 10) + topSizer = wxBoxSizer(wxHORIZONTAL) + topSizer.Add(panel, 0, wxALL, 10) - dialog.SetAutoLayout(true) - dialog.SetSizer(topSizer) - topSizer.Fit(dialog) + dialog.SetAutoLayout(true) + dialog.SetSizer(topSizer) + topSizer.Fit(dialog) - dialog.Centre() + dialog.Centre() - btn = dialog.ShowModal() - dialog.Destroy() + btn = dialog.ShowModal() + dialog.Destroy() # ============================= # == Object Creation Methods == # ============================= def createLine(self, x1, y1, x2, y2): - """ Create a new line object at the given position and size. - """ - self._saveUndoInfo() + """ Create a new line object at the given position and size. + """ + self._saveUndoInfo() - topLeftX = min(x1, x2) - topLeftY = min(y1, y2) - botRightX = max(x1, x2) - botRightY = max(y1, y2) + topLeftX = min(x1, x2) + topLeftY = min(y1, y2) + botRightX = max(x1, x2) + botRightY = max(y1, y2) - obj = DrawingObject(obj_LINE, position=wxPoint(topLeftX, topLeftY), - size=wxSize(botRightX-topLeftX, - botRightY-topLeftY), - penColour=self.penColour, - fillColour=self.fillColour, - lineSize=self.lineSize, - startPt = wxPoint(x1 - topLeftX, y1 - topLeftY), - endPt = wxPoint(x2 - topLeftX, y2 - topLeftY)) - self.contents.insert(0, obj) - self.dirty = true - self.doChooseSelectTool() - self.select(obj) + obj = DrawingObject(obj_LINE, position=wxPoint(topLeftX, topLeftY), + size=wxSize(botRightX-topLeftX, + botRightY-topLeftY), + penColour=self.penColour, + fillColour=self.fillColour, + lineSize=self.lineSize, + startPt = wxPoint(x1 - topLeftX, y1 - topLeftY), + endPt = wxPoint(x2 - topLeftX, y2 - topLeftY)) + self.contents.insert(0, obj) + self.dirty = true + self.doChooseSelectTool() + self.select(obj) def createRect(self, x, y, width, height): - """ Create a new rectangle object at the given position and size. - """ - self._saveUndoInfo() + """ Create a new rectangle object at the given position and size. + """ + self._saveUndoInfo() - obj = DrawingObject(obj_RECT, position=wxPoint(x, y), - size=wxSize(width, height), - penColour=self.penColour, - fillColour=self.fillColour, - lineSize=self.lineSize) - self.contents.insert(0, obj) - self.dirty = true - self.doChooseSelectTool() - self.select(obj) + obj = DrawingObject(obj_RECT, position=wxPoint(x, y), + size=wxSize(width, height), + penColour=self.penColour, + fillColour=self.fillColour, + lineSize=self.lineSize) + self.contents.insert(0, obj) + self.dirty = true + self.doChooseSelectTool() + self.select(obj) def createEllipse(self, x, y, width, height): - """ Create a new ellipse object at the given position and size. - """ - self._saveUndoInfo() + """ Create a new ellipse object at the given position and size. + """ + self._saveUndoInfo() - obj = DrawingObject(obj_ELLIPSE, position=wxPoint(x, y), - size=wxSize(width, height), - penColour=self.penColour, - fillColour=self.fillColour, - lineSize=self.lineSize) - self.contents.insert(0, obj) - self.dirty = true - self.doChooseSelectTool() - self.select(obj) + obj = DrawingObject(obj_ELLIPSE, position=wxPoint(x, y), + size=wxSize(width, height), + penColour=self.penColour, + fillColour=self.fillColour, + lineSize=self.lineSize) + self.contents.insert(0, obj) + self.dirty = true + self.doChooseSelectTool() + self.select(obj) def createText(self, x, y, width, height): - """ Create a new text object at the given position and size. - """ - editor = EditTextObjectDialog(self, "Create Text Object") - if editor.ShowModal() == wxID_CANCEL: - editor.Destroy() - return + """ Create a new text object at the given position and size. + """ + editor = EditTextObjectDialog(self, "Create Text Object") + if editor.ShowModal() == wxID_CANCEL: + editor.Destroy() + return - self._saveUndoInfo() + self._saveUndoInfo() - obj = DrawingObject(obj_TEXT, position=wxPoint(x, y), - size=wxSize(width, height)) - editor.dialogToObject(obj) - editor.Destroy() + obj = DrawingObject(obj_TEXT, position=wxPoint(x, y), + size=wxSize(width, height)) + editor.dialogToObject(obj) + editor.Destroy() - self.contents.insert(0, obj) - self.dirty = true - self.doChooseSelectTool() - self.select(obj) + self.contents.insert(0, obj) + self.dirty = true + self.doChooseSelectTool() + self.select(obj) # ======================= # == Selection Methods == # ======================= def selectAll(self): - """ Select every DrawingObject in our document. - """ - self.selection = [] - for obj in self.contents: - self.selection.append(obj) - self.drawPanel.Refresh() - self._adjustMenus() + """ Select every DrawingObject in our document. + """ + self.selection = [] + for obj in self.contents: + self.selection.append(obj) + self.drawPanel.Refresh() + self._adjustMenus() def deselectAll(self): - """ Deselect every DrawingObject in our document. - """ - self.selection = [] - self.drawPanel.Refresh() - self._adjustMenus() + """ Deselect every DrawingObject in our document. + """ + self.selection = [] + self.drawPanel.Refresh() + self._adjustMenus() def select(self, obj): - """ Select the given DrawingObject within our document. - """ - self.selection = [obj] - self.drawPanel.Refresh() - self._adjustMenus() + """ Select the given DrawingObject within our document. + """ + self.selection = [obj] + self.drawPanel.Refresh() + self._adjustMenus() def selectMany(self, objs): - """ Select the given list of DrawingObjects. - """ - self.selection = objs - self.drawPanel.Refresh() - self._adjustMenus() + """ Select the given list of DrawingObjects. + """ + self.selection = objs + self.drawPanel.Refresh() + self._adjustMenus() def selectByRectangle(self, x, y, width, height): - """ Select every DrawingObject in the given rectangular region. - """ - self.selection = [] - for obj in self.contents: - if obj.objectWithinRect(x, y, width, height): - self.selection.append(obj) - self.drawPanel.Refresh() - self._adjustMenus() + """ Select every DrawingObject in the given rectangular region. + """ + self.selection = [] + for obj in self.contents: + if obj.objectWithinRect(x, y, width, height): + self.selection.append(obj) + self.drawPanel.Refresh() + self._adjustMenus() # ====================== # == File I/O Methods == # ====================== def loadContents(self): - """ Load the contents of our document into memory. - """ - f = open(self.fileName, "rb") - objData = cPickle.load(f) - f.close() + """ Load the contents of our document into memory. + """ + f = open(self.fileName, "rb") + objData = cPickle.load(f) + f.close() - for type, data in objData: - obj = DrawingObject(type) - obj.setData(data) - self.contents.append(obj) + for type, data in objData: + obj = DrawingObject(type) + obj.setData(data) + self.contents.append(obj) - self.dirty = false - self.selection = [] - self.undoInfo = None + self.dirty = false + self.selection = [] + self.undoInfo = None - self.drawPanel.Refresh() - self._adjustMenus() + self.drawPanel.Refresh() + self._adjustMenus() def saveContents(self): - """ Save the contents of our document to disk. - """ - objData = [] - for obj in self.contents: - objData.append([obj.getType(), obj.getData()]) + """ Save the contents of our document to disk. + """ + objData = [] + for obj in self.contents: + objData.append([obj.getType(), obj.getData()]) - f = open(self.fileName, "wb") - cPickle.dump(objData, f) - f.close() + f = open(self.fileName, "wb") + cPickle.dump(objData, f) + f.close() - self.dirty = false + self.dirty = false def askIfUserWantsToSave(self, action): - """ Give the user the opportunity to save the current document. + """ Give the user the opportunity to save the current document. - 'action' is a string describing the action about to be taken. If - the user wants to save the document, it is saved immediately. If - the user cancels, we return false. - """ - if not self.dirty: return true # Nothing to do. + 'action' is a string describing the action about to be taken. If + the user wants to save the document, it is saved immediately. If + the user cancels, we return false. + """ + if not self.dirty: return true # Nothing to do. - response = wxMessageBox("Save changes before " + action + "?", - "Confirm", wxYES_NO | wxCANCEL, self) + response = wxMessageBox("Save changes before " + action + "?", + "Confirm", wxYES_NO | wxCANCEL, self) - if response == wxYES: - if self.fileName == None: - fileName = wxFileSelector("Save File As", "Saving", - default_extension="psk", - wildcard="*.psk", - flags = wxSAVE | wxOVERWRITE_PROMPT) - if fileName == "": return false # User cancelled. - self.fileName = fileName + if response == wxYES: + if self.fileName == None: + fileName = wxFileSelector("Save File As", "Saving", + default_extension="psk", + wildcard="*.psk", + flags = wxSAVE | wxOVERWRITE_PROMPT) + if fileName == "": return false # User cancelled. + self.fileName = fileName - self.saveContents() - return true - elif response == wxNO: - return true # User doesn't want changes saved. - elif response == wxCANCEL: - return false # User cancelled. + self.saveContents() + return true + elif response == wxNO: + return true # User doesn't want changes saved. + elif response == wxCANCEL: + return false # User cancelled. # ===================== # == Private Methods == # ===================== def _adjustMenus(self): - """ Adjust our menus and toolbar to reflect the current state of the - world. - """ - canSave = (self.fileName != None) and self.dirty - canRevert = (self.fileName != None) and self.dirty - canUndo = self.undoInfo != None - selection = len(self.selection) > 0 - onlyOne = len(self.selection) == 1 - isText = onlyOne and (self.selection[0].getType() == obj_TEXT) - front = onlyOne and (self.selection[0] == self.contents[0]) - back = onlyOne and (self.selection[0] == self.contents[-1]) + """ Adjust our menus and toolbar to reflect the current state of the + world. + """ + canSave = (self.fileName != None) and self.dirty + canRevert = (self.fileName != None) and self.dirty + canUndo = self.undoInfo != None + selection = len(self.selection) > 0 + onlyOne = len(self.selection) == 1 + isText = onlyOne and (self.selection[0].getType() == obj_TEXT) + front = onlyOne and (self.selection[0] == self.contents[0]) + back = onlyOne and (self.selection[0] == self.contents[-1]) - # Enable/disable our menu items. + # Enable/disable our menu items. - self.fileMenu.Enable(wxID_SAVE, canSave) - self.fileMenu.Enable(wxID_REVERT, canRevert) + self.fileMenu.Enable(wxID_SAVE, canSave) + self.fileMenu.Enable(wxID_REVERT, canRevert) - self.editMenu.Enable(menu_UNDO, canUndo) - self.editMenu.Enable(menu_DUPLICATE, selection) - self.editMenu.Enable(menu_EDIT_TEXT, isText) - self.editMenu.Enable(menu_DELETE, selection) + self.editMenu.Enable(menu_UNDO, canUndo) + self.editMenu.Enable(menu_DUPLICATE, selection) + self.editMenu.Enable(menu_EDIT_TEXT, isText) + self.editMenu.Enable(menu_DELETE, selection) - self.toolsMenu.Check(menu_SELECT, self.curTool == self.selectIcon) - self.toolsMenu.Check(menu_LINE, self.curTool == self.lineIcon) - self.toolsMenu.Check(menu_RECT, self.curTool == self.rectIcon) - self.toolsMenu.Check(menu_ELLIPSE, self.curTool == self.ellipseIcon) - self.toolsMenu.Check(menu_TEXT, self.curTool == self.textIcon) + self.toolsMenu.Check(menu_SELECT, self.curTool == self.selectIcon) + self.toolsMenu.Check(menu_LINE, self.curTool == self.lineIcon) + self.toolsMenu.Check(menu_RECT, self.curTool == self.rectIcon) + self.toolsMenu.Check(menu_ELLIPSE, self.curTool == self.ellipseIcon) + self.toolsMenu.Check(menu_TEXT, self.curTool == self.textIcon) - self.objectMenu.Enable(menu_MOVE_FORWARD, onlyOne and not front) - self.objectMenu.Enable(menu_MOVE_TO_FRONT, onlyOne and not front) - self.objectMenu.Enable(menu_MOVE_BACKWARD, onlyOne and not back) - self.objectMenu.Enable(menu_MOVE_TO_BACK, onlyOne and not back) + self.objectMenu.Enable(menu_MOVE_FORWARD, onlyOne and not front) + self.objectMenu.Enable(menu_MOVE_TO_FRONT, onlyOne and not front) + self.objectMenu.Enable(menu_MOVE_BACKWARD, onlyOne and not back) + self.objectMenu.Enable(menu_MOVE_TO_BACK, onlyOne and not back) - # Enable/disable our toolbar icons. + # Enable/disable our toolbar icons. - self.toolbar.EnableTool(wxID_NEW, true) - self.toolbar.EnableTool(wxID_OPEN, true) - self.toolbar.EnableTool(wxID_SAVE, canSave) - self.toolbar.EnableTool(menu_UNDO, canUndo) - self.toolbar.EnableTool(menu_DUPLICATE, selection) - self.toolbar.EnableTool(menu_MOVE_FORWARD, onlyOne and not front) - self.toolbar.EnableTool(menu_MOVE_BACKWARD, onlyOne and not back) + self.toolbar.EnableTool(wxID_NEW, true) + self.toolbar.EnableTool(wxID_OPEN, true) + self.toolbar.EnableTool(wxID_SAVE, canSave) + self.toolbar.EnableTool(menu_UNDO, canUndo) + self.toolbar.EnableTool(menu_DUPLICATE, selection) + self.toolbar.EnableTool(menu_MOVE_FORWARD, onlyOne and not front) + self.toolbar.EnableTool(menu_MOVE_BACKWARD, onlyOne and not back) def _setCurrentTool(self, newToolIcon): - """ Set the currently selected tool. - """ - if self.curTool == newToolIcon: return # Nothing to do. + """ Set the currently selected tool. + """ + if self.curTool == newToolIcon: return # Nothing to do. - if self.curTool != None: - self.curTool.deselect() + if self.curTool != None: + self.curTool.deselect() - newToolIcon.select() - self.curTool = newToolIcon + newToolIcon.select() + self.curTool = newToolIcon def _setPenColour(self, colour): - """ Set the default or selected object's pen colour. - """ - if len(self.selection) > 0: - self._saveUndoInfo() - for obj in self.selection: - obj.setPenColour(colour) - self.drawPanel.Refresh() - else: - self.penColour = colour - self.optionIndicator.setPenColour(colour) + """ Set the default or selected object's pen colour. + """ + if len(self.selection) > 0: + self._saveUndoInfo() + for obj in self.selection: + obj.setPenColour(colour) + self.drawPanel.Refresh() + else: + self.penColour = colour + self.optionIndicator.setPenColour(colour) def _setFillColour(self, colour): - """ Set the default or selected object's fill colour. - """ - if len(self.selection) > 0: - self._saveUndoInfo() - for obj in self.selection: - obj.setFillColour(colour) - self.drawPanel.Refresh() - else: - self.fillColour = colour - self.optionIndicator.setFillColour(colour) + """ Set the default or selected object's fill colour. + """ + if len(self.selection) > 0: + self._saveUndoInfo() + for obj in self.selection: + obj.setFillColour(colour) + self.drawPanel.Refresh() + else: + self.fillColour = colour + self.optionIndicator.setFillColour(colour) def _setLineSize(self, size): - """ Set the default or selected object's line size. - """ - if len(self.selection) > 0: - self._saveUndoInfo() - for obj in self.selection: - obj.setLineSize(size) - self.drawPanel.Refresh() - else: - self.lineSize = size - self.optionIndicator.setLineSize(size) + """ Set the default or selected object's line size. + """ + if len(self.selection) > 0: + self._saveUndoInfo() + for obj in self.selection: + obj.setLineSize(size) + self.drawPanel.Refresh() + else: + self.lineSize = size + self.optionIndicator.setLineSize(size) def _saveUndoInfo(self): - """ Remember the current state of the document, to allow for undo. + """ Remember the current state of the document, to allow for undo. - We make a copy of the document's contents, so that we can return to - the previous contents if the user does something and then wants to - undo the operation. - """ - savedContents = [] - for obj in self.contents: - savedContents.append([obj.getType(), obj.getData()]) + We make a copy of the document's contents, so that we can return to + the previous contents if the user does something and then wants to + undo the operation. + """ + savedContents = [] + for obj in self.contents: + savedContents.append([obj.getType(), obj.getData()]) - savedSelection = [] - for i in range(len(self.contents)): - if self.contents[i] in self.selection: - savedSelection.append(i) + savedSelection = [] + for i in range(len(self.contents)): + if self.contents[i] in self.selection: + savedSelection.append(i) - self.undoInfo = {"contents" : savedContents, - "selection" : savedSelection} + self.undoInfo = {"contents" : savedContents, + "selection" : savedSelection} def _resizeObject(self, obj, anchorPt, oldPt, newPt): - """ Resize the given object. + """ Resize the given object. - 'anchorPt' is the unchanging corner of the object, while the - opposite corner has been resized. 'oldPt' are the current - coordinates for this corner, while 'newPt' are the new coordinates. - The object should fit within the given dimensions, though if the - new point is less than the anchor point the object will need to be - moved as well as resized, to avoid giving it a negative size. - """ - if obj.getType() == obj_TEXT: - # Not allowed to resize text objects -- they're sized to fit text. - wxBell() - return + 'anchorPt' is the unchanging corner of the object, while the + opposite corner has been resized. 'oldPt' are the current + coordinates for this corner, while 'newPt' are the new coordinates. + The object should fit within the given dimensions, though if the + new point is less than the anchor point the object will need to be + moved as well as resized, to avoid giving it a negative size. + """ + if obj.getType() == obj_TEXT: + # Not allowed to resize text objects -- they're sized to fit text. + wxBell() + return - self._saveUndoInfo() + self._saveUndoInfo() - topLeft = wxPoint(min(anchorPt.x, newPt.x), - min(anchorPt.y, newPt.y)) - botRight = wxPoint(max(anchorPt.x, newPt.x), - max(anchorPt.y, newPt.y)) + topLeft = wxPoint(min(anchorPt.x, newPt.x), + min(anchorPt.y, newPt.y)) + botRight = wxPoint(max(anchorPt.x, newPt.x), + max(anchorPt.y, newPt.y)) - newWidth = botRight.x - topLeft.x - newHeight = botRight.y - topLeft.y + newWidth = botRight.x - topLeft.x + newHeight = botRight.y - topLeft.y - if obj.getType() == obj_LINE: - # Adjust the line so that its start and end points match the new - # overall object size. + if obj.getType() == obj_LINE: + # Adjust the line so that its start and end points match the new + # overall object size. - startPt = obj.getStartPt() - endPt = obj.getEndPt() + startPt = obj.getStartPt() + endPt = obj.getEndPt() - slopesDown = ((startPt.x < endPt.x) and (startPt.y < endPt.y)) or \ - ((startPt.x > endPt.x) and (startPt.y > endPt.y)) + slopesDown = ((startPt.x < endPt.x) and (startPt.y < endPt.y)) or \ + ((startPt.x > endPt.x) and (startPt.y > endPt.y)) - # Handle the user flipping the line. + # Handle the user flipping the line. - hFlip = ((anchorPt.x < oldPt.x) and (anchorPt.x > newPt.x)) or \ - ((anchorPt.x > oldPt.x) and (anchorPt.x < newPt.x)) - vFlip = ((anchorPt.y < oldPt.y) and (anchorPt.y > newPt.y)) or \ - ((anchorPt.y > oldPt.y) and (anchorPt.y < newPt.y)) + hFlip = ((anchorPt.x < oldPt.x) and (anchorPt.x > newPt.x)) or \ + ((anchorPt.x > oldPt.x) and (anchorPt.x < newPt.x)) + vFlip = ((anchorPt.y < oldPt.y) and (anchorPt.y > newPt.y)) or \ + ((anchorPt.y > oldPt.y) and (anchorPt.y < newPt.y)) - if (hFlip and not vFlip) or (vFlip and not hFlip): - slopesDown = not slopesDown # Line flipped. + if (hFlip and not vFlip) or (vFlip and not hFlip): + slopesDown = not slopesDown # Line flipped. - if slopesDown: - obj.setStartPt(wxPoint(0, 0)) - obj.setEndPt(wxPoint(newWidth, newHeight)) - else: - obj.setStartPt(wxPoint(0, newHeight)) - obj.setEndPt(wxPoint(newWidth, 0)) + if slopesDown: + obj.setStartPt(wxPoint(0, 0)) + obj.setEndPt(wxPoint(newWidth, newHeight)) + else: + obj.setStartPt(wxPoint(0, newHeight)) + obj.setEndPt(wxPoint(newWidth, 0)) - # Finally, adjust the bounds of the object to match the new dimensions. + # Finally, adjust the bounds of the object to match the new dimensions. - obj.setPosition(topLeft) - obj.setSize(wxSize(botRight.x - topLeft.x, botRight.y - topLeft.y)) + obj.setPosition(topLeft) + obj.setSize(wxSize(botRight.x - topLeft.x, botRight.y - topLeft.y)) - self.drawPanel.Refresh() + self.drawPanel.Refresh() def _moveObject(self, offsetX, offsetY): - """ Move the currently selected object(s) by the given offset. - """ - self._saveUndoInfo() + """ Move the currently selected object(s) by the given offset. + """ + self._saveUndoInfo() - for obj in self.selection: - pos = obj.getPosition() - pos.x = pos.x + offsetX - pos.y = pos.y + offsetY - obj.setPosition(pos) + for obj in self.selection: + pos = obj.getPosition() + pos.x = pos.x + offsetX + pos.y = pos.y + offsetY + obj.setPosition(pos) - self.drawPanel.Refresh() + self.drawPanel.Refresh() def _buildLineSizePopup(self, lineSize): - """ Build the pop-up menu used to set the line size. + """ Build the pop-up menu used to set the line size. - 'lineSize' is the current line size value. The corresponding item - is checked in the pop-up menu. - """ - menu = wxMenu() - menu.Append(id_LINESIZE_0, "no line", kind=wxITEM_CHECK) - menu.Append(id_LINESIZE_1, "1-pixel line", kind=wxITEM_CHECK) - menu.Append(id_LINESIZE_2, "2-pixel line", kind=wxITEM_CHECK) - menu.Append(id_LINESIZE_3, "3-pixel line", kind=wxITEM_CHECK) - menu.Append(id_LINESIZE_4, "4-pixel line", kind=wxITEM_CHECK) - menu.Append(id_LINESIZE_5, "5-pixel line", kind=wxITEM_CHECK) + 'lineSize' is the current line size value. The corresponding item + is checked in the pop-up menu. + """ + menu = wxMenu() + menu.Append(id_LINESIZE_0, "no line", kind=wxITEM_CHECK) + menu.Append(id_LINESIZE_1, "1-pixel line", kind=wxITEM_CHECK) + menu.Append(id_LINESIZE_2, "2-pixel line", kind=wxITEM_CHECK) + menu.Append(id_LINESIZE_3, "3-pixel line", kind=wxITEM_CHECK) + menu.Append(id_LINESIZE_4, "4-pixel line", kind=wxITEM_CHECK) + menu.Append(id_LINESIZE_5, "5-pixel line", kind=wxITEM_CHECK) - if lineSize == 0: menu.Check(id_LINESIZE_0, true) - elif lineSize == 1: menu.Check(id_LINESIZE_1, true) - elif lineSize == 2: menu.Check(id_LINESIZE_2, true) - elif lineSize == 3: menu.Check(id_LINESIZE_3, true) - elif lineSize == 4: menu.Check(id_LINESIZE_4, true) - elif lineSize == 5: menu.Check(id_LINESIZE_5, true) + if lineSize == 0: menu.Check(id_LINESIZE_0, true) + elif lineSize == 1: menu.Check(id_LINESIZE_1, true) + elif lineSize == 2: menu.Check(id_LINESIZE_2, true) + elif lineSize == 3: menu.Check(id_LINESIZE_3, true) + elif lineSize == 4: menu.Check(id_LINESIZE_4, true) + elif lineSize == 5: menu.Check(id_LINESIZE_5, true) - EVT_MENU(self, id_LINESIZE_0, self._lineSizePopupSelected) - EVT_MENU(self, id_LINESIZE_1, self._lineSizePopupSelected) - EVT_MENU(self, id_LINESIZE_2, self._lineSizePopupSelected) - EVT_MENU(self, id_LINESIZE_3, self._lineSizePopupSelected) - EVT_MENU(self, id_LINESIZE_4, self._lineSizePopupSelected) - EVT_MENU(self, id_LINESIZE_5, self._lineSizePopupSelected) + EVT_MENU(self, id_LINESIZE_0, self._lineSizePopupSelected) + EVT_MENU(self, id_LINESIZE_1, self._lineSizePopupSelected) + EVT_MENU(self, id_LINESIZE_2, self._lineSizePopupSelected) + EVT_MENU(self, id_LINESIZE_3, self._lineSizePopupSelected) + EVT_MENU(self, id_LINESIZE_4, self._lineSizePopupSelected) + EVT_MENU(self, id_LINESIZE_5, self._lineSizePopupSelected) - return menu + return menu def _lineSizePopupSelected(self, event): - """ Respond to the user selecting an item from the line size popup menu - """ - id = event.GetId() - if id == id_LINESIZE_0: self._setLineSize(0) - elif id == id_LINESIZE_1: self._setLineSize(1) - elif id == id_LINESIZE_2: self._setLineSize(2) - elif id == id_LINESIZE_3: self._setLineSize(3) - elif id == id_LINESIZE_4: self._setLineSize(4) - elif id == id_LINESIZE_5: self._setLineSize(5) - else: - wxBell() - return + """ Respond to the user selecting an item from the line size popup menu + """ + id = event.GetId() + if id == id_LINESIZE_0: self._setLineSize(0) + elif id == id_LINESIZE_1: self._setLineSize(1) + elif id == id_LINESIZE_2: self._setLineSize(2) + elif id == id_LINESIZE_3: self._setLineSize(3) + elif id == id_LINESIZE_4: self._setLineSize(4) + elif id == id_LINESIZE_5: self._setLineSize(5) + else: + wxBell() + return - self.optionIndicator.setLineSize(self.lineSize) + self.optionIndicator.setLineSize(self.lineSize) def _getEventCoordinates(self, event): - """ Return the coordinates associated with the given mouse event. + """ Return the coordinates associated with the given mouse event. - The coordinates have to be adjusted to allow for the current scroll - position. - """ + The coordinates have to be adjusted to allow for the current scroll + position. + """ originX, originY = self.drawPanel.GetViewStart() unitX, unitY = self.drawPanel.GetScrollPixelsPerUnit() return wxPoint(event.GetX() + (originX * unitX), - event.GetY() + (originY * unitY)) + event.GetY() + (originY * unitY)) def _getObjectAndSelectionHandleAt(self, pt): - """ Return the object and selection handle at the given point. + """ Return the object and selection handle at the given point. - We draw selection handles (small rectangles) around the currently - selected object(s). If the given point is within one of the - selection handle rectangles, we return the associated object and a - code indicating which selection handle the point is in. If the - point isn't within any selection handle at all, we return the tuple - (None, handle_NONE). - """ - for obj in self.selection: - handle = obj.getSelectionHandleContainingPoint(pt.x, pt.y) - if handle != handle_NONE: - return obj, handle + We draw selection handles (small rectangles) around the currently + selected object(s). If the given point is within one of the + selection handle rectangles, we return the associated object and a + code indicating which selection handle the point is in. If the + point isn't within any selection handle at all, we return the tuple + (None, handle_NONE). + """ + for obj in self.selection: + handle = obj.getSelectionHandleContainingPoint(pt.x, pt.y) + if handle != handle_NONE: + return obj, handle - return None, handle_NONE + return None, handle_NONE def _getObjectAt(self, pt): - """ Return the first object found which is at the given point. - """ - for obj in self.contents: - if obj.objectContainsPoint(pt.x, pt.y): - return obj - return None + """ Return the first object found which is at the given point. + """ + for obj in self.contents: + if obj.objectContainsPoint(pt.x, pt.y): + return obj + return None def _drawObjectOutline(self, offsetX, offsetY): - """ Draw an outline of the currently selected object. + """ Draw an outline of the currently selected object. - The selected object's outline is drawn at the object's position - plus the given offset. + The selected object's outline is drawn at the object's position + plus the given offset. - Note that the outline is drawn by *inverting* the window's - contents, so calling _drawObjectOutline twice in succession will - restore the window's contents back to what they were previously. - """ - if len(self.selection) != 1: return + Note that the outline is drawn by *inverting* the window's + contents, so calling _drawObjectOutline twice in succession will + restore the window's contents back to what they were previously. + """ + if len(self.selection) != 1: return - position = self.selection[0].getPosition() - size = self.selection[0].getSize() + position = self.selection[0].getPosition() + size = self.selection[0].getSize() - dc = wxClientDC(self.drawPanel) - self.drawPanel.PrepareDC(dc) - dc.BeginDrawing() - dc.SetPen(wxBLACK_DASHED_PEN) - dc.SetBrush(wxTRANSPARENT_BRUSH) - dc.SetLogicalFunction(wxINVERT) + dc = wxClientDC(self.drawPanel) + self.drawPanel.PrepareDC(dc) + dc.BeginDrawing() + dc.SetPen(wxBLACK_DASHED_PEN) + dc.SetBrush(wxTRANSPARENT_BRUSH) + dc.SetLogicalFunction(wxINVERT) - dc.DrawRectangle(position.x + offsetX, position.y + offsetY, - size.width, size.height) + dc.DrawRectangle(position.x + offsetX, position.y + offsetY, + size.width, size.height) - dc.EndDrawing() + dc.EndDrawing() def _drawVisualFeedback(self, startPt, endPt, type, dashedLine): - """ Draw visual feedback for a drawing operation. + """ Draw visual feedback for a drawing operation. - The visual feedback consists of a line, ellipse, or rectangle based - around the two given points. 'type' should be one of the following - predefined feedback type constants: + The visual feedback consists of a line, ellipse, or rectangle based + around the two given points. 'type' should be one of the following + predefined feedback type constants: - feedback_RECT -> draw rectangular feedback. - feedback_LINE -> draw line feedback. - feedback_ELLIPSE -> draw elliptical feedback. + feedback_RECT -> draw rectangular feedback. + feedback_LINE -> draw line feedback. + feedback_ELLIPSE -> draw elliptical feedback. - if 'dashedLine' is true, the feedback is drawn as a dashed rather - than a solid line. + if 'dashedLine' is true, the feedback is drawn as a dashed rather + than a solid line. - Note that the feedback is drawn by *inverting* the window's - contents, so calling _drawVisualFeedback twice in succession will - restore the window's contents back to what they were previously. - """ - dc = wxClientDC(self.drawPanel) - self.drawPanel.PrepareDC(dc) - dc.BeginDrawing() - if dashedLine: - dc.SetPen(wxBLACK_DASHED_PEN) - else: - dc.SetPen(wxBLACK_PEN) - dc.SetBrush(wxTRANSPARENT_BRUSH) - dc.SetLogicalFunction(wxINVERT) + Note that the feedback is drawn by *inverting* the window's + contents, so calling _drawVisualFeedback twice in succession will + restore the window's contents back to what they were previously. + """ + dc = wxClientDC(self.drawPanel) + self.drawPanel.PrepareDC(dc) + dc.BeginDrawing() + if dashedLine: + dc.SetPen(wxBLACK_DASHED_PEN) + else: + dc.SetPen(wxBLACK_PEN) + dc.SetBrush(wxTRANSPARENT_BRUSH) + dc.SetLogicalFunction(wxINVERT) - if type == feedback_RECT: - dc.DrawRectangle(startPt.x, startPt.y, - endPt.x - startPt.x, - endPt.y - startPt.y) - elif type == feedback_LINE: - dc.DrawLine(startPt.x, startPt.y, endPt.x, endPt.y) - elif type == feedback_ELLIPSE: - dc.DrawEllipse(startPt.x, startPt.y, - endPt.x - startPt.x, - endPt.y - startPt.y) + if type == feedback_RECT: + dc.DrawRectangle(startPt.x, startPt.y, + endPt.x - startPt.x, + endPt.y - startPt.y) + elif type == feedback_LINE: + dc.DrawLine(startPt.x, startPt.y, endPt.x, endPt.y) + elif type == feedback_ELLIPSE: + dc.DrawEllipse(startPt.x, startPt.y, + endPt.x - startPt.x, + endPt.y - startPt.y) - dc.EndDrawing() + dc.EndDrawing() #---------------------------------------------------------------------------- class DrawingObject: """ An object within the drawing panel. - A pySketch document consists of a front-to-back ordered list of - DrawingObjects. Each DrawingObject has the following properties: + A pySketch document consists of a front-to-back ordered list of + DrawingObjects. Each DrawingObject has the following properties: - 'type' What type of object this is (text, line, etc). - 'position' The position of the object within the document. - 'size' The size of the object within the document. - 'penColour' The colour to use for drawing the object's outline. - 'fillColour' Colour to use for drawing object's interior. - 'lineSize' Line width (in pixels) to use for object's outline. - 'startPt' The point, relative to the object's position, where - an obj_LINE object's line should start. - 'endPt' The point, relative to the object's position, where - an obj_LINE object's line should end. - 'text' The object's text (obj_TEXT objects only). - 'textFont' The text object's font name. - 'textSize' The text object's point size. - 'textBoldface' If true, this text object will be drawn in - boldface. - 'textItalic' If true, this text object will be drawn in italic. - 'textUnderline' If true, this text object will be drawn underlined. - """ + 'type' What type of object this is (text, line, etc). + 'position' The position of the object within the document. + 'size' The size of the object within the document. + 'penColour' The colour to use for drawing the object's outline. + 'fillColour' Colour to use for drawing object's interior. + 'lineSize' Line width (in pixels) to use for object's outline. + 'startPt' The point, relative to the object's position, where + an obj_LINE object's line should start. + 'endPt' The point, relative to the object's position, where + an obj_LINE object's line should end. + 'text' The object's text (obj_TEXT objects only). + 'textFont' The text object's font name. + 'textSize' The text object's point size. + 'textBoldface' If true, this text object will be drawn in + boldface. + 'textItalic' If true, this text object will be drawn in italic. + 'textUnderline' If true, this text object will be drawn underlined. + """ # ================== # == Constructors == # ================== def __init__(self, type, position=wxPoint(0, 0), size=wxSize(0, 0), - penColour=wxBLACK, fillColour=wxWHITE, lineSize=1, - text=None, startPt=wxPoint(0, 0), endPt=wxPoint(0,0)): - """ Standard constructor. + penColour=wxBLACK, fillColour=wxWHITE, lineSize=1, + text=None, startPt=wxPoint(0, 0), endPt=wxPoint(0,0)): + """ Standard constructor. - 'type' is the type of object being created. This should be one of - the following constants: + 'type' is the type of object being created. This should be one of + the following constants: - obj_LINE - obj_RECT - obj_ELLIPSE - obj_TEXT + obj_LINE + obj_RECT + obj_ELLIPSE + obj_TEXT - The remaining parameters let you set various options for the newly - created DrawingObject. - """ - self.type = type - self.position = position - self.size = size - self.penColour = penColour - self.fillColour = fillColour - self.lineSize = lineSize - self.startPt = startPt - self.endPt = endPt - self.text = text - self.textFont = wxSystemSettings_GetSystemFont( - wxSYS_DEFAULT_GUI_FONT).GetFaceName() - self.textSize = 12 - self.textBoldface = false - self.textItalic = false - self.textUnderline = false + The remaining parameters let you set various options for the newly + created DrawingObject. + """ + self.type = type + self.position = position + self.size = size + self.penColour = penColour + self.fillColour = fillColour + self.lineSize = lineSize + self.startPt = startPt + self.endPt = endPt + self.text = text + self.textFont = wxSystemSettings_GetSystemFont( + wxSYS_DEFAULT_GUI_FONT).GetFaceName() + self.textSize = 12 + self.textBoldface = false + self.textItalic = false + self.textUnderline = false # ============================= # == Object Property Methods == # ============================= def getData(self): - """ Return a copy of the object's internal data. + """ Return a copy of the object's internal data. - This is used to save this DrawingObject to disk. - """ - return [self.type, self.position.x, self.position.y, - self.size.width, self.size.height, - self.penColour.Red(), - self.penColour.Green(), - self.penColour.Blue(), - self.fillColour.Red(), - self.fillColour.Green(), - self.fillColour.Blue(), - self.lineSize, - self.startPt.x, self.startPt.y, - self.endPt.x, self.endPt.y, - self.text, - self.textFont, - self.textSize, - self.textBoldface, - self.textItalic, - self.textUnderline] + This is used to save this DrawingObject to disk. + """ + return [self.type, self.position.x, self.position.y, + self.size.width, self.size.height, + self.penColour.Red(), + self.penColour.Green(), + self.penColour.Blue(), + self.fillColour.Red(), + self.fillColour.Green(), + self.fillColour.Blue(), + self.lineSize, + self.startPt.x, self.startPt.y, + self.endPt.x, self.endPt.y, + self.text, + self.textFont, + self.textSize, + self.textBoldface, + self.textItalic, + self.textUnderline] def setData(self, data): - """ Set the object's internal data. + """ Set the object's internal data. - 'data' is a copy of the object's saved data, as returned by - getData() above. This is used to restore a previously saved - DrawingObject. - """ - #data = copy.deepcopy(data) # Needed? + 'data' is a copy of the object's saved data, as returned by + getData() above. This is used to restore a previously saved + DrawingObject. + """ + #data = copy.deepcopy(data) # Needed? - self.type = data[0] - self.position = wxPoint(data[1], data[2]) - self.size = wxSize(data[3], data[4]) - self.penColour = wxColour(red=data[5], - green=data[6], - blue=data[7]) - self.fillColour = wxColour(red=data[8], - green=data[9], - blue=data[10]) - self.lineSize = data[11] - self.startPt = wxPoint(data[12], data[13]) - self.endPt = wxPoint(data[14], data[15]) - self.text = data[16] - self.textFont = data[17] - self.textSize = data[18] - self.textBoldface = data[19] - self.textItalic = data[20] - self.textUnderline = data[21] + self.type = data[0] + self.position = wxPoint(data[1], data[2]) + self.size = wxSize(data[3], data[4]) + self.penColour = wxColour(red=data[5], + green=data[6], + blue=data[7]) + self.fillColour = wxColour(red=data[8], + green=data[9], + blue=data[10]) + self.lineSize = data[11] + self.startPt = wxPoint(data[12], data[13]) + self.endPt = wxPoint(data[14], data[15]) + self.text = data[16] + self.textFont = data[17] + self.textSize = data[18] + self.textBoldface = data[19] + self.textItalic = data[20] + self.textUnderline = data[21] def getType(self): - """ Return this DrawingObject's type. - """ - return self.type + """ Return this DrawingObject's type. + """ + return self.type def setPosition(self, position): - """ Set the origin (top-left corner) for this DrawingObject. - """ - self.position = position + """ Set the origin (top-left corner) for this DrawingObject. + """ + self.position = position def getPosition(self): - """ Return this DrawingObject's position. - """ - return self.position + """ Return this DrawingObject's position. + """ + return self.position def setSize(self, size): - """ Set the size for this DrawingObject. - """ - self.size = size + """ Set the size for this DrawingObject. + """ + self.size = size def getSize(self): - """ Return this DrawingObject's size. - """ - return self.size + """ Return this DrawingObject's size. + """ + return self.size def setPenColour(self, colour): - """ Set the pen colour used for this DrawingObject. - """ - self.penColour = colour + """ Set the pen colour used for this DrawingObject. + """ + self.penColour = colour def getPenColour(self): - """ Return this DrawingObject's pen colour. - """ - return self.penColour + """ Return this DrawingObject's pen colour. + """ + return self.penColour def setFillColour(self, colour): - """ Set the fill colour used for this DrawingObject. - """ - self.fillColour = colour + """ Set the fill colour used for this DrawingObject. + """ + self.fillColour = colour def getFillColour(self): - """ Return this DrawingObject's fill colour. - """ - return self.fillColour + """ Return this DrawingObject's fill colour. + """ + return self.fillColour def setLineSize(self, lineSize): - """ Set the linesize used for this DrawingObject. - """ - self.lineSize = lineSize + """ Set the linesize used for this DrawingObject. + """ + self.lineSize = lineSize def getLineSize(self): - """ Return this DrawingObject's line size. - """ - return self.lineSize + """ Return this DrawingObject's line size. + """ + return self.lineSize def setStartPt(self, startPt): - """ Set the starting point for this line DrawingObject. - """ - self.startPt = startPt + """ Set the starting point for this line DrawingObject. + """ + self.startPt = startPt def getStartPt(self): - """ Return the starting point for this line DrawingObject. - """ - return self.startPt + """ Return the starting point for this line DrawingObject. + """ + return self.startPt def setEndPt(self, endPt): - """ Set the ending point for this line DrawingObject. - """ - self.endPt = endPt + """ Set the ending point for this line DrawingObject. + """ + self.endPt = endPt def getEndPt(self): - """ Return the ending point for this line DrawingObject. - """ - return self.endPt + """ Return the ending point for this line DrawingObject. + """ + return self.endPt def setText(self, text): - """ Set the text for this DrawingObject. - """ - self.text = text + """ Set the text for this DrawingObject. + """ + self.text = text def getText(self): - """ Return this DrawingObject's text. - """ - return self.text + """ Return this DrawingObject's text. + """ + return self.text def setTextFont(self, font): - """ Set the typeface for this text DrawingObject. - """ - self.textFont = font + """ Set the typeface for this text DrawingObject. + """ + self.textFont = font def getTextFont(self): - """ Return this text DrawingObject's typeface. - """ - return self.textFont + """ Return this text DrawingObject's typeface. + """ + return self.textFont def setTextSize(self, size): - """ Set the point size for this text DrawingObject. - """ - self.textSize = size + """ Set the point size for this text DrawingObject. + """ + self.textSize = size def getTextSize(self): - """ Return this text DrawingObject's text size. - """ - return self.textSize + """ Return this text DrawingObject's text size. + """ + return self.textSize def setTextBoldface(self, boldface): - """ Set the boldface flag for this text DrawingObject. - """ - self.textBoldface = boldface + """ Set the boldface flag for this text DrawingObject. + """ + self.textBoldface = boldface def getTextBoldface(self): - """ Return this text DrawingObject's boldface flag. - """ - return self.textBoldface + """ Return this text DrawingObject's boldface flag. + """ + return self.textBoldface def setTextItalic(self, italic): - """ Set the italic flag for this text DrawingObject. - """ - self.textItalic = italic + """ Set the italic flag for this text DrawingObject. + """ + self.textItalic = italic def getTextItalic(self): - """ Return this text DrawingObject's italic flag. - """ - return self.textItalic + """ Return this text DrawingObject's italic flag. + """ + return self.textItalic def setTextUnderline(self, underline): - """ Set the underling flag for this text DrawingObject. - """ - self.textUnderline = underline + """ Set the underling flag for this text DrawingObject. + """ + self.textUnderline = underline def getTextUnderline(self): - """ Return this text DrawingObject's underline flag. - """ - return self.textUnderline + """ Return this text DrawingObject's underline flag. + """ + return self.textUnderline # ============================ # == Object Drawing Methods == # ============================ def draw(self, dc, selected): - """ Draw this DrawingObject into our window. + """ Draw this DrawingObject into our window. - 'dc' is the device context to use for drawing. If 'selected' is - true, the object is currently selected and should be drawn as such. - """ - if self.type != obj_TEXT: - if self.lineSize == 0: - dc.SetPen(wxPen(self.penColour, self.lineSize, wxTRANSPARENT)) - else: - dc.SetPen(wxPen(self.penColour, self.lineSize, wxSOLID)) - dc.SetBrush(wxBrush(self.fillColour, wxSOLID)) - else: - dc.SetTextForeground(self.penColour) - dc.SetTextBackground(self.fillColour) + 'dc' is the device context to use for drawing. If 'selected' is + true, the object is currently selected and should be drawn as such. + """ + if self.type != obj_TEXT: + if self.lineSize == 0: + dc.SetPen(wxPen(self.penColour, self.lineSize, wxTRANSPARENT)) + else: + dc.SetPen(wxPen(self.penColour, self.lineSize, wxSOLID)) + dc.SetBrush(wxBrush(self.fillColour, wxSOLID)) + else: + dc.SetTextForeground(self.penColour) + dc.SetTextBackground(self.fillColour) - self._privateDraw(dc, self.position, selected) + self._privateDraw(dc, self.position, selected) # ======================= # == Selection Methods == # ======================= def objectContainsPoint(self, x, y): - """ Returns true iff this object contains the given point. + """ Returns true iff this object contains the given point. - This is used to determine if the user clicked on the object. - """ - # Firstly, ignore any points outside of the object's bounds. + This is used to determine if the user clicked on the object. + """ + # Firstly, ignore any points outside of the object's bounds. - if x < self.position.x: return false - if x > self.position.x + self.size.x: return false - if y < self.position.y: return false - if y > self.position.y + self.size.y: return false + if x < self.position.x: return false + if x > self.position.x + self.size.x: return false + if y < self.position.y: return false + if y > self.position.y + self.size.y: return false - if self.type in [obj_RECT, obj_TEXT]: - # Rectangles and text are easy -- they're always selected if the - # point is within their bounds. - return true + if self.type in [obj_RECT, obj_TEXT]: + # Rectangles and text are easy -- they're always selected if the + # point is within their bounds. + return true - # Now things get tricky. There's no straightforward way of knowing - # whether the point is within the object's bounds...to get around this, - # we draw the object into a memory-based bitmap and see if the given - # point was drawn. This could no doubt be done more efficiently by - # some tricky maths, but this approach works and is simple enough. + # Now things get tricky. There's no straightforward way of knowing + # whether the point is within the object's bounds...to get around this, + # we draw the object into a memory-based bitmap and see if the given + # point was drawn. This could no doubt be done more efficiently by + # some tricky maths, but this approach works and is simple enough. - bitmap = wxEmptyBitmap(self.size.x + 10, self.size.y + 10) - dc = wxMemoryDC() - dc.SelectObject(bitmap) - dc.BeginDrawing() - dc.SetBackground(wxWHITE_BRUSH) - dc.Clear() - dc.SetPen(wxPen(wxBLACK, self.lineSize + 5, wxSOLID)) - dc.SetBrush(wxBLACK_BRUSH) - self._privateDraw(dc, wxPoint(5, 5), true) - dc.EndDrawing() - pixel = dc.GetPixel(x - self.position.x + 5, y - self.position.y + 5) - if (pixel.Red() == 0) and (pixel.Green() == 0) and (pixel.Blue() == 0): - return true - else: - return false + bitmap = wxEmptyBitmap(self.size.x + 10, self.size.y + 10) + dc = wxMemoryDC() + dc.SelectObject(bitmap) + dc.BeginDrawing() + dc.SetBackground(wxWHITE_BRUSH) + dc.Clear() + dc.SetPen(wxPen(wxBLACK, self.lineSize + 5, wxSOLID)) + dc.SetBrush(wxBLACK_BRUSH) + self._privateDraw(dc, wxPoint(5, 5), true) + dc.EndDrawing() + pixel = dc.GetPixel(x - self.position.x + 5, y - self.position.y + 5) + if (pixel.Red() == 0) and (pixel.Green() == 0) and (pixel.Blue() == 0): + return true + else: + return false def getSelectionHandleContainingPoint(self, x, y): - """ Return the selection handle containing the given point, if any. + """ Return the selection handle containing the given point, if any. - We return one of the predefined selection handle ID codes. - """ - if self.type == obj_LINE: - # We have selection handles at the start and end points. - if self._pointInSelRect(x, y, self.position.x + self.startPt.x, - self.position.y + self.startPt.y): - return handle_START_POINT - elif self._pointInSelRect(x, y, self.position.x + self.endPt.x, - self.position.y + self.endPt.y): - return handle_END_POINT - else: - return handle_NONE - else: - # We have selection handles at all four corners. - if self._pointInSelRect(x, y, self.position.x, self.position.y): - return handle_TOP_LEFT - elif self._pointInSelRect(x, y, self.position.x + self.size.width, - self.position.y): - return handle_TOP_RIGHT - elif self._pointInSelRect(x, y, self.position.x, - self.position.y + self.size.height): - return handle_BOTTOM_LEFT - elif self._pointInSelRect(x, y, self.position.x + self.size.width, - self.position.y + self.size.height): - return handle_BOTTOM_RIGHT - else: - return handle_NONE + We return one of the predefined selection handle ID codes. + """ + if self.type == obj_LINE: + # We have selection handles at the start and end points. + if self._pointInSelRect(x, y, self.position.x + self.startPt.x, + self.position.y + self.startPt.y): + return handle_START_POINT + elif self._pointInSelRect(x, y, self.position.x + self.endPt.x, + self.position.y + self.endPt.y): + return handle_END_POINT + else: + return handle_NONE + else: + # We have selection handles at all four corners. + if self._pointInSelRect(x, y, self.position.x, self.position.y): + return handle_TOP_LEFT + elif self._pointInSelRect(x, y, self.position.x + self.size.width, + self.position.y): + return handle_TOP_RIGHT + elif self._pointInSelRect(x, y, self.position.x, + self.position.y + self.size.height): + return handle_BOTTOM_LEFT + elif self._pointInSelRect(x, y, self.position.x + self.size.width, + self.position.y + self.size.height): + return handle_BOTTOM_RIGHT + else: + return handle_NONE def objectWithinRect(self, x, y, width, height): - """ Return true iff this object falls completely within the given rect. - """ - if x > self.position.x: return false - if x + width < self.position.x + self.size.width: return false - if y > self.position.y: return false - if y + height < self.position.y + self.size.height: return false - return true + """ Return true iff this object falls completely within the given rect. + """ + if x > self.position.x: return false + if x + width < self.position.x + self.size.width: return false + if y > self.position.y: return false + if y + height < self.position.y + self.size.height: return false + return true # ===================== # == Utility Methods == # ===================== def fitToText(self): - """ Resize a text DrawingObject so that it fits it's text exactly. - """ - if self.type != obj_TEXT: return + """ Resize a text DrawingObject so that it fits it's text exactly. + """ + if self.type != obj_TEXT: return - if self.textBoldface: weight = wxBOLD - else: weight = wxNORMAL - if self.textItalic: style = wxITALIC - else: style = wxNORMAL - font = wxFont(self.textSize, wxDEFAULT, style, weight, - self.textUnderline, self.textFont) + if self.textBoldface: weight = wxBOLD + else: weight = wxNORMAL + if self.textItalic: style = wxITALIC + else: style = wxNORMAL + font = wxFont(self.textSize, wxDEFAULT, style, weight, + self.textUnderline, self.textFont) - dummyWindow = wxFrame(None, -1, "") - dummyWindow.SetFont(font) - width, height = dummyWindow.GetTextExtent(self.text) - dummyWindow.Destroy() + dummyWindow = wxFrame(None, -1, "") + dummyWindow.SetFont(font) + width, height = dummyWindow.GetTextExtent(self.text) + dummyWindow.Destroy() - self.size = wxSize(width, height) + self.size = wxSize(width, height) # ===================== # == Private Methods == # ===================== def _privateDraw(self, dc, position, selected): - """ Private routine to draw this DrawingObject. + """ Private routine to draw this DrawingObject. - 'dc' is the device context to use for drawing, while 'position' is - the position in which to draw the object. If 'selected' is true, - the object is drawn with selection handles. This private drawing - routine assumes that the pen and brush have already been set by the - caller. - """ - if self.type == obj_LINE: - dc.DrawLine(position.x + self.startPt.x, - position.y + self.startPt.y, - position.x + self.endPt.x, - position.y + self.endPt.y) - elif self.type == obj_RECT: - dc.DrawRectangle(position.x, position.y, - self.size.width, self.size.height) - elif self.type == obj_ELLIPSE: - dc.DrawEllipse(position.x, position.y, - self.size.width, self.size.height) - elif self.type == obj_TEXT: - if self.textBoldface: weight = wxBOLD - else: weight = wxNORMAL - if self.textItalic: style = wxITALIC - else: style = wxNORMAL - font = wxFont(self.textSize, wxDEFAULT, style, weight, - self.textUnderline, self.textFont) - dc.SetFont(font) - dc.DrawText(self.text, position.x, position.y) + 'dc' is the device context to use for drawing, while 'position' is + the position in which to draw the object. If 'selected' is true, + the object is drawn with selection handles. This private drawing + routine assumes that the pen and brush have already been set by the + caller. + """ + if self.type == obj_LINE: + dc.DrawLine(position.x + self.startPt.x, + position.y + self.startPt.y, + position.x + self.endPt.x, + position.y + self.endPt.y) + elif self.type == obj_RECT: + dc.DrawRectangle(position.x, position.y, + self.size.width, self.size.height) + elif self.type == obj_ELLIPSE: + dc.DrawEllipse(position.x, position.y, + self.size.width, self.size.height) + elif self.type == obj_TEXT: + if self.textBoldface: weight = wxBOLD + else: weight = wxNORMAL + if self.textItalic: style = wxITALIC + else: style = wxNORMAL + font = wxFont(self.textSize, wxDEFAULT, style, weight, + self.textUnderline, self.textFont) + dc.SetFont(font) + dc.DrawText(self.text, position.x, position.y) - if selected: - dc.SetPen(wxTRANSPARENT_PEN) - dc.SetBrush(wxBLACK_BRUSH) + if selected: + dc.SetPen(wxTRANSPARENT_PEN) + dc.SetBrush(wxBLACK_BRUSH) - if self.type == obj_LINE: - # Draw selection handles at the start and end points. - self._drawSelHandle(dc, position.x + self.startPt.x, - position.y + self.startPt.y) - self._drawSelHandle(dc, position.x + self.endPt.x, - position.y + self.endPt.y) - else: - # Draw selection handles at all four corners. - self._drawSelHandle(dc, position.x, position.y) - self._drawSelHandle(dc, position.x + self.size.width, - position.y) - self._drawSelHandle(dc, position.x, - position.y + self.size.height) - self._drawSelHandle(dc, position.x + self.size.width, - position.y + self.size.height) + if self.type == obj_LINE: + # Draw selection handles at the start and end points. + self._drawSelHandle(dc, position.x + self.startPt.x, + position.y + self.startPt.y) + self._drawSelHandle(dc, position.x + self.endPt.x, + position.y + self.endPt.y) + else: + # Draw selection handles at all four corners. + self._drawSelHandle(dc, position.x, position.y) + self._drawSelHandle(dc, position.x + self.size.width, + position.y) + self._drawSelHandle(dc, position.x, + position.y + self.size.height) + self._drawSelHandle(dc, position.x + self.size.width, + position.y + self.size.height) def _drawSelHandle(self, dc, x, y): - """ Draw a selection handle around this DrawingObject. + """ Draw a selection handle around this DrawingObject. - 'dc' is the device context to draw the selection handle within, - while 'x' and 'y' are the coordinates to use for the centre of the - selection handle. - """ - dc.DrawRectangle(x - 3, y - 3, 6, 6) + 'dc' is the device context to draw the selection handle within, + while 'x' and 'y' are the coordinates to use for the centre of the + selection handle. + """ + dc.DrawRectangle(x - 3, y - 3, 6, 6) def _pointInSelRect(self, x, y, rX, rY): - """ Return true iff (x, y) is within the selection handle at (rX, ry). - """ - if x < rX - 3: return false - elif x > rX + 3: return false - elif y < rY - 3: return false - elif y > rY + 3: return false - else: return true + """ Return true iff (x, y) is within the selection handle at (rX, ry). + """ + if x < rX - 3: return false + elif x > rX + 3: return false + elif y < rY - 3: return false + elif y > rY + 3: return false + else: return true #---------------------------------------------------------------------------- class ToolPaletteIcon(wxStaticBitmap): """ An icon appearing in the tool palette area of our sketching window. - Note that this is actually implemented as a wxStaticBitmap rather - than as a wxIcon. wxIcon has a very specific meaning, and isn't - appropriate for this more general use. + Note that this is actually implemented as a wxStaticBitmap rather + than as a wxIcon. wxIcon has a very specific meaning, and isn't + appropriate for this more general use. """ def __init__(self, parent, iconID, iconName, toolTip): - """ Standard constructor. + """ Standard constructor. - 'parent' is the parent window this icon will be part of. - 'iconID' is the internal ID used for this icon. - 'iconName' is the name used for this icon. - 'toolTip' is the tool tip text to show for this icon. + 'parent' is the parent window this icon will be part of. + 'iconID' is the internal ID used for this icon. + 'iconName' is the name used for this icon. + 'toolTip' is the tool tip text to show for this icon. - The icon name is used to get the appropriate bitmap for this icon. - """ - bmp = wxBitmap("images/" + iconName + "Icon.bmp", wxBITMAP_TYPE_BMP) - wxStaticBitmap.__init__(self, parent, iconID, bmp, wxDefaultPosition, - wxSize(bmp.GetWidth(), bmp.GetHeight())) - self.SetToolTip(wxToolTip(toolTip)) + The icon name is used to get the appropriate bitmap for this icon. + """ + bmp = wxBitmap("images/" + iconName + "Icon.bmp", wxBITMAP_TYPE_BMP) + wxStaticBitmap.__init__(self, parent, iconID, bmp, wxDefaultPosition, + wxSize(bmp.GetWidth(), bmp.GetHeight())) + self.SetToolTip(wxToolTip(toolTip)) - self.iconID = iconID - self.iconName = iconName - self.isSelected = false + self.iconID = iconID + self.iconName = iconName + self.isSelected = false def select(self): - """ Select the icon. + """ Select the icon. - The icon's visual representation is updated appropriately. - """ - if self.isSelected: return # Nothing to do! + The icon's visual representation is updated appropriately. + """ + if self.isSelected: return # Nothing to do! - bmp = wxBitmap("images/" + self.iconName + "IconSel.bmp", - wxBITMAP_TYPE_BMP) - self.SetBitmap(bmp) - self.isSelected = true + bmp = wxBitmap("images/" + self.iconName + "IconSel.bmp", + wxBITMAP_TYPE_BMP) + self.SetBitmap(bmp) + self.isSelected = true def deselect(self): - """ Deselect the icon. + """ Deselect the icon. - The icon's visual representation is updated appropriately. - """ - if not self.isSelected: return # Nothing to do! + The icon's visual representation is updated appropriately. + """ + if not self.isSelected: return # Nothing to do! - bmp = wxBitmap("images/" + self.iconName + "Icon.bmp", - wxBITMAP_TYPE_BMP) - self.SetBitmap(bmp) - self.isSelected = false + bmp = wxBitmap("images/" + self.iconName + "Icon.bmp", + wxBITMAP_TYPE_BMP) + self.SetBitmap(bmp) + self.isSelected = false #---------------------------------------------------------------------------- @@ -2290,298 +2290,298 @@ class ToolOptionIndicator(wxWindow): """ A visual indicator which shows the current tool options. """ def __init__(self, parent): - """ Standard constructor. - """ - wxWindow.__init__(self, parent, -1, wxDefaultPosition, wxSize(52, 32)) + """ Standard constructor. + """ + wxWindow.__init__(self, parent, -1, wxDefaultPosition, wxSize(52, 32)) - self.penColour = wxBLACK - self.fillColour = wxWHITE - self.lineSize = 1 + self.penColour = wxBLACK + self.fillColour = wxWHITE + self.lineSize = 1 - EVT_PAINT(self, self.OnPaint) + EVT_PAINT(self, self.OnPaint) def setPenColour(self, penColour): - """ Set the indicator's current pen colour. - """ - self.penColour = penColour - self.Refresh() + """ Set the indicator's current pen colour. + """ + self.penColour = penColour + self.Refresh() def setFillColour(self, fillColour): - """ Set the indicator's current fill colour. - """ - self.fillColour = fillColour - self.Refresh() + """ Set the indicator's current fill colour. + """ + self.fillColour = fillColour + self.Refresh() def setLineSize(self, lineSize): - """ Set the indicator's current pen colour. - """ - self.lineSize = lineSize - self.Refresh() + """ Set the indicator's current pen colour. + """ + self.lineSize = lineSize + self.Refresh() def OnPaint(self, event): - """ Paint our tool option indicator. - """ - dc = wxPaintDC(self) - dc.BeginDrawing() + """ Paint our tool option indicator. + """ + dc = wxPaintDC(self) + dc.BeginDrawing() - if self.lineSize == 0: - dc.SetPen(wxPen(self.penColour, self.lineSize, wxTRANSPARENT)) - else: - dc.SetPen(wxPen(self.penColour, self.lineSize, wxSOLID)) - dc.SetBrush(wxBrush(self.fillColour, wxSOLID)) + if self.lineSize == 0: + dc.SetPen(wxPen(self.penColour, self.lineSize, wxTRANSPARENT)) + else: + dc.SetPen(wxPen(self.penColour, self.lineSize, wxSOLID)) + dc.SetBrush(wxBrush(self.fillColour, wxSOLID)) - dc.DrawRectangle(5, 5, self.GetSize().width - 10, - self.GetSize().height - 10) + dc.DrawRectangle(5, 5, self.GetSize().width - 10, + self.GetSize().height - 10) - dc.EndDrawing() + dc.EndDrawing() #---------------------------------------------------------------------------- class EditTextObjectDialog(wxDialog): """ Dialog box used to edit the properties of a text object. - The user can edit the object's text, font, size, and text style. + The user can edit the object's text, font, size, and text style. """ def __init__(self, parent, title): - """ Standard constructor. - """ - wxDialog.__init__(self, parent, -1, title) + """ Standard constructor. + """ + wxDialog.__init__(self, parent, -1, title) - self.textCtrl = wxTextCtrl(self, 1001, "", style=wxTE_PROCESS_ENTER, - validator=TextObjectValidator()) - extent = self.textCtrl.GetFullTextExtent("Hy") - lineHeight = extent[1] + extent[3] - self.textCtrl.SetSize(wxSize(-1, lineHeight * 4)) + self.textCtrl = wxTextCtrl(self, 1001, "", style=wxTE_PROCESS_ENTER, + validator=TextObjectValidator()) + extent = self.textCtrl.GetFullTextExtent("Hy") + lineHeight = extent[1] + extent[3] + self.textCtrl.SetSize(wxSize(-1, lineHeight * 4)) - EVT_TEXT_ENTER(self, 1001, self._doEnter) + EVT_TEXT_ENTER(self, 1001, self._doEnter) - fonts = wxFontEnumerator() - fonts.EnumerateFacenames() - self.fontList = fonts.GetFacenames() - self.fontList.sort() + fonts = wxFontEnumerator() + fonts.EnumerateFacenames() + self.fontList = fonts.GetFacenames() + self.fontList.sort() - fontLabel = wxStaticText(self, -1, "Font:") - self._setFontOptions(fontLabel, weight=wxBOLD) + fontLabel = wxStaticText(self, -1, "Font:") + self._setFontOptions(fontLabel, weight=wxBOLD) - self.fontCombo = wxComboBox(self, -1, "", wxDefaultPosition, - wxDefaultSize, self.fontList, - style = wxCB_READONLY) - self.fontCombo.SetSelection(0) # Default to first available font. + self.fontCombo = wxComboBox(self, -1, "", wxDefaultPosition, + wxDefaultSize, self.fontList, + style = wxCB_READONLY) + self.fontCombo.SetSelection(0) # Default to first available font. - self.sizeList = ["8", "9", "10", "12", "14", "16", - "18", "20", "24", "32", "48", "72"] + self.sizeList = ["8", "9", "10", "12", "14", "16", + "18", "20", "24", "32", "48", "72"] - sizeLabel = wxStaticText(self, -1, "Size:") - self._setFontOptions(sizeLabel, weight=wxBOLD) + sizeLabel = wxStaticText(self, -1, "Size:") + self._setFontOptions(sizeLabel, weight=wxBOLD) - self.sizeCombo = wxComboBox(self, -1, "", wxDefaultPosition, - wxDefaultSize, self.sizeList, - style=wxCB_READONLY) - self.sizeCombo.SetSelection(3) # Default to 12 point text. + self.sizeCombo = wxComboBox(self, -1, "", wxDefaultPosition, + wxDefaultSize, self.sizeList, + style=wxCB_READONLY) + self.sizeCombo.SetSelection(3) # Default to 12 point text. - gap = wxLEFT | wxTOP | wxRIGHT + gap = wxLEFT | wxTOP | wxRIGHT - comboSizer = wxBoxSizer(wxHORIZONTAL) - comboSizer.Add(fontLabel, 0, gap | wxALIGN_CENTRE_VERTICAL, 5) - comboSizer.Add(self.fontCombo, 0, gap, 5) - comboSizer.Add(5, 5) # Spacer. - comboSizer.Add(sizeLabel, 0, gap | wxALIGN_CENTRE_VERTICAL, 5) - comboSizer.Add(self.sizeCombo, 0, gap, 5) + comboSizer = wxBoxSizer(wxHORIZONTAL) + comboSizer.Add(fontLabel, 0, gap | wxALIGN_CENTRE_VERTICAL, 5) + comboSizer.Add(self.fontCombo, 0, gap, 5) + comboSizer.Add(5, 5) # Spacer. + comboSizer.Add(sizeLabel, 0, gap | wxALIGN_CENTRE_VERTICAL, 5) + comboSizer.Add(self.sizeCombo, 0, gap, 5) - self.boldCheckbox = wxCheckBox(self, -1, "Bold") - self.italicCheckbox = wxCheckBox(self, -1, "Italic") - self.underlineCheckbox = wxCheckBox(self, -1, "Underline") + self.boldCheckbox = wxCheckBox(self, -1, "Bold") + self.italicCheckbox = wxCheckBox(self, -1, "Italic") + self.underlineCheckbox = wxCheckBox(self, -1, "Underline") - self._setFontOptions(self.boldCheckbox, weight=wxBOLD) - self._setFontOptions(self.italicCheckbox, style=wxITALIC) - self._setFontOptions(self.underlineCheckbox, underline=true) + self._setFontOptions(self.boldCheckbox, weight=wxBOLD) + self._setFontOptions(self.italicCheckbox, style=wxITALIC) + self._setFontOptions(self.underlineCheckbox, underline=true) - styleSizer = wxBoxSizer(wxHORIZONTAL) - styleSizer.Add(self.boldCheckbox, 0, gap, 5) - styleSizer.Add(self.italicCheckbox, 0, gap, 5) - styleSizer.Add(self.underlineCheckbox, 0, gap, 5) + styleSizer = wxBoxSizer(wxHORIZONTAL) + styleSizer.Add(self.boldCheckbox, 0, gap, 5) + styleSizer.Add(self.italicCheckbox, 0, gap, 5) + styleSizer.Add(self.underlineCheckbox, 0, gap, 5) - self.okButton = wxButton(self, wxID_OK, "OK") - self.cancelButton = wxButton(self, wxID_CANCEL, "Cancel") + self.okButton = wxButton(self, wxID_OK, "OK") + self.cancelButton = wxButton(self, wxID_CANCEL, "Cancel") - btnSizer = wxBoxSizer(wxHORIZONTAL) - btnSizer.Add(self.okButton, 0, gap, 5) - btnSizer.Add(self.cancelButton, 0, gap, 5) + btnSizer = wxBoxSizer(wxHORIZONTAL) + btnSizer.Add(self.okButton, 0, gap, 5) + btnSizer.Add(self.cancelButton, 0, gap, 5) - sizer = wxBoxSizer(wxVERTICAL) - sizer.Add(self.textCtrl, 1, gap | wxEXPAND, 5) - sizer.Add(10, 10) # Spacer. - sizer.Add(comboSizer, 0, gap | wxALIGN_CENTRE, 5) - sizer.Add(styleSizer, 0, gap | wxALIGN_CENTRE, 5) - sizer.Add(10, 10) # Spacer. - sizer.Add(btnSizer, 0, gap | wxALIGN_CENTRE, 5) + sizer = wxBoxSizer(wxVERTICAL) + sizer.Add(self.textCtrl, 1, gap | wxEXPAND, 5) + sizer.Add(10, 10) # Spacer. + sizer.Add(comboSizer, 0, gap | wxALIGN_CENTRE, 5) + sizer.Add(styleSizer, 0, gap | wxALIGN_CENTRE, 5) + sizer.Add(10, 10) # Spacer. + sizer.Add(btnSizer, 0, gap | wxALIGN_CENTRE, 5) - self.SetAutoLayout(true) - self.SetSizer(sizer) - sizer.Fit(self) + self.SetAutoLayout(true) + self.SetSizer(sizer) + sizer.Fit(self) - self.textCtrl.SetFocus() + self.textCtrl.SetFocus() def objectToDialog(self, obj): - """ Copy the properties of the given text object into the dialog box. - """ - self.textCtrl.SetValue(obj.getText()) - self.textCtrl.SetSelection(0, len(obj.getText())) + """ Copy the properties of the given text object into the dialog box. + """ + self.textCtrl.SetValue(obj.getText()) + self.textCtrl.SetSelection(0, len(obj.getText())) - for i in range(len(self.fontList)): - if self.fontList[i] == obj.getTextFont(): - self.fontCombo.SetSelection(i) - break + for i in range(len(self.fontList)): + if self.fontList[i] == obj.getTextFont(): + self.fontCombo.SetSelection(i) + break - for i in range(len(self.sizeList)): - if self.sizeList[i] == str(obj.getTextSize()): - self.sizeCombo.SetSelection(i) - break + for i in range(len(self.sizeList)): + if self.sizeList[i] == str(obj.getTextSize()): + self.sizeCombo.SetSelection(i) + break - self.boldCheckbox.SetValue(obj.getTextBoldface()) - self.italicCheckbox.SetValue(obj.getTextItalic()) - self.underlineCheckbox.SetValue(obj.getTextUnderline()) + self.boldCheckbox.SetValue(obj.getTextBoldface()) + self.italicCheckbox.SetValue(obj.getTextItalic()) + self.underlineCheckbox.SetValue(obj.getTextUnderline()) def dialogToObject(self, obj): - """ Copy the properties from the dialog box into the given text object. - """ - obj.setText(self.textCtrl.GetValue()) - obj.setTextFont(self.fontCombo.GetValue()) - obj.setTextSize(string.atoi(self.sizeCombo.GetValue())) - obj.setTextBoldface(self.boldCheckbox.GetValue()) - obj.setTextItalic(self.italicCheckbox.GetValue()) - obj.setTextUnderline(self.underlineCheckbox.GetValue()) - obj.fitToText() + """ Copy the properties from the dialog box into the given text object. + """ + obj.setText(self.textCtrl.GetValue()) + obj.setTextFont(self.fontCombo.GetValue()) + obj.setTextSize(string.atoi(self.sizeCombo.GetValue())) + obj.setTextBoldface(self.boldCheckbox.GetValue()) + obj.setTextItalic(self.italicCheckbox.GetValue()) + obj.setTextUnderline(self.underlineCheckbox.GetValue()) + obj.fitToText() # ====================== # == Private Routines == # ====================== def _setFontOptions(self, ctrl, family=None, pointSize=-1, - style=wxNORMAL, weight=wxNORMAL, - underline=false): - """ Change the font settings for the given control. + style=wxNORMAL, weight=wxNORMAL, + underline=false): + """ Change the font settings for the given control. - The meaning of the 'family', 'pointSize', 'style', 'weight' and - 'underline' parameters are the same as for the wxFont constructor. - If the family and/or pointSize isn't specified, the current default - value is used. - """ - if family == None: family = ctrl.GetFont().GetFamily() - if pointSize == -1: pointSize = ctrl.GetFont().GetPointSize() + The meaning of the 'family', 'pointSize', 'style', 'weight' and + 'underline' parameters are the same as for the wxFont constructor. + If the family and/or pointSize isn't specified, the current default + value is used. + """ + if family == None: family = ctrl.GetFont().GetFamily() + if pointSize == -1: pointSize = ctrl.GetFont().GetPointSize() - ctrl.SetFont(wxFont(pointSize, family, style, weight, underline)) - ctrl.SetSize(ctrl.GetBestSize()) # Adjust size to reflect font change. + ctrl.SetFont(wxFont(pointSize, family, style, weight, underline)) + ctrl.SetSize(ctrl.GetBestSize()) # Adjust size to reflect font change. def _doEnter(self, event): - """ Respond to the user hitting the ENTER key. + """ Respond to the user hitting the ENTER key. - We simulate clicking on the "OK" button. - """ - if self.Validate(): self.Show(false) + We simulate clicking on the "OK" button. + """ + if self.Validate(): self.Show(false) #---------------------------------------------------------------------------- class TextObjectValidator(wxPyValidator): """ This validator is used to ensure that the user has entered something - into the text object editor dialog's text field. + into the text object editor dialog's text field. """ def __init__(self): - """ Standard constructor. - """ - wxPyValidator.__init__(self) + """ Standard constructor. + """ + wxPyValidator.__init__(self) def Clone(self): - """ Standard cloner. + """ Standard cloner. - Note that every validator must implement the Clone() method. - """ - return TextObjectValidator() + Note that every validator must implement the Clone() method. + """ + return TextObjectValidator() def Validate(self, win): - """ Validate the contents of the given text control. - """ - textCtrl = wxPyTypeCast(self.GetWindow(), "wxTextCtrl") - text = textCtrl.GetValue() + """ Validate the contents of the given text control. + """ + textCtrl = wxPyTypeCast(self.GetWindow(), "wxTextCtrl") + text = textCtrl.GetValue() - if len(text) == 0: - wxMessageBox("A text object must contain some text!", "Error") - return false - else: - return true + if len(text) == 0: + wxMessageBox("A text object must contain some text!", "Error") + return false + else: + return true def TransferToWindow(self): - """ Transfer data from validator to window. + """ Transfer data from validator to window. - The default implementation returns false, indicating that an error - occurred. We simply return true, as we don't do any data transfer. - """ - return true # Prevent wxDialog from complaining. + The default implementation returns false, indicating that an error + occurred. We simply return true, as we don't do any data transfer. + """ + return true # Prevent wxDialog from complaining. def TransferFromWindow(self): - """ Transfer data from window to validator. + """ Transfer data from window to validator. - The default implementation returns false, indicating that an error - occurred. We simply return true, as we don't do any data transfer. - """ - return true # Prevent wxDialog from complaining. + The default implementation returns false, indicating that an error + occurred. We simply return true, as we don't do any data transfer. + """ + return true # Prevent wxDialog from complaining. #---------------------------------------------------------------------------- class ExceptionHandler: """ A simple error-handling class to write exceptions to a text file. - Under MS Windows, the standard DOS console window doesn't scroll and - closes as soon as the application exits, making it hard to find and - view Python exceptions. This utility class allows you to handle Python - exceptions in a more friendly manner. + Under MS Windows, the standard DOS console window doesn't scroll and + closes as soon as the application exits, making it hard to find and + view Python exceptions. This utility class allows you to handle Python + exceptions in a more friendly manner. """ def __init__(self): - """ Standard constructor. - """ - self._buff = "" - if os.path.exists("errors.txt"): - os.remove("errors.txt") # Delete previous error log, if any. + """ Standard constructor. + """ + self._buff = "" + if os.path.exists("errors.txt"): + os.remove("errors.txt") # Delete previous error log, if any. def write(self, s): - """ Write the given error message to a text file. + """ Write the given error message to a text file. - Note that if the error message doesn't end in a carriage return, we - have to buffer up the inputs until a carriage return is received. - """ - if (s[-1] != "\n") and (s[-1] != "\r"): - self._buff = self._buff + s - return + Note that if the error message doesn't end in a carriage return, we + have to buffer up the inputs until a carriage return is received. + """ + if (s[-1] != "\n") and (s[-1] != "\r"): + self._buff = self._buff + s + return - try: - s = self._buff + s - self._buff = "" + try: + s = self._buff + s + self._buff = "" - if s[:9] == "Traceback": - # Tell the user than an exception occurred. - wxMessageBox("An internal error has occurred.\nPlease " + \ - "refer to the 'errors.txt' file for details.", - "Error", wxOK | wxCENTRE | wxICON_EXCLAMATION) + if s[:9] == "Traceback": + # Tell the user than an exception occurred. + wxMessageBox("An internal error has occurred.\nPlease " + \ + "refer to the 'errors.txt' file for details.", + "Error", wxOK | wxCENTRE | wxICON_EXCLAMATION) - f = open("errors.txt", "a") - f.write(s) - f.close() - except: - pass # Don't recursively crash on errors. + f = open("errors.txt", "a") + f.write(s) + f.close() + except: + pass # Don't recursively crash on errors. #---------------------------------------------------------------------------- @@ -2589,30 +2589,30 @@ class SketchApp(wxApp): """ The main pySketch application object. """ def OnInit(self): - """ Initialise the application. - """ + """ Initialise the application. + """ wxInitAllImageHandlers() - global _docList - _docList = [] + global _docList + _docList = [] - if len(sys.argv) == 1: - # No file name was specified on the command line -> start with a - # blank document. - frame = DrawingFrame(None, -1, "Untitled") - frame.Centre() - frame.Show(TRUE) - _docList.append(frame) - else: - # Load the file(s) specified on the command line. - for arg in sys.argv[1:]: - fileName = os.path.join(os.getcwd(), arg) - if os.path.isfile(fileName): - frame = DrawingFrame(None, -1, - os.path.basename(fileName), - fileName=fileName) - frame.Show(TRUE) - _docList.append(frame) + if len(sys.argv) == 1: + # No file name was specified on the command line -> start with a + # blank document. + frame = DrawingFrame(None, -1, "Untitled") + frame.Centre() + frame.Show(TRUE) + _docList.append(frame) + else: + # Load the file(s) specified on the command line. + for arg in sys.argv[1:]: + fileName = os.path.join(os.getcwd(), arg) + if os.path.isfile(fileName): + frame = DrawingFrame(None, -1, + os.path.basename(fileName), + fileName=fileName) + frame.Show(TRUE) + _docList.append(frame) return TRUE diff --git a/wxPython/scripts/CreateBatchFiles.py b/wxPython/scripts/CreateBatchFiles.py index eeb00f3a08..b03044b667 100644 --- a/wxPython/scripts/CreateBatchFiles.py +++ b/wxPython/scripts/CreateBatchFiles.py @@ -1,6 +1,6 @@ #---------------------------------------------------------------------- # Name: CreateBatchFiles.py -# Purpose: Run by the InnoSetup installer to create a DOS batch +# Purpose: Run by the InnoSetup installer to create a DOS batch # file for each of the wxPython tool scripts. # # Author: Robin Dunn diff --git a/wxPython/scripts/CreateMacScripts.py b/wxPython/scripts/CreateMacScripts.py index 8108771e7c..cc7e761959 100644 --- a/wxPython/scripts/CreateMacScripts.py +++ b/wxPython/scripts/CreateMacScripts.py @@ -1,6 +1,6 @@ #---------------------------------------------------------------------- # Name: CreateMacScripts.py -# Purpose: Massages the scripts to be usable with MachoPython +# Purpose: Massages the scripts to be usable with MachoPython # # Author: Robin Dunn # diff --git a/wxPython/src/_extras.py b/wxPython/src/_extras.py index f31349b313..b20cce579f 100644 --- a/wxPython/src/_extras.py +++ b/wxPython/src/_extras.py @@ -1,6 +1,6 @@ #---------------------------------------------------------------------------- # Name: _extra.py -# Purpose: This file is appended to the shadow class file generated +# Purpose: This file is appended to the shadow class file generated # by SWIG. We add some unSWIGable things here. # # Author: Robin Dunn diff --git a/wxPython/src/wx.i b/wxPython/src/wx.i index ec1ced419d..6bfcffc3af 100644 --- a/wxPython/src/wx.i +++ b/wxPython/src/wx.i @@ -291,3 +291,4 @@ static wxPyCoreAPI API = { %pragma(python) include="_extras.py"; + diff --git a/wxPython/tests/hangman.py b/wxPython/tests/hangman.py index 76b9622689..d9fed0ec19 100644 --- a/wxPython/tests/hangman.py +++ b/wxPython/tests/hangman.py @@ -1,12 +1,12 @@ -"""Hangman.py, a simple wxPython game, inspired by the +"""Hangman.py, a simple wxPython game, inspired by the old bsd game by Ken Arnold. From the original man page: - In hangman, the computer picks a word from the on-line - word list and you must try to guess it. The computer - keeps track of which letters have been guessed and how + In hangman, the computer picks a word from the on-line + word list and you must try to guess it. The computer + keeps track of which letters have been guessed and how many wrong guesses you have made on the screen in a - graphic fashion. + graphic fashion. That says it all, doesn't it? @@ -19,30 +19,30 @@ from wxPython.wx import * class WordFetcher: def __init__(self, filename, min_length = 5): - self.min_length = min_length - print "Trying to open file %s" % (filename,) - try: - f = open(filename, "r") - except: - print "Couldn't open dictionary file %s, using build-ins" % (filename,) - self.words = self.builtin_words - self.filename = None - return - self.words = f.read() - self.filename = filename - print "Got %d bytes." % (len(self.words),) + self.min_length = min_length + print "Trying to open file %s" % (filename,) + try: + f = open(filename, "r") + except: + print "Couldn't open dictionary file %s, using build-ins" % (filename,) + self.words = self.builtin_words + self.filename = None + return + self.words = f.read() + self.filename = filename + print "Got %d bytes." % (len(self.words),) def SetMinLength(min_length): - self.min_length = min_length + self.min_length = min_length def Get(self): - reg = re.compile('\s+([a-zA-Z]+)\s+') - n = 50 # safety valve; maximum number of tries to find a suitable word - while n: - index = int(random.random()*len(self.words)) - m = reg.search(self.words[index:]) - if m and len(m.groups()[0]) >= self.min_length: break - n = n - 1 - if n: return string.lower(m.groups()[0]) - return "error" + reg = re.compile('\s+([a-zA-Z]+)\s+') + n = 50 # safety valve; maximum number of tries to find a suitable word + while n: + index = int(random.random()*len(self.words)) + m = reg.search(self.words[index:]) + if m and len(m.groups()[0]) >= self.min_length: break + n = n - 1 + if n: return string.lower(m.groups()[0]) + return "error" builtin_words = ' albatros banana electrometer eggshell' def stdprint(x): @@ -50,47 +50,47 @@ def stdprint(x): class URLWordFetcher(WordFetcher): def __init__(self, url): - self.OpenURL(url) - WordFetcher.__init__(self, "hangman_dict.txt") + self.OpenURL(url) + WordFetcher.__init__(self, "hangman_dict.txt") def logprint(self,x): - print x + print x def RetrieveAsFile(self, host, path=''): - from httplib import HTTP - try: - h = HTTP(host) - except: - self.logprint("Failed to create HTTP connection to %s... is the network available?" % (host)) - return None - h.putrequest('GET',path) - h.putheader('Accept','text/html') - h.putheader('Accept','text/plain') - h.endheaders() - errcode, errmsg, headers = h.getreply() - if errcode != 200: - self.logprint("HTTP error code %d: %s" % (errcode, errmsg)) - return None - f = h.getfile() - return f + from httplib import HTTP + try: + h = HTTP(host) + except: + self.logprint("Failed to create HTTP connection to %s... is the network available?" % (host)) + return None + h.putrequest('GET',path) + h.putheader('Accept','text/html') + h.putheader('Accept','text/plain') + h.endheaders() + errcode, errmsg, headers = h.getreply() + if errcode != 200: + self.logprint("HTTP error code %d: %s" % (errcode, errmsg)) + return None + f = h.getfile() + return f def OpenURL(self,url): - from htmllib import HTMLParser - import formatter - self.url = url - m = re.match('http://([^/]+)(/\S*)\s*', url) - if m: - host = m.groups()[0] - path = m.groups()[1] - else: - m = re.match('http://(\S+)\s*', url) - if not m: - # Invalid URL - self.logprint("Invalid or unsupported URL: %s" % (url)) - return - host = m.groups()[0] - path = '' - f = self.RetrieveAsFile(host,path) - if not f: - self.logprint("Could not open %s" % (url)) - return + from htmllib import HTMLParser + import formatter + self.url = url + m = re.match('http://([^/]+)(/\S*)\s*', url) + if m: + host = m.groups()[0] + path = m.groups()[1] + else: + m = re.match('http://(\S+)\s*', url) + if not m: + # Invalid URL + self.logprint("Invalid or unsupported URL: %s" % (url)) + return + host = m.groups()[0] + path = '' + f = self.RetrieveAsFile(host,path) + if not f: + self.logprint("Could not open %s" % (url)) + return self.logprint("Receiving data...") data = f.read() tmp = open('hangman_dict.txt','w') @@ -103,287 +103,287 @@ class URLWordFetcher(WordFetcher): class HangmanWnd(wxWindow): def __init__(self, parent, id, pos=wxDefaultPosition, size=wxDefaultSize): - wxWindow.__init__(self, parent, id, pos, size) - self.SetBackgroundColour(wxNamedColour('white')) - if wxPlatform == '__WXGTK__': - self.font = wxFont(12, wxMODERN, wxNORMAL, wxNORMAL) - else: - self.font = wxFont(10, wxMODERN, wxNORMAL, wxNORMAL) - self.SetFocus() + wxWindow.__init__(self, parent, id, pos, size) + self.SetBackgroundColour(wxNamedColour('white')) + if wxPlatform == '__WXGTK__': + self.font = wxFont(12, wxMODERN, wxNORMAL, wxNORMAL) + else: + self.font = wxFont(10, wxMODERN, wxNORMAL, wxNORMAL) + self.SetFocus() def StartGame(self, word): - self.word = word - self.guess = [] - self.tries = 0 - self.misses = 0 - self.Draw() + self.word = word + self.guess = [] + self.tries = 0 + self.misses = 0 + self.Draw() def EndGame(self): - self.misses = 7; - self.guess = map(chr, range(ord('a'),ord('z')+1)) - self.Draw() + self.misses = 7; + self.guess = map(chr, range(ord('a'),ord('z')+1)) + self.Draw() def HandleKey(self, key): - self.message = "" - if self.guess.count(key): - self.message = 'Already guessed %s' % (key,) - return 0 - self.guess.append(key) - self.guess.sort() - self.tries = self.tries+1 - if not key in self.word: - self.misses = self.misses+1 - if self.misses == 7: - self.EndGame() - return 1 - has_won = 1 - for letter in self.word: - if not self.guess.count(letter): - has_won = 0 - break - if has_won: - self.Draw() - return 2 - self.Draw() - return 0 + self.message = "" + if self.guess.count(key): + self.message = 'Already guessed %s' % (key,) + return 0 + self.guess.append(key) + self.guess.sort() + self.tries = self.tries+1 + if not key in self.word: + self.misses = self.misses+1 + if self.misses == 7: + self.EndGame() + return 1 + has_won = 1 + for letter in self.word: + if not self.guess.count(letter): + has_won = 0 + break + if has_won: + self.Draw() + return 2 + self.Draw() + return 0 def Draw(self, dc = None): - if not dc: - dc = wxClientDC(self) - dc.SetFont(self.font) - dc.Clear() - (x,y) = self.GetSizeTuple() - x1 = x-200; y1 = 20 - for letter in self.word: - if self.guess.count(letter): - dc.DrawText(letter, x1, y1) - else: - dc.DrawText('.', x1, y1) - x1 = x1 + 10 - x1 = x-200 - dc.DrawText("tries %d misses %d" % (self.tries,self.misses),x1,50) - guesses = "" - for letter in self.guess: - guesses = guesses + letter - dc.DrawText("guessed:", x1, 70) - dc.DrawText(guesses[:13], x1+80, 70) - dc.DrawText(guesses[13:], x1+80, 90) - dc.SetUserScale(x/1000., y/1000.) - self.DrawVictim(dc) + if not dc: + dc = wxClientDC(self) + dc.SetFont(self.font) + dc.Clear() + (x,y) = self.GetSizeTuple() + x1 = x-200; y1 = 20 + for letter in self.word: + if self.guess.count(letter): + dc.DrawText(letter, x1, y1) + else: + dc.DrawText('.', x1, y1) + x1 = x1 + 10 + x1 = x-200 + dc.DrawText("tries %d misses %d" % (self.tries,self.misses),x1,50) + guesses = "" + for letter in self.guess: + guesses = guesses + letter + dc.DrawText("guessed:", x1, 70) + dc.DrawText(guesses[:13], x1+80, 70) + dc.DrawText(guesses[13:], x1+80, 90) + dc.SetUserScale(x/1000., y/1000.) + self.DrawVictim(dc) def DrawVictim(self, dc): - dc.SetPen(wxPen(wxNamedColour('black'), 20)) - dc.DrawLines([(10, 980), (10,900), (700,900), (700,940), (720,940), - (720,980), (900,980)]) - dc.DrawLines([(100,900), (100, 100), (300,100)]) - dc.DrawLine(100,200,200,100) - if ( self.misses == 0 ): return - dc.SetPen(wxPen(wxNamedColour('blue'), 10)) - dc.DrawLine(300,100,300,200) - if ( self.misses == 1 ): return - dc.DrawEllipse(250,200,100,100) - if ( self.misses == 2 ): return - dc.DrawLine(300,300,300,600) - if ( self.misses == 3) : return - dc.DrawLine(300,300,250,550) - if ( self.misses == 4) : return - dc.DrawLine(300,300,350,550) - if ( self.misses == 5) : return - dc.DrawLine(300,600,350,850) - if ( self.misses == 6) : return - dc.DrawLine(300,600,250,850) + dc.SetPen(wxPen(wxNamedColour('black'), 20)) + dc.DrawLines([(10, 980), (10,900), (700,900), (700,940), (720,940), + (720,980), (900,980)]) + dc.DrawLines([(100,900), (100, 100), (300,100)]) + dc.DrawLine(100,200,200,100) + if ( self.misses == 0 ): return + dc.SetPen(wxPen(wxNamedColour('blue'), 10)) + dc.DrawLine(300,100,300,200) + if ( self.misses == 1 ): return + dc.DrawEllipse(250,200,100,100) + if ( self.misses == 2 ): return + dc.DrawLine(300,300,300,600) + if ( self.misses == 3) : return + dc.DrawLine(300,300,250,550) + if ( self.misses == 4) : return + dc.DrawLine(300,300,350,550) + if ( self.misses == 5) : return + dc.DrawLine(300,600,350,850) + if ( self.misses == 6) : return + dc.DrawLine(300,600,250,850) def OnPaint(self, event): - dc = wxPaintDC(self) - self.Draw(dc) + dc = wxPaintDC(self) + self.Draw(dc) class HangmanDemo(HangmanWnd): def __init__(self, wf, parent, id, pos, size): - HangmanWnd.__init__(self, parent, id, pos, size) - self.StartGame("dummy") - self.start_new = 1 - self.wf = wf - self.delay = 500 - self.timer = self.PlayTimer(self.MakeMove) + HangmanWnd.__init__(self, parent, id, pos, size) + self.StartGame("dummy") + self.start_new = 1 + self.wf = wf + self.delay = 500 + self.timer = self.PlayTimer(self.MakeMove) def MakeMove(self): - self.timer.Stop() - if self.start_new: - self.StartGame(self.wf.Get()) - self.start_new = 0 - self.left = list('aaaabcdeeeeefghiiiiijklmnnnoooopqrssssttttuuuuvwxyz') - else: - key = self.left[int(random.random()*len(self.left))] - while self.left.count(key): self.left.remove(key) - self.start_new = self.HandleKey(key) - self.timer.Start(self.delay) + self.timer.Stop() + if self.start_new: + self.StartGame(self.wf.Get()) + self.start_new = 0 + self.left = list('aaaabcdeeeeefghiiiiijklmnnnoooopqrssssttttuuuuvwxyz') + else: + key = self.left[int(random.random()*len(self.left))] + while self.left.count(key): self.left.remove(key) + self.start_new = self.HandleKey(key) + self.timer.Start(self.delay) def Stop(self): - self.timer.Stop() + self.timer.Stop() class PlayTimer(wxTimer): - def __init__(self,func): - wxTimer.__init__(self) - self.func = func - self.Start(1000) - def Notify(self): - apply(self.func, ()) + def __init__(self,func): + wxTimer.__init__(self) + self.func = func + self.Start(1000) + def Notify(self): + apply(self.func, ()) class HangmanDemoFrame(wxFrame): def __init__(self, wf, parent, id, pos, size): - wxFrame.__init__(self, parent, id, "Hangman demo", pos, size) - self.demo = HangmanDemo(wf, self, -1, wxDefaultPosition, wxDefaultSize) + wxFrame.__init__(self, parent, id, "Hangman demo", pos, size) + self.demo = HangmanDemo(wf, self, -1, wxDefaultPosition, wxDefaultSize) def OnCloseWindow(self, event): - self.demo.timer.Stop() - self.Destroy() + self.demo.timer.Stop() + self.Destroy() class AboutBox(wxDialog): def __init__(self, parent,wf): - wxDialog.__init__(self, parent, -1, "About Hangman", wxDefaultPosition, wxSize(350,450)) - self.wnd = HangmanDemo(wf, self, -1, wxPoint(1,1), wxSize(350,150)) - self.static = wxStaticText(self, -1, __doc__, wxPoint(1,160), wxSize(350, 250)) - self.button = wxButton(self, 2001, "OK", wxPoint(150,420), wxSize(50,-1)) - EVT_BUTTON(self, 2001, self.OnOK) + wxDialog.__init__(self, parent, -1, "About Hangman", wxDefaultPosition, wxSize(350,450)) + self.wnd = HangmanDemo(wf, self, -1, wxPoint(1,1), wxSize(350,150)) + self.static = wxStaticText(self, -1, __doc__, wxPoint(1,160), wxSize(350, 250)) + self.button = wxButton(self, 2001, "OK", wxPoint(150,420), wxSize(50,-1)) + EVT_BUTTON(self, 2001, self.OnOK) def OnOK(self, event): - self.wnd.Stop() - self.EndModal(wxID_OK) - + self.wnd.Stop() + self.EndModal(wxID_OK) + class MyFrame(wxFrame): def __init__(self, wf): - self.wf = wf - wxFrame.__init__(self, NULL, -1, "hangman", wxDefaultPosition, wxSize(400,300)) - self.wnd = HangmanWnd(self, -1) - menu = wxMenu() - menu.Append(1001, "New") - menu.Append(1002, "End") - menu.AppendSeparator() - menu.Append(1003, "Reset") - menu.Append(1004, "Demo...") - menu.AppendSeparator() - menu.Append(1005, "Exit") - menubar = wxMenuBar() - menubar.Append(menu, "Game") - menu = wxMenu() - #menu.Append(1010, "Internal", "Use internal dictionary", TRUE) - menu.Append(1011, "ASCII File...") - urls = [ 'wxPython home', 'http://208.240.253.245/wxPython/main.html', - 'slashdot.org', 'http://slashdot.org/', - 'cnn.com', 'http://cnn.com', - 'The New York Times', 'http://www.nytimes.com', - 'De Volkskrant', 'http://www.volkskrant.nl/frameless/25000006.html', - 'Gnu GPL', 'http://www.fsf.org/copyleft/gpl.html', - 'Bijbel: Genesis', 'http://www.coas.com/bijbel/gn1.htm'] - urlmenu = wxMenu() - for item in range(0,len(urls),2): - urlmenu.Append(1020+item/2, urls[item], urls[item+1]) - urlmenu.Append(1080, 'Other...', 'Enter an URL') - menu.AppendMenu(1012, 'URL', urlmenu, 'Use a webpage') - menu.Append(1013, 'Dump', 'Write contents to stdout') - menubar.Append(menu, "Dictionary") - self.urls = urls - self.urloffset = 1020 - menu = wxMenu() - menu.Append(1090, "About...") - menubar.Append(menu, "Help") - self.SetMenuBar(menubar) - self.CreateStatusBar(2) - EVT_MENU(self, 1001, self.OnGameNew) - EVT_MENU(self, 1002, self.OnGameEnd) - EVT_MENU(self, 1003, self.OnGameReset) - EVT_MENU(self, 1004, self.OnGameDemo) - EVT_MENU(self, 1005, self.OnWindowClose) - EVT_MENU(self, 1011, self.OnDictFile) - EVT_MENU_RANGE(self, 1020, 1020+len(urls)/2, self.OnDictURL) - EVT_MENU(self, 1080, self.OnDictURLSel) - EVT_MENU(self, 1013, self.OnDictDump) - EVT_MENU(self, 1090, self.OnHelpAbout) - EVT_CHAR(self.wnd, self.OnChar) - self.OnGameReset() + self.wf = wf + wxFrame.__init__(self, NULL, -1, "hangman", wxDefaultPosition, wxSize(400,300)) + self.wnd = HangmanWnd(self, -1) + menu = wxMenu() + menu.Append(1001, "New") + menu.Append(1002, "End") + menu.AppendSeparator() + menu.Append(1003, "Reset") + menu.Append(1004, "Demo...") + menu.AppendSeparator() + menu.Append(1005, "Exit") + menubar = wxMenuBar() + menubar.Append(menu, "Game") + menu = wxMenu() + #menu.Append(1010, "Internal", "Use internal dictionary", TRUE) + menu.Append(1011, "ASCII File...") + urls = [ 'wxPython home', 'http://208.240.253.245/wxPython/main.html', + 'slashdot.org', 'http://slashdot.org/', + 'cnn.com', 'http://cnn.com', + 'The New York Times', 'http://www.nytimes.com', + 'De Volkskrant', 'http://www.volkskrant.nl/frameless/25000006.html', + 'Gnu GPL', 'http://www.fsf.org/copyleft/gpl.html', + 'Bijbel: Genesis', 'http://www.coas.com/bijbel/gn1.htm'] + urlmenu = wxMenu() + for item in range(0,len(urls),2): + urlmenu.Append(1020+item/2, urls[item], urls[item+1]) + urlmenu.Append(1080, 'Other...', 'Enter an URL') + menu.AppendMenu(1012, 'URL', urlmenu, 'Use a webpage') + menu.Append(1013, 'Dump', 'Write contents to stdout') + menubar.Append(menu, "Dictionary") + self.urls = urls + self.urloffset = 1020 + menu = wxMenu() + menu.Append(1090, "About...") + menubar.Append(menu, "Help") + self.SetMenuBar(menubar) + self.CreateStatusBar(2) + EVT_MENU(self, 1001, self.OnGameNew) + EVT_MENU(self, 1002, self.OnGameEnd) + EVT_MENU(self, 1003, self.OnGameReset) + EVT_MENU(self, 1004, self.OnGameDemo) + EVT_MENU(self, 1005, self.OnWindowClose) + EVT_MENU(self, 1011, self.OnDictFile) + EVT_MENU_RANGE(self, 1020, 1020+len(urls)/2, self.OnDictURL) + EVT_MENU(self, 1080, self.OnDictURLSel) + EVT_MENU(self, 1013, self.OnDictDump) + EVT_MENU(self, 1090, self.OnHelpAbout) + EVT_CHAR(self.wnd, self.OnChar) + self.OnGameReset() def OnGameNew(self, event): - word = self.wf.Get() - self.in_progress = 1 - self.SetStatusText("",0) - self.wnd.StartGame(word) + word = self.wf.Get() + self.in_progress = 1 + self.SetStatusText("",0) + self.wnd.StartGame(word) def OnGameEnd(self, event): - self.UpdateAverages(0) - self.in_progress = 0 - self.SetStatusText("",0) - self.wnd.EndGame() + self.UpdateAverages(0) + self.in_progress = 0 + self.SetStatusText("",0) + self.wnd.EndGame() def OnGameReset(self, event=None): - self.played = 0 - self.won = 0 - self.history = [] - self.average = 0.0 - self.OnGameNew(None) + self.played = 0 + self.won = 0 + self.history = [] + self.average = 0.0 + self.OnGameNew(None) def OnGameDemo(self, event): - frame = HangmanDemoFrame(self.wf, self, -1, wxDefaultPosition, self.GetSize()) - frame.Show(TRUE) + frame = HangmanDemoFrame(self.wf, self, -1, wxDefaultPosition, self.GetSize()) + frame.Show(TRUE) def OnDictFile(self, event): - fd = wxFileDialog(self) - if (self.wf.filename): - fd.SetFilename(self.wf.filename) - if fd.ShowModal() == wxID_OK: - file = fd.GetPath() - self.wf = WordFetcher(file) + fd = wxFileDialog(self) + if (self.wf.filename): + fd.SetFilename(self.wf.filename) + if fd.ShowModal() == wxID_OK: + file = fd.GetPath() + self.wf = WordFetcher(file) def OnDictURL(self, event): - item = (event.GetId() - self.urloffset)*2 - print "Trying to open %s at %s" % (self.urls[item], self.urls[item+1]) - self.wf = URLWordFetcher(self.urls[item+1]) + item = (event.GetId() - self.urloffset)*2 + print "Trying to open %s at %s" % (self.urls[item], self.urls[item+1]) + self.wf = URLWordFetcher(self.urls[item+1]) def OnDictURLSel(self, event): - msg = wxTextEntryDialog(self, "Enter the URL of the dictionary document", "Enter URL") - if msg.ShowModal() == wxID_OK: - url = msg.GetValue() - self.wf = URLWordFetcher(url) + msg = wxTextEntryDialog(self, "Enter the URL of the dictionary document", "Enter URL") + if msg.ShowModal() == wxID_OK: + url = msg.GetValue() + self.wf = URLWordFetcher(url) def OnDictDump(self, event): - print self.wf.words + print self.wf.words def OnHelpAbout(self, event): - about = AboutBox(self, self.wf) - about.ShowModal() - about.wnd.Stop() # that damn timer won't stop! + about = AboutBox(self, self.wf) + about.ShowModal() + about.wnd.Stop() # that damn timer won't stop! def UpdateAverages(self, has_won): - if has_won: - self.won = self.won + 1 - self.played = self.played+1 - self.history.append(self.wnd.misses) # ugly - total = 0.0 - for m in self.history: - total = total + m - self.average = float(total/len(self.history)) + if has_won: + self.won = self.won + 1 + self.played = self.played+1 + self.history.append(self.wnd.misses) # ugly + total = 0.0 + for m in self.history: + total = total + m + self.average = float(total/len(self.history)) def OnChar(self, event): - if not self.in_progress: - self.OnGameNew(None) - return - key = event.KeyCode(); - if key >= ord('A') and key <= ord('Z'): - key = key + ord('a') - ord('A') - key = chr(key) - if key < 'a' or key > 'z': - event.Skip() - return - res = self.wnd.HandleKey(key) - if res == 0: - self.SetStatusText(self.wnd.message) - elif res == 1: - self.UpdateAverages(0) - self.SetStatusText("Too bad, you're dead!",0) - self.in_progress = 0 + if not self.in_progress: + self.OnGameNew(None) + return + key = event.KeyCode(); + if key >= ord('A') and key <= ord('Z'): + key = key + ord('a') - ord('A') + key = chr(key) + if key < 'a' or key > 'z': + event.Skip() + return + res = self.wnd.HandleKey(key) + if res == 0: + self.SetStatusText(self.wnd.message) + elif res == 1: + self.UpdateAverages(0) + self.SetStatusText("Too bad, you're dead!",0) + self.in_progress = 0 elif res == 2: - self.in_progress = 0 - self.UpdateAverages(1) - self.SetStatusText("Congratulations!",0) - if self.played: - percent = (100.*self.won)/self.played - else: - percent = 0.0 - self.SetStatusText("p %d, w %d (%g %%), av %g" % (self.played,self.won, percent, self.average),1) + self.in_progress = 0 + self.UpdateAverages(1) + self.SetStatusText("Congratulations!",0) + if self.played: + percent = (100.*self.won)/self.played + else: + percent = 0.0 + self.SetStatusText("p %d, w %d (%g %%), av %g" % (self.played,self.won, percent, self.average),1) def OnWindowClose(self, event): - self.Destroy() - + self.Destroy() + class MyApp(wxApp): def OnInit(self): - if wxPlatform == '__WXGTK__': - defaultfile = "/usr/share/games/hangman-words" - elif wxPlatform == '__WXMSW__': - defaultfile = "c:\\windows\\hardware.txt" - else: - defaultfile = "" - wf = WordFetcher(defaultfile) - frame = MyFrame(wf) - self.SetTopWindow(frame) - frame.Show(TRUE) - return TRUE + if wxPlatform == '__WXGTK__': + defaultfile = "/usr/share/games/hangman-words" + elif wxPlatform == '__WXMSW__': + defaultfile = "c:\\windows\\hardware.txt" + else: + defaultfile = "" + wf = WordFetcher(defaultfile) + frame = MyFrame(wf) + self.SetTopWindow(frame) + frame.Show(TRUE) + return TRUE if __name__ == '__main__': app = MyApp(0) diff --git a/wxPython/tests/test7.py b/wxPython/tests/test7.py index 50f394ad5f..11b786e19f 100644 --- a/wxPython/tests/test7.py +++ b/wxPython/tests/test7.py @@ -35,17 +35,26 @@ class MyFrame(wxFrame): wxStaticText(panel, -1, "Size:", wxDLG_PNT(panel, wxPoint(4, 4)), wxDefaultSize) wxStaticText(panel, -1, "Pos:", - wxDLG_PNT(panel, wxPoint(4, 14)), wxDefaultSize) + wxDLG_PNT(panel, wxPoint(4, 18)), wxDefaultSize) + wxStaticText(panel, -1, "ScreenPos:", + wxDLG_PNT(panel, wxPoint(4, 32)), wxDefaultSize) self.sizeCtrl = wxTextCtrl(panel, -1, "", - wxDLG_PNT(panel, wxPoint(24, 4)), + wxDLG_PNT(panel, wxPoint(36, 4)), wxDLG_SZE(panel, wxSize(36, -1)), wxTE_READONLY) self.posCtrl = wxTextCtrl(panel, -1, "", - wxDLG_PNT(panel, wxPoint(24, 14)), + wxDLG_PNT(panel, wxPoint(36, 18)), wxDLG_SZE(panel, wxSize(36, -1)), wxTE_READONLY) + self.sposCtrl = wxTextCtrl(panel, -1, "", + wxDLG_PNT(panel, wxPoint(36, 32)), + wxDLG_SZE(panel, wxSize(36, -1)), + wxTE_READONLY) + + panel.Fit() + self.Fit() # This method is called automatically when the CLOSE event is # sent to this window @@ -59,6 +68,8 @@ class MyFrame(wxFrame): def OnSize(self, event): size = event.GetSize() self.sizeCtrl.SetValue("%s, %s" % (size.width, size.height)) + p = self.ClientToScreen((0,0)) + self.sposCtrl.SetValue("%s, %s" % (p.x, p.y)) # tell the event system to continue looking for an event handler, # so the default handler will get called. @@ -69,6 +80,8 @@ class MyFrame(wxFrame): def OnMove(self, event): pos = event.GetPosition() self.posCtrl.SetValue("%s, %s" % (pos.x, pos.y)) + p = self.ClientToScreen((0,0)) + self.sposCtrl.SetValue("%s, %s" % (p.x, p.y)) diff --git a/wxPython/tests/test8.py b/wxPython/tests/test8.py index ec383b7a09..34cd268791 100644 --- a/wxPython/tests/test8.py +++ b/wxPython/tests/test8.py @@ -18,15 +18,15 @@ use_wxpython = 1 def DoThread(mesg): while 1: sleeptime = (random() * 3) + 0.5 - print "Hello from %s (%1.3f)" % (mesg, sleeptime) - time.sleep(sleeptime) + print "Hello from %s (%1.3f)" % (mesg, sleeptime) + time.sleep(sleeptime) # the same, but write it to a textctrl. def DoTextCtrlThread(text, mesg): while 1: sleeptime = (random() * 3) + 0.5 - text.WriteText("Hello from %s (%1.3f)\n" % (mesg, sleeptime)) - time.sleep(sleeptime) + text.WriteText("Hello from %s (%1.3f)\n" % (mesg, sleeptime)) + time.sleep(sleeptime) # A very simple queue for textctrls. # Nice demonstration of the power of OO programming too (at least I think so!) @@ -34,41 +34,41 @@ def DoTextCtrlThread(text, mesg): # The main (UI) thread must call Flush to force output. (see MyFrame::OnIdle) class wxTextCtrlQueue(wxTextCtrl): def __init__(self, parent, id, value, pos, size, flags): - wxTextCtrl.__init__(self,parent, id, value, pos, size, flags) - self.queue = [] + wxTextCtrl.__init__(self,parent, id, value, pos, size, flags) + self.queue = [] def WriteText(self, value): - self.queue.append(value) + self.queue.append(value) def Flush(self): - queue = self.queue - self.queue = [] - for value in queue: - wxTextCtrl.WriteText(self,value) + queue = self.queue + self.queue = [] + for value in queue: + wxTextCtrl.WriteText(self,value) # MyFrame and MyApp are very simple classes to test python threads in # wxPython. class MyFrame(wxFrame): def __init__(self): - wxFrame.__init__(self, NULL, -1, "test threads", wxDefaultPosition, wxSize(300,200)) - self.text = wxTextCtrlQueue(self, -1, "thread output\n", wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE) - menu = wxMenu() - menu.Append(1001, "Start thread") - self.cnt = 0; - menubar = wxMenuBar() - menubar.Append(menu, "Action") - self.SetMenuBar(menubar) - EVT_MENU(self, 1001, self.StartThread) + wxFrame.__init__(self, NULL, -1, "test threads", wxDefaultPosition, wxSize(300,200)) + self.text = wxTextCtrlQueue(self, -1, "thread output\n", wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE) + menu = wxMenu() + menu.Append(1001, "Start thread") + self.cnt = 0; + menubar = wxMenuBar() + menubar.Append(menu, "Action") + self.SetMenuBar(menubar) + EVT_MENU(self, 1001, self.StartThread) def StartThread(self, event): - self.cnt = self.cnt + 1 - thread.start_new_thread(DoTextCtrlThread, (self.text, "thread %d" % self.cnt)) + self.cnt = self.cnt + 1 + thread.start_new_thread(DoTextCtrlThread, (self.text, "thread %d" % self.cnt)) def OnIdle(self, event): - self.text.Flush() + self.text.Flush() class MyApp(wxApp): def OnInit(self): - frame = MyFrame() - self.SetTopWindow(frame) - frame.Show(TRUE) - return TRUE + frame = MyFrame() + self.SetTopWindow(frame) + frame.Show(TRUE) + return TRUE # Start two threads that print a message every second thread.start_new_thread(DoThread, ("thread A",)) @@ -80,6 +80,6 @@ if use_wxpython: app.MainLoop() else: while 1: - print "main loop" - time.sleep(4) + print "main loop" + time.sleep(4) print 'done!' diff --git a/wxPython/tests/testDlg.py b/wxPython/tests/testDlg.py index 6dee2656d4..5bad5eb49a 100644 --- a/wxPython/tests/testDlg.py +++ b/wxPython/tests/testDlg.py @@ -5,43 +5,43 @@ from wxPython.wx import * ## Create a new frame class, derived from the wxPython Frame. class Dialog(wxDialog): - def __init__(self, parent, title): - # First, call the base class' __init__ method to create the frame - wxDialog.__init__( self, parent, -1, title, wxDefaultPosition, wxDefaultSize ) + def __init__(self, parent, title): + # First, call the base class' __init__ method to create the frame + wxDialog.__init__( self, parent, -1, title, wxDefaultPosition, wxDefaultSize ) wxButton(self, wxID_OK, "OK", (10, 10)) wxButton(self, wxID_CANCEL, "Cancel", (50,50)) - self.Centre( wxBOTH ) + self.Centre( wxBOTH ) - # This method is called automatically when the CLOSE event is - # sent to this window - #def OnCloseWindow(self, event): - # self.Destroy() + # This method is called automatically when the CLOSE event is + # sent to this window + #def OnCloseWindow(self, event): + # self.Destroy() - #def OnCloseMe(self, event): - #self.Close(true) + #def OnCloseMe(self, event): + #self.Close(true) def main(): - # Every wxWindows application must have a class derived from wxApp - class App(wxApp): + # Every wxWindows application must have a class derived from wxApp + class App(wxApp): - # wxWindows calls this method to initialize the application - def OnInit(self): + # wxWindows calls this method to initialize the application + def OnInit(self): - # Create an instance of our customized Frame class - dialog = Dialog( NULL, 'test' ) - dialog.ShowModal() + # Create an instance of our customized Frame class + dialog = Dialog( NULL, 'test' ) + dialog.ShowModal() print "got here" dialog.Destroy() - # Tell wxWindows that this is our main window - # Return a success flag - return true + # Tell wxWindows that this is our main window + # Return a success flag + return true - app = App(0) # Create an instance of the application class - app.MainLoop() # Tell it to start processing events + app = App(0) # Create an instance of the application class + app.MainLoop() # Tell it to start processing events diff --git a/wxPython/tests/testTree.py b/wxPython/tests/testTree.py index e445371c94..1b91ffd427 100644 --- a/wxPython/tests/testTree.py +++ b/wxPython/tests/testTree.py @@ -7,110 +7,110 @@ from stat import * GlobalObjList = [] class Obj: - def __init__(self, obj): - self.obj = obj - # Uncomment next line to eliminate crash. - # GlobalObjList.append(self) + def __init__(self, obj): + self.obj = obj + # Uncomment next line to eliminate crash. + # GlobalObjList.append(self) - def Name(self): - head, tail = os.path.split(self.obj) - if tail: - return tail - else: - return head - - def HasChildren(self): - return os.path.isdir(self.obj) - - def Children(self): - objList = os.listdir(self.obj) - objList.sort() - objList = map(lambda obj,parent=self.obj: os.path.join(parent,obj), - objList) - objectList = map(Obj, objList) - return objectList - - def __str__(self): - return self.obj - - def __repr__(self): - return self.obj + def Name(self): + head, tail = os.path.split(self.obj) + if tail: + return tail + else: + return head + + def HasChildren(self): + return os.path.isdir(self.obj) + + def Children(self): + objList = os.listdir(self.obj) + objList.sort() + objList = map(lambda obj,parent=self.obj: os.path.join(parent,obj), + objList) + objectList = map(Obj, objList) + return objectList + + def __str__(self): + return self.obj + + def __repr__(self): + return self.obj + + def __del__(self): + print 'del', self.obj - def __del__(self): - print 'del', self.obj - #---------------------------------------------------------------------- class pyTree(wx.wxTreeCtrl): - def __init__(self, parent, id, obj): - wx.wxTreeCtrl.__init__(self, parent, id) - self.root = self.AddRoot(obj.Name(), -1, -1, wx.wxTreeItemData('')) - self.SetPyData(self.root, obj) - if obj.HasChildren(): - self.SetItemHasChildren(self.root, wx.TRUE) - wx.EVT_TREE_ITEM_EXPANDING(self, self.GetId(), self.OnItemExpanding) - wx.EVT_TREE_ITEM_COLLAPSED(self, self.GetId(), self.OnItemCollapsed) - wx.EVT_TREE_SEL_CHANGED(self, self.GetId(), self.OnSelChanged) - self.output = None + def __init__(self, parent, id, obj): + wx.wxTreeCtrl.__init__(self, parent, id) + self.root = self.AddRoot(obj.Name(), -1, -1, wx.wxTreeItemData('')) + self.SetPyData(self.root, obj) + if obj.HasChildren(): + self.SetItemHasChildren(self.root, wx.TRUE) + wx.EVT_TREE_ITEM_EXPANDING(self, self.GetId(), self.OnItemExpanding) + wx.EVT_TREE_ITEM_COLLAPSED(self, self.GetId(), self.OnItemCollapsed) + wx.EVT_TREE_SEL_CHANGED(self, self.GetId(), self.OnSelChanged) + self.output = None - def SetOutput(self, output): - self.output = output + def SetOutput(self, output): + self.output = output - def OnItemExpanding(self,event): - item = event.GetItem() - obj = self.GetPyData(item) - children = obj.Children() - for child in children: - new_item = self.AppendItem(item, child.Name(), -1, -1, - wx.wxTreeItemData('')) - self.SetPyData(new_item, child) - if child.HasChildren(): - self.SetItemHasChildren(new_item, wx.TRUE) + def OnItemExpanding(self,event): + item = event.GetItem() + obj = self.GetPyData(item) + children = obj.Children() + for child in children: + new_item = self.AppendItem(item, child.Name(), -1, -1, + wx.wxTreeItemData('')) + self.SetPyData(new_item, child) + if child.HasChildren(): + self.SetItemHasChildren(new_item, wx.TRUE) - def OnItemCollapsed(self, event): - item = event.GetItem() - self.DeleteChildren(item) + def OnItemCollapsed(self, event): + item = event.GetItem() + self.DeleteChildren(item) - def OnSelChanged(self, event): - if not self.output: - return - obj = self.GetPyData( event.GetItem() ) - apply(self.output, (`obj`,)) + def OnSelChanged(self, event): + if not self.output: + return + obj = self.GetPyData( event.GetItem() ) + apply(self.output, (`obj`,)) #---------------------------------------------------------------------- if __name__ == '__main__': - class MyFrame(wx.wxFrame): + class MyFrame(wx.wxFrame): - def __init__(self): - wx.wxFrame.__init__(self, wx.NULL, -1, 'PyTreeItemData Test', - wx.wxDefaultPosition, wx.wxSize(600,500)) - split = wx.wxSplitterWindow(self, -1) - - if sys.platform == 'win32': - tree = pyTree(split, -1, Obj('C:\\')) - else: - tree = pyTree(split, -1, Obj('/')) - - text = wx.wxTextCtrl(split, -1, '', wx.wxDefaultPosition, - wx.wxDefaultSize, wx.wxTE_MULTILINE) - split.SplitVertically(tree, text, 200) - tree.SetOutput(text.SetValue) - tree.SelectItem(tree.root) + def __init__(self): + wx.wxFrame.__init__(self, wx.NULL, -1, 'PyTreeItemData Test', + wx.wxDefaultPosition, wx.wxSize(600,500)) + split = wx.wxSplitterWindow(self, -1) - class MyApp(wx.wxApp): - - def OnInit(self): - frame = MyFrame() - frame.Show(wx.TRUE) - self.SetTopWindow(frame) - return wx.TRUE + if sys.platform == 'win32': + tree = pyTree(split, -1, Obj('C:\\')) + else: + tree = pyTree(split, -1, Obj('/')) - app = MyApp(0) - app.MainLoop() + text = wx.wxTextCtrl(split, -1, '', wx.wxDefaultPosition, + wx.wxDefaultSize, wx.wxTE_MULTILINE) + split.SplitVertically(tree, text, 200) + tree.SetOutput(text.SetValue) + tree.SelectItem(tree.root) + + class MyApp(wx.wxApp): + + def OnInit(self): + frame = MyFrame() + frame.Show(wx.TRUE) + self.SetTopWindow(frame) + return wx.TRUE + + app = MyApp(0) + app.MainLoop() diff --git a/wxPython/tests/wxPlotCanvas.py b/wxPython/tests/wxPlotCanvas.py index baa9112c10..05c0efde1d 100644 --- a/wxPython/tests/wxPlotCanvas.py +++ b/wxPython/tests/wxPlotCanvas.py @@ -27,15 +27,15 @@ try: import Numeric except: # bummer! - d = wx.wxMessageDialog(wx.NULL, + d = wx.wxMessageDialog(wx.NULL, """This module requires the Numeric module, which could not be imported. It probably is not installed (it's not part of the standard Python -distribution). See the Python site (http://www.python.org) for -information on downloading source or binaries.""", +distribution). See the Python site (http://www.python.org) for +information on downloading source or binaries.""", "Numeric not found") if d.ShowModal() == wx.wxID_CANCEL: - d = wx.wxMessageDialog(wx.NULL, "I kid you not! Pressing Cancel won't help you!", "Not a joke", wx.wxOK) - d.ShowModal() + d = wx.wxMessageDialog(wx.NULL, "I kid you not! Pressing Cancel won't help you!", "Not a joke", wx.wxOK) + d.ShowModal() import sys sys.exit() @@ -46,7 +46,7 @@ class PolyPoints: def __init__(self, points, attr): self.points = Numeric.array(points) - self.scaled = self.points + self.scaled = self.points self.attributes = {} for name, value in self._attributes.items(): try: @@ -71,11 +71,11 @@ class PolyLine(PolyPoints): 'width': 1} def draw(self, dc): - color = self.attributes['color'] - width = self.attributes['width'] - arguments = [] - dc.SetPen(wx.wxPen(wx.wxNamedColour(color), width)) - dc.DrawLines(map(tuple,self.scaled)) + color = self.attributes['color'] + width = self.attributes['width'] + arguments = [] + dc.SetPen(wx.wxPen(wx.wxNamedColour(color), width)) + dc.DrawLines(map(tuple,self.scaled)) class PolyMarker(PolyPoints): @@ -88,25 +88,25 @@ class PolyMarker(PolyPoints): 'width': 1, 'fillcolor': None, 'size': 2, - 'fillstyle': wx.wxSOLID, + 'fillstyle': wx.wxSOLID, 'outline': 'black', 'marker': 'circle'} def draw(self, dc): - color = self.attributes['color'] - width = self.attributes['width'] + color = self.attributes['color'] + width = self.attributes['width'] size = self.attributes['size'] fillcolor = self.attributes['fillcolor'] fillstyle = self.attributes['fillstyle'] marker = self.attributes['marker'] - dc.SetPen(wx.wxPen(wx.wxNamedColour(color),width)) - if fillcolor: - dc.SetBrush(wx.wxBrush(wx.wxNamedColour(fillcolor),fillstyle)) - else: - dc.SetBrush(wx.wxBrush(wx.wxNamedColour('black'), wx.wxTRANSPARENT)) + dc.SetPen(wx.wxPen(wx.wxNamedColour(color),width)) + if fillcolor: + dc.SetBrush(wx.wxBrush(wx.wxNamedColour(fillcolor),fillstyle)) + else: + dc.SetBrush(wx.wxBrush(wx.wxNamedColour('black'), wx.wxTRANSPARENT)) - self._drawmarkers(dc, self.scaled, marker, size) + self._drawmarkers(dc, self.scaled, marker, size) def _drawmarkers(self, dc, coords, marker,size=1): f = eval('self._' +marker) @@ -114,31 +114,31 @@ class PolyMarker(PolyPoints): f(dc, xc, yc, size) def _circle(self, dc, xc, yc, size=1): - dc.DrawEllipse(xc-2.5*size,yc-2.5*size,5.*size,5.*size) + dc.DrawEllipse(xc-2.5*size,yc-2.5*size,5.*size,5.*size) def _dot(self, dc, xc, yc, size=1): - dc.DrawPoint(xc,yc) + dc.DrawPoint(xc,yc) def _square(self, dc, xc, yc, size=1): - dc.DrawRectangle(xc-2.5*size,yc-2.5*size,5.*size,5.*size) - + dc.DrawRectangle(xc-2.5*size,yc-2.5*size,5.*size,5.*size) + def _triangle(self, dc, xc, yc, size=1): - dc.DrawPolygon([(-0.5*size*5,0.2886751*size*5), - (0.5*size*5,0.2886751*size*5), - (0.0,-0.577350*size*5)],xc,yc) + dc.DrawPolygon([(-0.5*size*5,0.2886751*size*5), + (0.5*size*5,0.2886751*size*5), + (0.0,-0.577350*size*5)],xc,yc) def _triangle_down(self, dc, xc, yc, size=1): - dc.DrawPolygon([(-0.5*size*5,-0.2886751*size*5), - (0.5*size*5,-0.2886751*size*5), - (0.0,0.577350*size*5)],xc,yc) + dc.DrawPolygon([(-0.5*size*5,-0.2886751*size*5), + (0.5*size*5,-0.2886751*size*5), + (0.0,0.577350*size*5)],xc,yc) def _cross(self, dc, xc, yc, size=1): - dc.DrawLine(xc-2.5*size,yc-2.5*size,xc+2.5*size,yc+2.5*size) - dc.DrawLine(xc-2.5*size,yc+2.5*size,xc+2.5*size,yc-2.5*size) + dc.DrawLine(xc-2.5*size,yc-2.5*size,xc+2.5*size,yc+2.5*size) + dc.DrawLine(xc-2.5*size,yc+2.5*size,xc+2.5*size,yc-2.5*size) def _plus(self, dc, xc, yc, size=1): - dc.DrawLine(xc-2.5*size,yc,xc+2.5*size,yc) - dc.DrawLine(xc,yc-2.5*size,xc,yc+2.5*size) + dc.DrawLine(xc-2.5*size,yc,xc+2.5*size,yc) + dc.DrawLine(xc,yc-2.5*size,xc,yc+2.5*size) class PlotGraphics: @@ -146,191 +146,191 @@ class PlotGraphics: self.objects = objects def boundingBox(self): - p1, p2 = self.objects[0].boundingBox() - for o in self.objects[1:]: - p1o, p2o = o.boundingBox() - p1 = Numeric.minimum(p1, p1o) - p2 = Numeric.maximum(p2, p2o) - return p1, p2 + p1, p2 = self.objects[0].boundingBox() + for o in self.objects[1:]: + p1o, p2o = o.boundingBox() + p1 = Numeric.minimum(p1, p1o) + p2 = Numeric.maximum(p2, p2o) + return p1, p2 def scaleAndShift(self, scale=1, shift=0): - for o in self.objects: - o.scaleAndShift(scale, shift) + for o in self.objects: + o.scaleAndShift(scale, shift) def draw(self, canvas): - for o in self.objects: - o.draw(canvas) + for o in self.objects: + o.draw(canvas) def __len__(self): - return len(self.objects) + return len(self.objects) def __getitem__(self, item): - return self.objects[item] + return self.objects[item] class PlotCanvas(wx.wxWindow): def __init__(self, parent, id = -1): - wx.wxWindow.__init__(self, parent, id, wx.wxPyDefaultPosition, wx.wxPyDefaultSize) - self.border = (1,1) - self.SetClientSizeWH(400,400) - self.SetBackgroundColour(wx.wxNamedColour("white")) + wx.wxWindow.__init__(self, parent, id, wx.wxPyDefaultPosition, wx.wxPyDefaultSize) + self.border = (1,1) + self.SetClientSizeWH(400,400) + self.SetBackgroundColour(wx.wxNamedColour("white")) - wx.EVT_SIZE(self,self.reconfigure) - self._setsize() - self.last_draw = None -# self.font = self._testFont(font) + wx.EVT_SIZE(self,self.reconfigure) + self._setsize() + self.last_draw = None +# self.font = self._testFont(font) def OnPaint(self, event): - pdc = wx.wxPaintDC(self) - if self.last_draw is not None: - apply(self.draw, self.last_draw + (pdc,)) + pdc = wx.wxPaintDC(self) + if self.last_draw is not None: + apply(self.draw, self.last_draw + (pdc,)) def reconfigure(self, event): - (new_width,new_height) = self.GetClientSizeTuple() + (new_width,new_height) = self.GetClientSizeTuple() if new_width == self.width and new_height == self.height: return self._setsize() # self.redraw() def _testFont(self, font): - if font is not None: - bg = self.canvas.cget('background') - try: - item = CanvasText(self.canvas, 0, 0, anchor=NW, - text='0', fill=bg, font=font) - self.canvas.delete(item) - except TclError: - font = None - return font + if font is not None: + bg = self.canvas.cget('background') + try: + item = CanvasText(self.canvas, 0, 0, anchor=NW, + text='0', fill=bg, font=font) + self.canvas.delete(item) + except TclError: + font = None + return font def _setsize(self): - (self.width,self.height) = self.GetClientSizeTuple(); - self.plotbox_size = 0.97*Numeric.array([self.width, -self.height]) - xo = 0.5*(self.width-self.plotbox_size[0]) - yo = self.height-0.5*(self.height+self.plotbox_size[1]) - self.plotbox_origin = Numeric.array([xo, yo]) + (self.width,self.height) = self.GetClientSizeTuple(); + self.plotbox_size = 0.97*Numeric.array([self.width, -self.height]) + xo = 0.5*(self.width-self.plotbox_size[0]) + yo = self.height-0.5*(self.height+self.plotbox_size[1]) + self.plotbox_origin = Numeric.array([xo, yo]) def draw(self, graphics, xaxis = None, yaxis = None, dc = None): - if dc == None: dc = wx.wxClientDC(self) - dc.BeginDrawing() - dc.Clear() - self.last_draw = (graphics, xaxis, yaxis) - p1, p2 = graphics.boundingBox() - xaxis = self._axisInterval(xaxis, p1[0], p2[0]) - yaxis = self._axisInterval(yaxis, p1[1], p2[1]) - text_width = [0., 0.] - text_height = [0., 0.] - if xaxis is not None: - p1[0] = xaxis[0] - p2[0] = xaxis[1] - xticks = self._ticks(xaxis[0], xaxis[1]) - bb = dc.GetTextExtent(xticks[0][1]) - text_height[1] = bb[1] - text_width[0] = 0.5*bb[0] - bb = dc.GetTextExtent(xticks[-1][1]) - text_width[1] = 0.5*bb[0] - else: - xticks = None - if yaxis is not None: - p1[1] = yaxis[0] - p2[1] = yaxis[1] - yticks = self._ticks(yaxis[0], yaxis[1]) - for y in yticks: - bb = dc.GetTextExtent(y[1]) - text_width[0] = max(text_width[0],bb[0]) - h = 0.5*bb[1] - text_height[0] = h - text_height[1] = max(text_height[1], h) - else: - yticks = None - text1 = Numeric.array([text_width[0], -text_height[1]]) - text2 = Numeric.array([text_width[1], -text_height[0]]) - scale = (self.plotbox_size-text1-text2) / (p2-p1) - shift = -p1*scale + self.plotbox_origin + text1 - self._drawAxes(dc, xaxis, yaxis, p1, p2, + if dc == None: dc = wx.wxClientDC(self) + dc.BeginDrawing() + dc.Clear() + self.last_draw = (graphics, xaxis, yaxis) + p1, p2 = graphics.boundingBox() + xaxis = self._axisInterval(xaxis, p1[0], p2[0]) + yaxis = self._axisInterval(yaxis, p1[1], p2[1]) + text_width = [0., 0.] + text_height = [0., 0.] + if xaxis is not None: + p1[0] = xaxis[0] + p2[0] = xaxis[1] + xticks = self._ticks(xaxis[0], xaxis[1]) + bb = dc.GetTextExtent(xticks[0][1]) + text_height[1] = bb[1] + text_width[0] = 0.5*bb[0] + bb = dc.GetTextExtent(xticks[-1][1]) + text_width[1] = 0.5*bb[0] + else: + xticks = None + if yaxis is not None: + p1[1] = yaxis[0] + p2[1] = yaxis[1] + yticks = self._ticks(yaxis[0], yaxis[1]) + for y in yticks: + bb = dc.GetTextExtent(y[1]) + text_width[0] = max(text_width[0],bb[0]) + h = 0.5*bb[1] + text_height[0] = h + text_height[1] = max(text_height[1], h) + else: + yticks = None + text1 = Numeric.array([text_width[0], -text_height[1]]) + text2 = Numeric.array([text_width[1], -text_height[0]]) + scale = (self.plotbox_size-text1-text2) / (p2-p1) + shift = -p1*scale + self.plotbox_origin + text1 + self._drawAxes(dc, xaxis, yaxis, p1, p2, scale, shift, xticks, yticks) - graphics.scaleAndShift(scale, shift) - graphics.draw(dc) - dc.EndDrawing() + graphics.scaleAndShift(scale, shift) + graphics.draw(dc) + dc.EndDrawing() def _axisInterval(self, spec, lower, upper): - if spec is None: - return None - if spec == 'minimal': - if lower == upper: - return lower-0.5, upper+0.5 - else: - return lower, upper - if spec == 'automatic': - range = upper-lower - if range == 0.: - return lower-0.5, upper+0.5 - log = Numeric.log10(range) - power = Numeric.floor(log) - fraction = log-power - if fraction <= 0.05: - power = power-1 - grid = 10.**power - lower = lower - lower % grid - mod = upper % grid - if mod != 0: - upper = upper - mod + grid - return lower, upper - if type(spec) == type(()): - lower, upper = spec - if lower <= upper: - return lower, upper - else: - return upper, lower - raise ValueError, str(spec) + ': illegal axis specification' + if spec is None: + return None + if spec == 'minimal': + if lower == upper: + return lower-0.5, upper+0.5 + else: + return lower, upper + if spec == 'automatic': + range = upper-lower + if range == 0.: + return lower-0.5, upper+0.5 + log = Numeric.log10(range) + power = Numeric.floor(log) + fraction = log-power + if fraction <= 0.05: + power = power-1 + grid = 10.**power + lower = lower - lower % grid + mod = upper % grid + if mod != 0: + upper = upper - mod + grid + return lower, upper + if type(spec) == type(()): + lower, upper = spec + if lower <= upper: + return lower, upper + else: + return upper, lower + raise ValueError, str(spec) + ': illegal axis specification' def _drawAxes(self, dc, xaxis, yaxis, bb1, bb2, scale, shift, xticks, yticks): - dc.SetPen(wx.wxPen(wx.wxNamedColour('BLACK'),1)) - if xaxis is not None: - lower, upper = xaxis - text = 1 - for y, d in [(bb1[1], -3), (bb2[1], 3)]: - p1 = scale*Numeric.array([lower, y])+shift - p2 = scale*Numeric.array([upper, y])+shift - dc.DrawLine(p1[0],p1[1],p2[0],p2[1]) - for x, label in xticks: - p = scale*Numeric.array([x, y])+shift - dc.DrawLine(p[0],p[1],p[0],p[1]+d) - if text: - dc.DrawText(label,p[0],p[1]) - text = 0 + dc.SetPen(wx.wxPen(wx.wxNamedColour('BLACK'),1)) + if xaxis is not None: + lower, upper = xaxis + text = 1 + for y, d in [(bb1[1], -3), (bb2[1], 3)]: + p1 = scale*Numeric.array([lower, y])+shift + p2 = scale*Numeric.array([upper, y])+shift + dc.DrawLine(p1[0],p1[1],p2[0],p2[1]) + for x, label in xticks: + p = scale*Numeric.array([x, y])+shift + dc.DrawLine(p[0],p[1],p[0],p[1]+d) + if text: + dc.DrawText(label,p[0],p[1]) + text = 0 - if yaxis is not None: - lower, upper = yaxis - text = 1 - h = dc.GetCharHeight() - for x, d in [(bb1[0], -3), (bb2[0], 3)]: - p1 = scale*Numeric.array([x, lower])+shift - p2 = scale*Numeric.array([x, upper])+shift - dc.DrawLine(p1[0],p1[1],p2[0],p2[1]) - for y, label in yticks: - p = scale*Numeric.array([x, y])+shift - dc.DrawLine(p[0],p[1],p[0]-d,p[1]) - if text: - dc.DrawText(label,p[0]-dc.GetTextExtent(label)[0], - p[1]-0.5*h) - text = 0 + if yaxis is not None: + lower, upper = yaxis + text = 1 + h = dc.GetCharHeight() + for x, d in [(bb1[0], -3), (bb2[0], 3)]: + p1 = scale*Numeric.array([x, lower])+shift + p2 = scale*Numeric.array([x, upper])+shift + dc.DrawLine(p1[0],p1[1],p2[0],p2[1]) + for y, label in yticks: + p = scale*Numeric.array([x, y])+shift + dc.DrawLine(p[0],p[1],p[0]-d,p[1]) + if text: + dc.DrawText(label,p[0]-dc.GetTextExtent(label)[0], + p[1]-0.5*h) + text = 0 def _ticks(self, lower, upper): - ideal = (upper-lower)/7. - log = Numeric.log10(ideal) - power = Numeric.floor(log) - fraction = log-power - factor = 1. - error = fraction - for f, lf in self._multiples: - e = Numeric.fabs(fraction-lf) - if e < error: - error = e - factor = f - grid = factor * 10.**power + ideal = (upper-lower)/7. + log = Numeric.log10(ideal) + power = Numeric.floor(log) + fraction = log-power + factor = 1. + error = fraction + for f, lf in self._multiples: + e = Numeric.fabs(fraction-lf) + if e < error: + error = e + factor = f + grid = factor * 10.**power if power > 3 or power < -3: format = '%+7.0e' elif power >= 0: @@ -339,18 +339,18 @@ class PlotCanvas(wx.wxWindow): else: digits = -int(power) format = '%'+`digits+2`+'.'+`digits`+'f' - ticks = [] - t = -grid*Numeric.floor(-lower/grid) - while t <= upper: - ticks.append(t, format % (t,)) - t = t + grid - return ticks + ticks = [] + t = -grid*Numeric.floor(-lower/grid) + while t <= upper: + ticks.append(t, format % (t,)) + t = t + grid + return ticks _multiples = [(2., Numeric.log10(2.)), (5., Numeric.log10(5.))] def redraw(self,dc=None): - if self.last_draw is not None: - apply(self.draw, self.last_draw + (dc,)) + if self.last_draw is not None: + apply(self.draw, self.last_draw + (dc,)) def clear(self): self.canvas.delete('all') @@ -362,98 +362,98 @@ class PlotCanvas(wx.wxWindow): if __name__ == '__main__': class AppFrame(wx.wxFrame): - def __init__(self, parent, id, title): - wx.wxFrame.__init__(self, parent, id, title, - wx.wxPyDefaultPosition, wx.wxSize(400, 400)) + def __init__(self, parent, id, title): + wx.wxFrame.__init__(self, parent, id, title, + wx.wxPyDefaultPosition, wx.wxSize(400, 400)) - # Now Create the menu bar and items - self.mainmenu = wx.wxMenuBar() + # Now Create the menu bar and items + self.mainmenu = wx.wxMenuBar() - menu = wx.wxMenu() - menu.Append(200, '&Print...', 'Print the current plot') - wx.EVT_MENU(self, 200, self.OnFilePrint) - menu.Append(209, 'E&xit', 'Enough of this already!') - wx.EVT_MENU(self, 209, self.OnFileExit) - self.mainmenu.Append(menu, '&File') + menu = wx.wxMenu() + menu.Append(200, '&Print...', 'Print the current plot') + wx.EVT_MENU(self, 200, self.OnFilePrint) + menu.Append(209, 'E&xit', 'Enough of this already!') + wx.EVT_MENU(self, 209, self.OnFileExit) + self.mainmenu.Append(menu, '&File') - menu = wx.wxMenu() - menu.Append(210, '&Draw', 'Draw plots') - wx.EVT_MENU(self,210,self.OnPlotDraw) - menu.Append(211, '&Redraw', 'Redraw plots') - wx.EVT_MENU(self,211,self.OnPlotRedraw) - menu.Append(212, '&Clear', 'Clear canvas') - wx.EVT_MENU(self,212,self.OnPlotClear) - self.mainmenu.Append(menu, '&Plot') + menu = wx.wxMenu() + menu.Append(210, '&Draw', 'Draw plots') + wx.EVT_MENU(self,210,self.OnPlotDraw) + menu.Append(211, '&Redraw', 'Redraw plots') + wx.EVT_MENU(self,211,self.OnPlotRedraw) + menu.Append(212, '&Clear', 'Clear canvas') + wx.EVT_MENU(self,212,self.OnPlotClear) + self.mainmenu.Append(menu, '&Plot') - menu = wx.wxMenu() - menu.Append(220, '&About', 'About this thing...') - wx.EVT_MENU(self, 220, self.OnHelpAbout) - self.mainmenu.Append(menu, '&Help') + menu = wx.wxMenu() + menu.Append(220, '&About', 'About this thing...') + wx.EVT_MENU(self, 220, self.OnHelpAbout) + self.mainmenu.Append(menu, '&Help') - self.SetMenuBar(self.mainmenu) + self.SetMenuBar(self.mainmenu) - # A status bar to tell people what's happening - self.CreateStatusBar(1) + # A status bar to tell people what's happening + self.CreateStatusBar(1) - self.client = PlotCanvas(self) + self.client = PlotCanvas(self) - def OnFilePrint(self, event): - d = wx.wxMessageDialog(self, + def OnFilePrint(self, event): + d = wx.wxMessageDialog(self, """As of this writing, printing support in wxPython is shaky at best. Are you sure you want to do this?""", "Danger!", wx.wxYES_NO) if d.ShowModal() == wx.wxID_YES: - psdc = wx.wxPostScriptDC("out.ps", wx.TRUE, self) - self.client.redraw(psdc) + psdc = wx.wxPostScriptDC("out.ps", wx.TRUE, self) + self.client.redraw(psdc) - def OnFileExit(self, event): - self.Close() + def OnFileExit(self, event): + self.Close() - def OnPlotDraw(self, event): - self.client.draw(InitObjects(),'automatic','automatic'); + def OnPlotDraw(self, event): + self.client.draw(InitObjects(),'automatic','automatic'); - def OnPlotRedraw(self,event): - self.client.redraw() + def OnPlotRedraw(self,event): + self.client.redraw() - def OnPlotClear(self,event): - self.client.last_draw = None - dc = wx.wxClientDC(self.client) - dc.Clear() + def OnPlotClear(self,event): + self.client.last_draw = None + dc = wx.wxClientDC(self.client) + dc.Clear() - def OnHelpAbout(self, event): - about = wx.wxMessageDialog(self, __doc__, "About...", wx.wxOK) - about.ShowModal() + def OnHelpAbout(self, event): + about = wx.wxMessageDialog(self, __doc__, "About...", wx.wxOK) + about.ShowModal() - def OnCloseWindow(self, event): - self.Destroy() + def OnCloseWindow(self, event): + self.Destroy() def InitObjects(): - # 100 points sin function, plotted as green circles - data1 = 2.*Numeric.pi*Numeric.arange(200)/200. - data1.shape = (100, 2) - data1[:,1] = Numeric.sin(data1[:,0]) - markers1 = PolyMarker(data1, color='green', marker='circle',size=1) + # 100 points sin function, plotted as green circles + data1 = 2.*Numeric.pi*Numeric.arange(200)/200. + data1.shape = (100, 2) + data1[:,1] = Numeric.sin(data1[:,0]) + markers1 = PolyMarker(data1, color='green', marker='circle',size=1) - # 50 points cos function, plotted as red line - data1 = 2.*Numeric.pi*Numeric.arange(100)/100. - data1.shape = (50,2) - data1[:,1] = Numeric.cos(data1[:,0]) - lines = PolyLine(data1, color='red') + # 50 points cos function, plotted as red line + data1 = 2.*Numeric.pi*Numeric.arange(100)/100. + data1.shape = (50,2) + data1[:,1] = Numeric.cos(data1[:,0]) + lines = PolyLine(data1, color='red') - # A few more points... - pi = Numeric.pi - markers2 = PolyMarker([(0., 0.), (pi/4., 1.), (pi/2, 0.), - (3.*pi/4., -1)], color='blue', - fillcolor='green', marker='cross') + # A few more points... + pi = Numeric.pi + markers2 = PolyMarker([(0., 0.), (pi/4., 1.), (pi/2, 0.), + (3.*pi/4., -1)], color='blue', + fillcolor='green', marker='cross') - return PlotGraphics([markers1, lines, markers2]) + return PlotGraphics([markers1, lines, markers2]) class MyApp(wx.wxApp): - def OnInit(self): - frame = AppFrame(wx.NULL, -1, "wxPlotCanvas") - frame.Show(wx.TRUE) - self.SetTopWindow(frame) - return wx.TRUE + def OnInit(self): + frame = AppFrame(wx.NULL, -1, "wxPlotCanvas") + frame.Show(wx.TRUE) + self.SetTopWindow(frame) + return wx.TRUE app = MyApp(0) diff --git a/wxPython/tests/wxSlash.py b/wxPython/tests/wxSlash.py index ae1164d233..c98148a028 100644 --- a/wxPython/tests/wxSlash.py +++ b/wxPython/tests/wxSlash.py @@ -164,22 +164,22 @@ class AppStatusBar(wxStatusBar): # This is a simple timer class to start a function after a short delay; class QuickTimer(wxTimer): def __init__(self, func, wait=100): - wxTimer.__init__(self) - self.callback = func - self.Start(wait); # wait .1 second (.001 second doesn't work. why?) + wxTimer.__init__(self) + self.callback = func + self.Start(wait); # wait .1 second (.001 second doesn't work. why?) def Notify(self): - self.Stop(); - apply(self.callback, ()); + self.Stop(); + apply(self.callback, ()); class AppFrame(wxFrame): def __init__(self, parent, id, title): wxFrame.__init__(self, parent, id, title, wxPyDefaultPosition, wxSize(650, 250)) - # if the window manager closes the window: - EVT_CLOSE(self, self.OnCloseWindow); + # if the window manager closes the window: + EVT_CLOSE(self, self.OnCloseWindow); - # Now Create the menu bar and items + # Now Create the menu bar and items self.mainmenu = wxMenuBar() menu = wxMenu() @@ -202,46 +202,46 @@ class AppFrame(wxFrame): menu.Append(222, '&Settings...', 'External browser Settings') EVT_MENU(self, 222, self.OnBrowserSettings) self.mainmenu.Append(menu, '&Browser') - menu = wxMenu() - menu.Append(230, '&About', 'Some documentation'); - EVT_MENU(self, 230, self.OnAbout) - self.mainmenu.Append(menu, '&Help') + menu = wxMenu() + menu.Append(230, '&About', 'Some documentation'); + EVT_MENU(self, 230, self.OnAbout) + self.mainmenu.Append(menu, '&Help') self.SetMenuBar(self.mainmenu) - if wxPlatform == '__WXGTK__': - # I like lynx. Also Netscape 4.5 doesn't react to my cmdline opts - self.BrowserSettings = "xterm -e lynx %s &" - elif wxPlatform == '__WXMSW__': - # netscape 4.x likes to hang out here... - self.BrowserSettings = '\\progra~1\\Netscape\\Communicator\\Program\\netscape.exe %s' - else: - # a wild guess... - self.BrowserSettings = 'netscape %s' - - # A status bar to tell people what's happening - self.sb = AppStatusBar(self) + if wxPlatform == '__WXGTK__': + # I like lynx. Also Netscape 4.5 doesn't react to my cmdline opts + self.BrowserSettings = "xterm -e lynx %s &" + elif wxPlatform == '__WXMSW__': + # netscape 4.x likes to hang out here... + self.BrowserSettings = '\\progra~1\\Netscape\\Communicator\\Program\\netscape.exe %s' + else: + # a wild guess... + self.BrowserSettings = 'netscape %s' + + # A status bar to tell people what's happening + self.sb = AppStatusBar(self) self.SetStatusBar(self.sb) self.list = wxListCtrl(self, 1100) - self.list.SetSingleStyle(wxLC_REPORT) - self.list.InsertColumn(0, 'Subject') - self.list.InsertColumn(1, 'Date') - self.list.InsertColumn(2, 'Posted by') - self.list.InsertColumn(3, 'Comments') + self.list.SetSingleStyle(wxLC_REPORT) + self.list.InsertColumn(0, 'Subject') + self.list.InsertColumn(1, 'Date') + self.list.InsertColumn(2, 'Posted by') + self.list.InsertColumn(3, 'Comments') self.list.SetColumnWidth(0, 300) self.list.SetColumnWidth(1, 150) self.list.SetColumnWidth(2, 100) self.list.SetColumnWidth(3, 100) EVT_LIST_ITEM_SELECTED(self, 1100, self.OnItemSelected) - EVT_LEFT_DCLICK(self.list, self.OnLeftDClick) + EVT_LEFT_DCLICK(self.list, self.OnLeftDClick) - self.logprint("Connecting to slashdot... Please wait.") - # wxYield doesn't yet work here. That's why we use a timer - # to make sure that we see some GUI stuff before the slashdot - # file is transfered. - self.timer = QuickTimer(self.DoRefresh, 1000) + self.logprint("Connecting to slashdot... Please wait.") + # wxYield doesn't yet work here. That's why we use a timer + # to make sure that we see some GUI stuff before the slashdot + # file is transfered. + self.timer = QuickTimer(self.DoRefresh, 1000) def logprint(self, x): self.sb.logprint(x) @@ -263,12 +263,12 @@ class AppFrame(wxFrame): self.list.SetStringItem(i, 3, article[6]) self.url.append(article[1]) i = i + 1 - self.logprint("File retrieved OK.") + self.logprint("File retrieved OK.") def OnViewRefresh(self, event): - self.logprint("Connecting to slashdot... Please wait."); - wxYield() - self.DoRefresh() + self.logprint("Connecting to slashdot... Please wait."); + wxYield() + self.DoRefresh() def DoViewIndex(self): if self.UseInternal: @@ -278,12 +278,12 @@ class AppFrame(wxFrame): else: self.logprint(self.BrowserSettings % ('http://slashdot.org')) os.system(self.BrowserSettings % ('http://slashdot.org')) - self.logprint("OK") + self.logprint("OK") def OnViewIndex(self, event): - self.logprint("Starting browser... Please wait.") - wxYield() - self.DoViewIndex() + self.logprint("Starting browser... Please wait.") + wxYield() + self.DoViewIndex() def DoViewArticle(self): if self.current<0: return @@ -294,12 +294,12 @@ class AppFrame(wxFrame): else: self.logprint(self.BrowserSettings % (url)) os.system(self.BrowserSettings % (url)) - self.logprint("OK") + self.logprint("OK") def OnViewArticle(self, event): - self.logprint("Starting browser... Please wait.") - wxYield() - self.DoViewArticle() + self.logprint("Starting browser... Please wait.") + wxYield() + self.DoViewArticle() def OnBrowserInternal(self, event): if self.mainmenu.Checked(220): @@ -313,28 +313,28 @@ class AppFrame(wxFrame): self.BrowserSettings = dlg.GetValue() def OnAbout(self, event): - dlg = wxMessageDialog(self, __doc__, "wxSlash", wxOK | wxICON_INFORMATION) - dlg.ShowModal() + dlg = wxMessageDialog(self, __doc__, "wxSlash", wxOK | wxICON_INFORMATION) + dlg.ShowModal() def OnItemSelected(self, event): self.current = event.m_itemIndex self.logprint("URL: %s" % (self.url[self.current])) def OnLeftDClick(self, event): - (x,y) = event.Position(); - # Actually, we should convert x,y to logical coords using - # a dc, but only for a wxScrolledWindow widget. - # Now wxGTK derives wxListCtrl from wxScrolledWindow, - # and wxMSW from wxControl... So that doesn't work. - #dc = wxClientDC(self.list) - ##self.list.PrepareDC(dc) - #x = dc.DeviceToLogicalX( event.GetX() ) - #y = dc.DeviceToLogicalY( event.GetY() ) - id = self.list.HitTest(wxPoint(x,y)) - #print "Double click at %d %d" % (x,y), id - # Okay, we got a double click. Let's assume it's the current selection - wxYield() - self.OnViewArticle(event) + (x,y) = event.Position(); + # Actually, we should convert x,y to logical coords using + # a dc, but only for a wxScrolledWindow widget. + # Now wxGTK derives wxListCtrl from wxScrolledWindow, + # and wxMSW from wxControl... So that doesn't work. + #dc = wxClientDC(self.list) + ##self.list.PrepareDC(dc) + #x = dc.DeviceToLogicalX( event.GetX() ) + #y = dc.DeviceToLogicalY( event.GetY() ) + id = self.list.HitTest(wxPoint(x,y)) + #print "Double click at %d %d" % (x,y), id + # Okay, we got a double click. Let's assume it's the current selection + wxYield() + self.OnViewArticle(event) def OnCloseWindow(self, event): self.Destroy() diff --git a/wxPython/wxPython/lib/CDate.py b/wxPython/wxPython/lib/CDate.py index c4f0d9b79c..d900e0d203 100644 --- a/wxPython/wxPython/lib/CDate.py +++ b/wxPython/wxPython/lib/CDate.py @@ -11,11 +11,11 @@ import time Month = {2: 'February', 3: 'March', None: 0, 'July': 7, 11: - 'November', 'December': 12, 'June': 6, 'January': 1, 'September': 9, - 'August': 8, 'March': 3, 'November': 11, 'April': 4, 12: 'December', - 'May': 5, 10: 'October', 9: 'September', 8: 'August', 7: 'July', 6: - 'June', 5: 'May', 4: 'April', 'October': 10, 'February': 2, 1: - 'January', 0: None} + 'November', 'December': 12, 'June': 6, 'January': 1, 'September': 9, + 'August': 8, 'March': 3, 'November': 11, 'April': 4, 12: 'December', + 'May': 5, 10: 'October', 9: 'September', 8: 'August', 7: 'July', 6: + 'June', 5: 'May', 4: 'April', 'October': 10, 'February': 2, 1: + 'January', 0: None} # Number of days per month (except for February in leap years) mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] diff --git a/wxPython/wxPython/lib/grids.py b/wxPython/wxPython/lib/grids.py index 9d517db3b0..5425d1adf4 100644 --- a/wxPython/wxPython/lib/grids.py +++ b/wxPython/wxPython/lib/grids.py @@ -126,8 +126,8 @@ class wxGridSizer(wxPySizer): sz = self.GetSize() pt = self.GetPosition() - w = (sz.width - (ncols - 1) * self.hgap) / ncols; - h = (sz.height - (nrows - 1) * self.vgap) / nrows; + w = (sz.width - (ncols - 1) * self.hgap) / ncols; + h = (sz.height - (nrows - 1) * self.vgap) / nrows; x = pt.x for c in range(ncols): diff --git a/wxPython/wxPython/lib/imagebrowser.py b/wxPython/wxPython/lib/imagebrowser.py index b47ef31484..0937beed5b 100644 --- a/wxPython/wxPython/lib/imagebrowser.py +++ b/wxPython/wxPython/lib/imagebrowser.py @@ -14,7 +14,7 @@ # View "All Image" File Types as default filter # Sort the file list # Use newer "re" function for patterns - + #--------------------------------------------------------------------------- import os, sys, string @@ -30,7 +30,7 @@ def ConvertBMP(file_nm): fl_fld = os.path.splitext(file_nm) ext = fl_fld[1] ext = string.lower(ext[1:]) - if ext == 'bmp': + if ext == 'bmp': image = wxImage(file_nm, wxBITMAP_TYPE_BMP) elif ext == 'gif': image = wxImage(file_nm, wxBITMAP_TYPE_GIF) @@ -93,31 +93,31 @@ class ImageView(wxWindow): def DrawImage(self, dc): try: - image = self.image + image = self.image except: return self.DrawBorder(dc) if image is None: return - + bmp = image.ConvertToBitmap() - + iwidth = bmp.GetWidth() # dimensions of image file iheight = bmp.GetHeight() - + diffx = (self.image_sizex - iwidth)/2 # center calc if iwidth >= self.image_sizex -10: # if image width fits in window adjust diffx = 5 iwidth = self.image_sizex - 10 - + diffy = (self.image_sizey - iheight)/2 # center calc if iheight >= self.image_sizey - 10: # if image height fits in window adjust diffy = 5 iheight = self.image_sizey - 10 image.Rescale(iwidth, iheight) # rescale to fit the window - image.ConvertToBitmap() + image.ConvertToBitmap() bmp = image.ConvertToBitmap() dc.DrawBitmap(bmp, diffx, diffy) # draw the image to window @@ -125,38 +125,38 @@ class ImageView(wxWindow): class ImageDialog(wxDialog): def __init__(self, parent, set_dir = None): wxDialog.__init__(self, parent, -1, "Image Browser", wxPyDefaultPosition, wxSize(400, 400)) - + self.x_pos = 30 # initial display positions self.y_pos = 20 - self.delta = 20 + self.delta = 20 size = wxSize(80, 25) - + self.set_dir = os.getcwd() - + if set_dir != None: if os.path.exists(set_dir): # set to working directory if nothing set self.set_dir = set_dir - + self.dir_x = self.x_pos self.dir_y = self.y_pos self.DisplayDir() # display the directory value - + self.y_pos = self.y_pos + self.delta mID = NewId() wxButton(self, mID, ' Set Directory ', wxPoint(self.x_pos, self.y_pos), size).SetDefault() EVT_BUTTON(self, mID, self.SetDirect) - self.type_posy = self.y_pos # save the y position for the image type combo + self.type_posy = self.y_pos # save the y position for the image type combo self.fl_ext = '*.bmp' # initial setting for file filtering self.GetFiles() # get the file list - + self.y_pos = self.y_pos + self.delta + 10 self.list_height = 150 - + # List of Labels mID = NewId() self.tb = tb = wxListBox(self, mID, wxPoint(self.x_pos, self.y_pos), wxSize(160, self.list_height), self.fl_list, wxLB_SINGLE) @@ -170,12 +170,12 @@ class ImageDialog(wxDialog): image_sizey = self.list_height self.fl_types = ["All Images", "Bmp", "Gif", "Png", "Jpg", "Ico", "Pnm", "Pcx", "Tif", "All Files"] - self.fl_ext_types = { "All Images": "All", "Bmp": "*.bmp", "Gif": "*.gif", "Png": "*.png", "Jpg": "*.jpg", + self.fl_ext_types = { "All Images": "All", "Bmp": "*.bmp", "Gif": "*.gif", "Png": "*.png", "Jpg": "*.jpg", "Ico": "*.ico", "Pnm": "*.pnm", "Pcx": "*.pcx", "Tif": "*.tif", "All Files": "*.*" } - + self.set_type = self.fl_types[0] # initial file filter setting self.fl_ext = self.fl_ext_types[self.set_type] - + mID = NewId() self.sel_type = wxComboBox(self, mID, self.set_type, wxPoint(image_posx , self.type_posy), wxSize(150, -1), self.fl_types, wxCB_DROPDOWN) EVT_COMBOBOX(self, mID, self.OnSetType) @@ -193,7 +193,7 @@ class ImageDialog(wxDialog): self.y_pos = self.y_pos + self.delta fsize = wxSize(400, self.y_pos + 50) # resize dialog for final vertical position self.SetSize(fsize) - + self.ResetFiles() def GetFiles(self): # get the file list using directory and extension values @@ -204,7 +204,7 @@ class ImageDialog(wxDialog): self.fl_val = FindFiles(self, self.set_dir, filter) all_files = all_files + self.fl_val.files # add to list of files self.fl_list = all_files - else: + else: self.fl_val = FindFiles(self, self.set_dir, self.fl_ext) self.fl_list = self.fl_val.files @@ -212,19 +212,19 @@ class ImageDialog(wxDialog): def DisplayDir(self): # display the working directory wxStaticText(self, -1, self.set_dir, wxPoint(self.dir_x, self.dir_y), wxSize(250, -1)) - + def OnSetType(self, event): val = event.GetString() # get file type value self.fl_ext = self.fl_ext_types[val] - self.ResetFiles() - + self.ResetFiles() + def OnListDClick(self, event): self.OnOk(0) - + def OnListClick(self, event): val = event.GetSelection() self.SetListValue(val) - + def SetListValue(self, val): file_nm = self.fl_list[val] self.set_file = file_val = os.path.join(self.set_dir, file_nm) @@ -237,7 +237,7 @@ class ImageDialog(wxDialog): self.set_dir = dlg.GetPath() self.ResetFiles() dlg.Destroy() - + def ResetFiles(self): # refresh the display with files and initial image self.DisplayDir() self.GetFiles() @@ -247,13 +247,13 @@ class ImageDialog(wxDialog): self.SetListValue(0) except: self.image_view.SetValue(None) - + def GetFile(self): return self.set_file def GetDirectory(self): return self.set_dir - + def OnCancel(self, event): self.result = None self.EndModal(wxID_CANCEL) @@ -282,7 +282,7 @@ class FindFiles: pattern = self.MakeRegex(mask) for i in os.listdir(dir): if i == "." or i == "..": - continue + continue path = os.path.join(dir, i) path = string.upper(path) value = string.upper(i) @@ -290,11 +290,11 @@ class FindFiles: if pattern.match(value) != None: filelist.append(i) - self.files = filelist + self.files = filelist def MakeRegex(self, pattern): import re - f = "" # Set up a regex for file names + f = "" # Set up a regex for file names for ch in pattern: if ch == "*": f = f + ".*" diff --git a/wxPython/wxPython/lib/printout.py b/wxPython/wxPython/lib/printout.py index a2eb56c323..3770a9134e 100644 --- a/wxPython/wxPython/lib/printout.py +++ b/wxPython/wxPython/lib/printout.py @@ -101,7 +101,7 @@ class PrintBase: cnt = 0 for word in split: - bword = " " + word # blank + word + bword = " " + word # blank + word length = len(bword) w, h = self.DC.GetTextExtent(text + bword) diff --git a/wxPython/wxPython/lib/pyshell.py b/wxPython/wxPython/lib/pyshell.py index 7457f3c830..1584b52aea 100644 --- a/wxPython/wxPython/lib/pyshell.py +++ b/wxPython/wxPython/lib/pyshell.py @@ -248,7 +248,7 @@ class PyShellWindow(wxStyledTextCtrl, InteractiveInterpreter): def OnUpdateUI(self, evt): # check for matching braces braceAtCaret = -1 - braceOpposite = -1 + braceOpposite = -1 charBefore = None caretPos = self.GetCurrentPos() if caretPos > 0: diff --git a/wxPython/wxPython/lib/vtk.py b/wxPython/wxPython/lib/vtk.py index 6a6c977185..676932d215 100644 --- a/wxPython/wxPython/lib/vtk.py +++ b/wxPython/wxPython/lib/vtk.py @@ -136,7 +136,7 @@ class wxVTKRenderWindowBase(wxWindow): def OnCreateWindow(self, event): - hdl = self.GetHandle() + hdl = self.GetHandle() try: self._RenderWindow.SetParentInfo(str(hdl)) except: @@ -163,7 +163,7 @@ class wxVTKRenderWindowBase(wxWindow): # Windows. #self._RenderWindow.GetSize() # - self._RenderWindow.SetSize(sz.width, sz.height) + self._RenderWindow.SetSize(sz.width, sz.height) def OnLeftButtonDown(self, event): diff --git a/wxPython/wxPython/lib/wxpTag.py b/wxPython/wxPython/lib/wxpTag.py index 8dbc44a382..ec490b7c7b 100644 --- a/wxPython/wxPython/lib/wxpTag.py +++ b/wxPython/wxPython/lib/wxpTag.py @@ -241,27 +241,27 @@ def _my_import(name): def _param2dict(param): i = 0; j = 0; s = len(param); d = {} while 1: - while i=s: break - j = i - while j=s: - break - word = param[i:j] - i=j+1 - if (param[i] == '"'): - j=i+1 - while j=s: break + j = i + while j=s: + break + word = param[i:j] + i=j+1 + if (param[i] == '"'): + j=i+1 + while j