Ver código fonte

wxGUI/histogram: major clean up

git-svn-id: https://svn.osgeo.org/grass/grass/trunk@42368 15284696-431f-4ddb-bdfa-cd5b030d7da7
Martin Landa 15 anos atrás
pai
commit
62adaff862
2 arquivos alterados com 249 adições e 286 exclusões
  1. 199 284
      gui/wxpython/gui_modules/histogram.py
  2. 50 2
      gui/wxpython/gui_modules/toolbars.py

+ 199 - 284
gui/wxpython/gui_modules/histogram.py

@@ -1,73 +1,54 @@
-"""
-MODULE: histogram
+"""!
+@package histogram.py
 
 
-CLASSES:
-    * BufferedWindow
-    * HistFrame
+Plotting histogram
 
 
-PURPOSE: Plotting histogram
+Classes:
+ - BufferedWindow
+ - HistFrame
 
 
-AUTHORS: The GRASS Development Team
-         Michael Barton
+COPYRIGHT: (C) 2007, 2010 by the GRASS Development Team
+This program is free software under the GNU General Public License
+(>=v2). Read the file COPYING that comes with GRASS for details.
 
 
-COPYRIGHT: (C) 2007 by the GRASS Development Team
-           This program is free software under the GNU General Public
-           License (>=v2). Read the file COPYING that comes with GRASS
-           for details.
+@author Michael Barton
+@author Various updates by Martin Landa
 """
 """
 
 
-import wx
-import wx.aui
-import os, sys, time, glob, math
-from threading import Thread
-
-import globalvar
-try:
-    import subprocess
-except:
-    CompatPath = os.path.join(globalvar.ETCWXDIR)
-    sys.path.append(CompatPath)
-    from compat import subprocess
+import os
+import sys
 
 
-gmpath = os.path.join(globalvar.ETCWXDIR, "icons")
-sys.path.append(gmpath)
+import wx
 
 
 import render
 import render
 import menuform
 import menuform
 import disp_print
 import disp_print
 import utils
 import utils
-from gui_modules.preferences import DefaultFontDialog as DefaultFontDialog
-from debug import Debug as Debug
-from icon import Icons as Icons
-
-import images
-imagepath = images.__path__[0]
-sys.path.append(imagepath)
-
-os.environ["GRASS_BACKGROUNDCOLOR"] = "blue"
+import gdialogs
+import globalvar
+from toolbars import HistogramToolbar
+from preferences import DefaultFontDialog
+from debug import Debug
+from icon import Icons
 
 
 class BufferedWindow(wx.Window):
 class BufferedWindow(wx.Window):
-    """
-    A Buffered window class.
+    """!A Buffered window class.
 
 
     When the drawing needs to change, you app needs to call the
     When the drawing needs to change, you app needs to call the
     UpdateHist() method. Since the drawing is stored in a bitmap, you
     UpdateHist() method. Since the drawing is stored in a bitmap, you
     can also save the drawing to file by calling the
     can also save the drawing to file by calling the
     SaveToFile(self,file_name,file_type) method.
     SaveToFile(self,file_name,file_type) method.
     """
     """
-
-    def __init__(self, parent, id,
-                 pos = wx.DefaultPosition,
-                 size = wx.DefaultSize,
-                 style=wx.NO_FULL_REPAINT_ON_RESIZE,
-                 Map=None):
-
-        wx.Window.__init__(self, parent, id, pos, size, style)
-
+    def __init__(self, parent, id =  wx.ID_ANY,
+                 style = wx.NO_FULL_REPAINT_ON_RESIZE,
+                 Map = None, **kwargs):
+        
+        wx.Window.__init__(self, parent, id = id, style = style, **kwargs)
+        
         self.parent = parent
         self.parent = parent
         self.Map = Map
         self.Map = Map
         self.mapname = self.parent.mapname
         self.mapname = self.parent.mapname
-
+        
         #
         #
         # Flags
         # Flags
         #
         #
@@ -75,36 +56,34 @@ class BufferedWindow(wx.Window):
         self.resize = False # indicates whether or not a resize event has taken place
         self.resize = False # indicates whether or not a resize event has taken place
         self.dragimg = None # initialize variable for map panning
         self.dragimg = None # initialize variable for map panning
         self.pen = None     # pen for drawing zoom boxes, etc.
         self.pen = None     # pen for drawing zoom boxes, etc.
-
+        
         #
         #
         # Event bindings
         # Event bindings
         #
         #
         self.Bind(wx.EVT_PAINT,        self.OnPaint)
         self.Bind(wx.EVT_PAINT,        self.OnPaint)
         self.Bind(wx.EVT_SIZE,         self.OnSize)
         self.Bind(wx.EVT_SIZE,         self.OnSize)
         self.Bind(wx.EVT_IDLE,         self.OnIdle)
         self.Bind(wx.EVT_IDLE,         self.OnIdle)
-
+        
         #
         #
         # Render output objects
         # Render output objects
         #
         #
         self.mapfile = None # image file to be rendered
         self.mapfile = None # image file to be rendered
         self.img = ""       # wx.Image object (self.mapfile)
         self.img = ""       # wx.Image object (self.mapfile)
-
+        
         self.imagedict = {} # images and their PseudoDC ID's for painting and dragging
         self.imagedict = {} # images and their PseudoDC ID's for painting and dragging
-
+        
         self.pdc = wx.PseudoDC()
         self.pdc = wx.PseudoDC()
-        self._Buffer = '' # will store an off screen empty bitmap for saving to file
-
+        self._buffer = '' # will store an off screen empty bitmap for saving to file
+        
         # make sure that extents are updated at init
         # make sure that extents are updated at init
         self.Map.region = self.Map.GetRegion()
         self.Map.region = self.Map.GetRegion()
         self.Map.SetRegion() 
         self.Map.SetRegion() 
-
+        
         self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x:None)
         self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x:None)
-
-    def Draw(self, pdc, img=None, drawid=None, pdctype='image', coords=[0,0,0,0]):
-        """
-        Draws histogram or clears window
+        
+    def Draw(self, pdc, img = None, drawid = None, pdctype = 'image', coords = [0,0,0,0]):
+        """!Draws histogram or clears window
         """
         """
-
         if drawid == None:
         if drawid == None:
             if pdctype == 'image' :
             if pdctype == 'image' :
                 drawid = imagedict[img]
                 drawid = imagedict[img]
@@ -114,11 +93,11 @@ class BufferedWindow(wx.Window):
                 drawid = wx.NewId()
                 drawid = wx.NewId()
         else:
         else:
             pdc.SetId(drawid)
             pdc.SetId(drawid)
-
+        
         pdc.BeginDrawing()
         pdc.BeginDrawing()
-
+        
         Debug.msg (3, "BufferedWindow.Draw(): id=%s, pdctype=%s, coord=%s" % (drawid, pdctype, coords))
         Debug.msg (3, "BufferedWindow.Draw(): id=%s, pdctype=%s, coord=%s" % (drawid, pdctype, coords))
-
+        
         if pdctype == 'clear': # erase the display
         if pdctype == 'clear': # erase the display
             bg = wx.WHITE_BRUSH
             bg = wx.WHITE_BRUSH
             pdc.SetBackground(bg)
             pdc.SetBackground(bg)
@@ -126,7 +105,7 @@ class BufferedWindow(wx.Window):
             self.Refresh()
             self.Refresh()
             pdc.EndDrawing()
             pdc.EndDrawing()
             return
             return
-
+        
         if pdctype == 'image':
         if pdctype == 'image':
             bg = wx.TRANSPARENT_BRUSH
             bg = wx.TRANSPARENT_BRUSH
             pdc.SetBackground(bg)
             pdc.SetBackground(bg)
@@ -134,17 +113,15 @@ class BufferedWindow(wx.Window):
             w,h = bitmap.GetSize()
             w,h = bitmap.GetSize()
             pdc.DrawBitmap(bitmap, coords[0], coords[1], True) # draw the composite map
             pdc.DrawBitmap(bitmap, coords[0], coords[1], True) # draw the composite map
             pdc.SetIdBounds(drawid, (coords[0],coords[1],w,h))
             pdc.SetIdBounds(drawid, (coords[0],coords[1],w,h))
-
+        
         pdc.EndDrawing()
         pdc.EndDrawing()
         self.Refresh()
         self.Refresh()
-
+        
     def OnPaint(self, event):
     def OnPaint(self, event):
+        """!Draw psuedo DC to buffer
         """
         """
-        Draw psuedo DC to buffer
-        """
-
-        dc = wx.BufferedPaintDC(self, self._Buffer)
-
+        dc = wx.BufferedPaintDC(self, self._buffer)
+        
         # use PrepareDC to set position correctly
         # use PrepareDC to set position correctly
         self.PrepareDC(dc)
         self.PrepareDC(dc)
         # we need to clear the dc BEFORE calling PrepareDC
         # we need to clear the dc BEFORE calling PrepareDC
@@ -157,80 +134,83 @@ class BufferedWindow(wx.Window):
         r = rgn.GetBox()
         r = rgn.GetBox()
         # draw to the dc using the calculated clipping rect
         # draw to the dc using the calculated clipping rect
         self.pdc.DrawToDCClipped(dc,r)
         self.pdc.DrawToDCClipped(dc,r)
-
-
+        
     def OnSize(self, event):
     def OnSize(self, event):
+        """!Init image size to match window size
         """
         """
-         Init image size to match window size
-        """
-
-            # set size of the input image
+        # set size of the input image
         self.Map.width, self.Map.height = self.GetClientSize()
         self.Map.width, self.Map.height = self.GetClientSize()
-
+        
         # Make new off screen bitmap: this bitmap will always have the
         # Make new off screen bitmap: this bitmap will always have the
         # current drawing in it, so it can be used to save the image to
         # current drawing in it, so it can be used to save the image to
         # a file, or whatever.
         # a file, or whatever.
-        self._Buffer = wx.EmptyBitmap(self.Map.width, self.Map.height)
-
+        self._buffer = wx.EmptyBitmap(self.Map.width, self.Map.height)
+        
         # get the image to be rendered
         # get the image to be rendered
         self.img = self.GetImage()
         self.img = self.GetImage()
-
+        
         # update map display
         # update map display
         if self.img and self.Map.width + self.Map.height > 0: # scale image during resize
         if self.img and self.Map.width + self.Map.height > 0: # scale image during resize
             self.img = self.img.Scale(self.Map.width, self.Map.height)
             self.img = self.img.Scale(self.Map.width, self.Map.height)
             self.render = False
             self.render = False
             self.UpdateHist()
             self.UpdateHist()
-
+        
         # re-render image on idle
         # re-render image on idle
         self.resize = True
         self.resize = True
-
+        
     def OnIdle(self, event):
     def OnIdle(self, event):
+        """!Only re-render a histogram image from GRASS during idle
+        time instead of multiple times during resizing.
         """
         """
-        Only re-render a histogram image from GRASS during
-        idle time instead of multiple times during resizing.
-            """
-
         if self.resize:
         if self.resize:
             self.render = True
             self.render = True
             self.UpdateHist()
             self.UpdateHist()
         event.Skip()
         event.Skip()
-
-    def SaveToFile(self, FileName, FileType):
-        """
-        This will save the contents of the buffer
-        to the specified file. See the wx.Windows docs for
-        wx.Bitmap::SaveFile for the details
-        """
-        dc = wx.BufferedPaintDC(self, self._Buffer)
+        
+    def SaveToFile(self, FileName, FileType, width, height):
+        """!This will save the contents of the buffer to the specified
+        file. See the wx.Windows docs for wx.Bitmap::SaveFile for the
+        details
+        """
+        busy = wx.BusyInfo(message=_("Please wait, exporting image..."),
+                           parent=self)
+        wx.Yield()
+        
+        self.Map.ChangeMapSize((width, height))
+        ibuffer = wx.EmptyBitmap(max(1, width), max(1, height))
+        self.Map.Render(force=True, windres = True)
+        img = self.GetImage()
+        self.Draw(self.pdc, img, drawid = 99)
+        dc = wx.BufferedPaintDC(self, ibuffer)
+        dc.Clear()
+        self.PrepareDC(dc)
         self.pdc.DrawToDC(dc)
         self.pdc.DrawToDC(dc)
-        self._Buffer.SaveFile(FileName, FileType)
-
+        ibuffer.SaveFile(FileName, FileType)
+        
+        busy.Destroy()
+        
     def GetImage(self):
     def GetImage(self):
-        """
-        Converts files to wx.Image
+        """!Converts files to wx.Image
         """
         """
         if self.Map.mapfile and os.path.isfile(self.Map.mapfile) and \
         if self.Map.mapfile and os.path.isfile(self.Map.mapfile) and \
                 os.path.getsize(self.Map.mapfile):
                 os.path.getsize(self.Map.mapfile):
             img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
             img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
         else:
         else:
             img = None
             img = None
-
+        
         self.imagedict[img] = 99 # set image PeudoDC ID
         self.imagedict[img] = 99 # set image PeudoDC ID
         return img
         return img
-
-
-    def UpdateHist(self, img=None):
+    
+    def UpdateHist(self, img = None):
+        """!Update canvas if histogram options changes or window
+        changes geometry
         """
         """
-        Update canvas if histogram options changes or window changes geometry
-        """
-
         Debug.msg (2, "BufferedWindow.UpdateHist(%s): render=%s" % (img, self.render))
         Debug.msg (2, "BufferedWindow.UpdateHist(%s): render=%s" % (img, self.render))
         oldfont = ""
         oldfont = ""
         oldencoding = ""
         oldencoding = ""
-
+        
         if self.render:
         if self.render:
             # render new map images
             # render new map images
-
             # set default font and encoding environmental variables
             # set default font and encoding environmental variables
             if "GRASS_FONT" in os.environ:
             if "GRASS_FONT" in os.environ:
                 oldfont = os.environ["GRASS_FONT"]
                 oldfont = os.environ["GRASS_FONT"]
@@ -241,294 +221,230 @@ class BufferedWindow(wx.Window):
                 os.environ[GRASS_ENCODING] = self.parent.encoding
                 os.environ[GRASS_ENCODING] = self.parent.encoding
             
             
             # using active comp region
             # using active comp region
-            self.Map.GetRegion(update=True)
+            self.Map.GetRegion(update = True)
             
             
             self.Map.width, self.Map.height = self.GetClientSize()
             self.Map.width, self.Map.height = self.GetClientSize()
-            self.mapfile = self.Map.Render(force=self.render)
+            self.mapfile = self.Map.Render(force = self.render)
             self.img = self.GetImage()
             self.img = self.GetImage()
             self.resize = False
             self.resize = False
-
+        
         if not self.img: return
         if not self.img: return
         try:
         try:
             id = self.imagedict[self.img]
             id = self.imagedict[self.img]
         except:
         except:
             return
             return
-
+        
         # paint images to PseudoDC
         # paint images to PseudoDC
         self.pdc.Clear()
         self.pdc.Clear()
         self.pdc.RemoveAll()
         self.pdc.RemoveAll()
-        self.Draw(self.pdc, self.img, drawid=id) # draw map image background
-
+        self.Draw(self.pdc, self.img, drawid = id) # draw map image background
+        
         self.resize = False
         self.resize = False
-
+        
         # update statusbar
         # update statusbar
         # Debug.msg (3, "BufferedWindow.UpdateHist(%s): region=%s" % self.Map.region)
         # Debug.msg (3, "BufferedWindow.UpdateHist(%s): region=%s" % self.Map.region)
         self.Map.SetRegion()
         self.Map.SetRegion()
         self.parent.statusbar.SetStatusText("Raster/Image map layer <%s>" % self.parent.mapname)
         self.parent.statusbar.SetStatusText("Raster/Image map layer <%s>" % self.parent.mapname)
-
+        
         # set default font and encoding environmental variables
         # set default font and encoding environmental variables
         if oldfont != "":
         if oldfont != "":
             os.environ["GRASS_FONT"] = oldfont
             os.environ["GRASS_FONT"] = oldfont
         if oldencoding != "":
         if oldencoding != "":
             os.environ["GRASS_ENCODING"] = oldencoding
             os.environ["GRASS_ENCODING"] = oldencoding
-
+        
     def EraseMap(self):
     def EraseMap(self):
+        """!Erase the map display
         """
         """
-        Erase the map display
-        """
-        self.Draw(self.pdc, pdctype='clear')
-
+        self.Draw(self.pdc, pdctype = 'clear')
+        
 class HistFrame(wx.Frame):
 class HistFrame(wx.Frame):
+    """!Main frame for hisgram display window.  Uses d.histogram
+    rendered onto canvas
     """
     """
-    Main frame for hisgram display window.
-    Uses d.histogram rendered onto canvas
-    """
-
-    def __init__(self, parent=None, id = wx.ID_ANY, title="Histogram of image or raster map",
-                 pos=wx.DefaultPosition, size=wx.DefaultSize,
-                 style=wx.DEFAULT_FRAME_STYLE):
-
-        wx.Frame.__init__(self, parent, id, title, pos, size, style)
-
-        toolbar = self.__createToolBar()
-
+    def __init__(self, parent = None, id = wx.ID_ANY,
+                 title = _("GRASS GIS Histogram of image or raster map"),
+                 style = wx.DEFAULT_FRAME_STYLE, **kwargs):
+        wx.Frame.__init__(self, parent, id, title, style = style, **kwargs)
+        self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
+        
         self.Map   = render.Map()  # instance of render.Map to be associated with display
         self.Map   = render.Map()  # instance of render.Map to be associated with display
         self.layer = None          # reference to layer with histogram
         self.layer = None          # reference to layer with histogram
-        #
-        # Set the size & cursor
-        #
-        self.SetClientSize(size)
-        self.iconsize = (16, 16)
-
+        
         # Init variables
         # Init variables
         self.params = {}  # previously set histogram parameters
         self.params = {}  # previously set histogram parameters
         self.propwin = '' # ID of properties dialog
         self.propwin = '' # ID of properties dialog
-
+        
         self.font = ""
         self.font = ""
         self.encoding = 'ISO-8859-1' # default encoding for display fonts
         self.encoding = 'ISO-8859-1' # default encoding for display fonts
+        
+        self.toolbar = HistogramToolbar(parent = self)
+        self.SetToolBar(self.toolbar)
 
 
-        #
         # Add statusbar
         # Add statusbar
-        #
         self.mapname = ''
         self.mapname = ''
-        self.statusbar = self.CreateStatusBar(number=1, style=0)
+        self.statusbar = self.CreateStatusBar(number = 1, style = 0)
         # self.statusbar.SetStatusWidths([-2, -1])
         # self.statusbar.SetStatusWidths([-2, -1])
         hist_frame_statusbar_fields = ["Histogramming %s" % self.mapname]
         hist_frame_statusbar_fields = ["Histogramming %s" % self.mapname]
         for i in range(len(hist_frame_statusbar_fields)):
         for i in range(len(hist_frame_statusbar_fields)):
             self.statusbar.SetStatusText(hist_frame_statusbar_fields[i], i)
             self.statusbar.SetStatusText(hist_frame_statusbar_fields[i], i)
-
-        #
+        
         # Init map display
         # Init map display
-        #
         self.InitDisplay() # initialize region values
         self.InitDisplay() # initialize region values
-
+        
         # initialize buffered DC
         # initialize buffered DC
-        self.HistWindow = BufferedWindow(self, id = wx.ID_ANY, Map=self.Map) # initialize buffered DC
-
-        #
+        self.HistWindow = BufferedWindow(self, id = wx.ID_ANY, Map = self.Map) # initialize buffered DC
+        
         # Bind various events
         # Bind various events
-        #
         self.Bind(wx.EVT_CLOSE,    self.OnCloseWindow)
         self.Bind(wx.EVT_CLOSE,    self.OnCloseWindow)
-
-        #
+        
         # Init print module and classes
         # Init print module and classes
-        #
         self.printopt = disp_print.PrintOptions(self, self.HistWindow)
         self.printopt = disp_print.PrintOptions(self, self.HistWindow)
-
-        #
+        
         # Add layer to the map
         # Add layer to the map
-        #
-        self.layer = self.Map.AddLayer(type="command", name='histogram', command=['d.histogram'],
-                                       l_active=False, l_hidden=False, l_opacity=1, l_render=False)
-
-
-    def __createToolBar(self):
-        """!Creates toolbar"""
-
-        toolbar = self.CreateToolBar()
-        for each in self.toolbarData():
-            self.AddToolbarButton(toolbar, *each)
-        toolbar.Realize()
-
-    def AddToolbarButton(self, toolbar, label, icon, help, handler):
-        """!Adds buttons to the toolbar"""
-
-        if not label:
-            toolbar.AddSeparator()
-            return
-        tool = toolbar.AddLabelTool(id=wx.ID_ANY, label=label, bitmap=icon, shortHelp=help)
-        self.Bind(wx.EVT_TOOL, handler, tool)
-
-    def toolbarData(self):
-
-        return   (
-                 ('histogram',
-                  Icons["histogram"].GetBitmap(),
-                  Icons["histogram"].GetLabel(),
-                  self.OnOptions),
-                 ('rendermap',
-                  Icons["displaymap"].GetBitmap(),
-                  Icons["displaymap"].GetLabel(),
-                  self.OnRender),
-                 ('erase',
-                  Icons["erase"].GetBitmap(),
-                  Icons["erase"].GetLabel(),
-                  self.OnErase),
-                 ('font',
-                  Icons["font"].GetBitmap(),
-                  Icons["font"].GetLabel(),
-                  self.SetHistFont),
-                 ('', '', '', ''),
-                 ('save', 
-                  Icons["savefile"].GetBitmap(),
-                  Icons["savefile"].GetLabel(),
-                  self.SaveToFile),
-                 ('print',
-                  Icons["printmap"].GetBitmap(),
-                  Icons["printmap"].GetLabel(),
-                  self.PrintMenu),
-                 ('quit', 
-                  Icons["quit"].GetBitmap(),
-                  Icons["quit"].GetLabel(),
-                  self.OnQuit))
-
+        self.layer = self.Map.AddLayer(type = "command", name = 'histogram', command = ['d.histogram'],
+                                       l_active = False, l_hidden = False, l_opacity = 1, l_render = False)
+        
     def InitDisplay(self):
     def InitDisplay(self):
-        """
-        Initialize histogram display, set dimensions and region
+        """!Initialize histogram display, set dimensions and region
         """
         """
         self.width, self.height = self.GetClientSize()
         self.width, self.height = self.GetClientSize()
         self.Map.geom = self.width, self.height
         self.Map.geom = self.width, self.height
-
+        
     def OnOptions(self, event):
     def OnOptions(self, event):
         """!Change histogram settings"""
         """!Change histogram settings"""
-
         cmd = ['d.histogram']
         cmd = ['d.histogram']
         if self.mapname != '':
         if self.mapname != '':
             cmd.append('map=%s' % self.mapname)
             cmd.append('map=%s' % self.mapname)
-
+        
         menuform.GUI().ParseCommand(cmd,
         menuform.GUI().ParseCommand(cmd,
-                                    completed=(self.GetOptData, None, self.params),
-                                    parentframe=self)
+                                    completed = (self.GetOptData, None, self.params),
+                                    parentframe = self)
         
         
     def GetOptData(self, dcmd, layer, params, propwin):
     def GetOptData(self, dcmd, layer, params, propwin):
-        """
-        Callback method for histogram command generated by
-        dialog created in menuform.py
+        """!Callback method for histogram command generated by dialog
+        created in menuform.py
         """
         """
         if dcmd:
         if dcmd:
-            name = utils.GetLayerNameFromCmd(dcmd, fullyQualified=True)
+            name = utils.GetLayerNameFromCmd(dcmd, fullyQualified = True)
             self.SetHistLayer(name)
             self.SetHistLayer(name)
         self.params = params
         self.params = params
         self.propwin = propwin
         self.propwin = propwin
-
+        
         self.HistWindow.UpdateHist()
         self.HistWindow.UpdateHist()
-
+        
     def SetHistLayer(self, name):
     def SetHistLayer(self, name):
-        """
-        Set histogram layer
+        """!Set histogram layer
         """
         """
         self.mapname = name
         self.mapname = name
-
-        self.layer = self.Map.ChangeLayer(layer=self.layer,
-                                          command=[['d.histogram', 'map=%s' % self.mapname],],
-                                          active=True)
-
+        
+        self.layer = self.Map.ChangeLayer(layer = self.layer,
+                                          command = [['d.histogram', 'map=%s' % self.mapname],],
+                                          active = True)
+        
         return self.layer
         return self.layer
 
 
     def SetHistFont(self, event):
     def SetHistFont(self, event):
+        """!Set font for histogram. If not set, font will be default
+        display font.
         """
         """
-        Set font for histogram. If not
-        set, font will be default display font.
-        """
-
-        dlg = DefaultFontDialog(parent=self, id=wx.ID_ANY,
-                                title=_('Select font for histogram text'))        
+        dlg = DefaultFontDialog(parent = self, id = wx.ID_ANY,
+                                title = _('Select font for histogram text'))        
         dlg.fontlb.SetStringSelection(self.font, True)
         dlg.fontlb.SetStringSelection(self.font, True)
         
         
         if dlg.ShowModal() == wx.ID_CANCEL:
         if dlg.ShowModal() == wx.ID_CANCEL:
             dlg.Destroy()
             dlg.Destroy()
             return
             return
-
+        
         # set default font type, font, and encoding to whatever selected in dialog
         # set default font type, font, and encoding to whatever selected in dialog
         if dlg.font != None:
         if dlg.font != None:
             self.font = dlg.font
             self.font = dlg.font
         if dlg.encoding != None:
         if dlg.encoding != None:
             self.encoding = dlg.encoding
             self.encoding = dlg.encoding
-
+        
         dlg.Destroy()
         dlg.Destroy()
         self.HistWindow.UpdateHist()
         self.HistWindow.UpdateHist()
 
 
     def OnErase(self, event):
     def OnErase(self, event):
+        """!Erase the histogram display
         """
         """
-        Erase the histogram display
-        """
-        self.HistWindow.Draw(self.HistWindow.pdc, pdctype='clear')
-
+        self.HistWindow.Draw(self.HistWindow.pdc, pdctype = 'clear')
+        
     def OnRender(self, event):
     def OnRender(self, event):
-        """
-        Re-render histogram
+        """!Re-render histogram
         """
         """
         self.HistWindow.UpdateHist()
         self.HistWindow.UpdateHist()
-
+        
+    def GetWindow(self):
+        """!Get buffered window"""
+        return self.HistWindow
+    
     def SaveToFile(self, event):
     def SaveToFile(self, event):
+        """!Save to file
         """
         """
-        Save to file
-        """
-        filetype =  "PNG file (*.png)|*.png|"\
-                    "TIF file (*.tif)|*.tif|"\
-                    "GIF file (*.gif)|*.gif"
-
-        dlg = wx.FileDialog(self, "Choose a file name to save the image as a PNG to",
-            defaultDir = "",
-            defaultFile = "",
-            wildcard = filetype,
-            style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
+        filetype, ltype = gdialogs.GetImageHandlers(self.HistWindow.img)
+        
+        # get size
+        dlg = gdialogs.ImageSizeDialog(self)
+        dlg.CentreOnParent()
+        if dlg.ShowModal() != wx.ID_OK:
+            dlg.Destroy()
+            return
+        width, height = dlg.GetValues()
+        dlg.Destroy()
+        
+        # get filename
+        dlg = wx.FileDialog(parent = self,
+                            message = _("Choose a file name to save the image "
+                                        "(no need to add extension)"),
+                            wildcard = filetype,
+                            style=wx.SAVE | wx.FD_OVERWRITE_PROMPT)
+        
         if dlg.ShowModal() == wx.ID_OK:
         if dlg.ShowModal() == wx.ID_OK:
-            base = os.path.splitext(dlg.GetPath())[0]
-            ext = os.path.splitext(dlg.GetPath())[1]
-            if dlg.GetFilterIndex() == 0:
-                type = wx.BITMAP_TYPE_PNG
-                path = dlg.GetPath()
-                if ext != '.png': path = base+'.png'
-            elif dlg.GetFilterIndex() == 1:
-                type = wx.BITMAP_TYPE_TIF
-                if ext != '.tif': path = base+'.tif'
-            elif dlg.GetFilterIndex() == 2:
-                type = wx.BITMAP_TYPE_TIF
-                if ext != '.gif': path = base+'.gif'
-            self.HistWindow.SaveToFile(path, type)
+            path = dlg.GetPath()
+            if not path:
+                dlg.Destroy()
+                return
+            
+            base, ext = os.path.splitext(path)
+            fileType = ltype[dlg.GetFilterIndex()]['type']
+            extType  = ltype[dlg.GetFilterIndex()]['ext']
+            if ext != extType:
+                path = base + '.' + extType
+            
+            self.HistWindow.SaveToFile(path, fileType,
+                                       width, height)
+        
+        self.HistWindow.UpdateHist()
         dlg.Destroy()
         dlg.Destroy()
-
+        
     def PrintMenu(self, event):
     def PrintMenu(self, event):
-        """
-        Print options and output menu
+        """!Print options and output menu
         """
         """
         point = wx.GetMousePosition()
         point = wx.GetMousePosition()
         printmenu = wx.Menu()
         printmenu = wx.Menu()
         # Add items to the menu
         # Add items to the menu
-        setup = wx.MenuItem(printmenu, -1,'Page setup')
+        setup = wx.MenuItem(printmenu, id = wx.ID_ANY, text = _('Page setup'))
         printmenu.AppendItem(setup)
         printmenu.AppendItem(setup)
         self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
         self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
-
-        preview = wx.MenuItem(printmenu, -1,'Print preview')
+        
+        preview = wx.MenuItem(printmenu, id = wx.ID_ANY, text = _('Print preview'))
         printmenu.AppendItem(preview)
         printmenu.AppendItem(preview)
         self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
         self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
-
-        doprint = wx.MenuItem(printmenu, -1,'Print display')
+        
+        doprint = wx.MenuItem(printmenu, id = wx.ID_ANY, text = _('Print display'))
         printmenu.AppendItem(doprint)
         printmenu.AppendItem(doprint)
         self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
         self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
-
+        
         # Popup the menu.  If an item is selected then its handler
         # Popup the menu.  If an item is selected then its handler
         # will be called before PopupMenu returns.
         # will be called before PopupMenu returns.
         self.PopupMenu(printmenu)
         self.PopupMenu(printmenu)
         printmenu.Destroy()
         printmenu.Destroy()
-
+        
     def OnQuit(self, event):
     def OnQuit(self, event):
         self.Close(True)
         self.Close(True)
-
+        
     def OnCloseWindow(self, event):
     def OnCloseWindow(self, event):
-        """
-        Window closed
+        """!Window closed
         Also remove associated rendered images
         Also remove associated rendered images
         """
         """
         try:
         try:
@@ -537,5 +453,4 @@ class HistFrame(wx.Frame):
             pass
             pass
         self.Map.Clean()
         self.Map.Clean()
         self.Destroy()
         self.Destroy()
-
-
+        

+ 50 - 2
gui/wxpython/gui_modules/toolbars.py

@@ -12,7 +12,8 @@ Classes:
  - ProfileToolbar
  - ProfileToolbar
  - NvizToolbar
  - NvizToolbar
  - ModelToolbar
  - ModelToolbar
-
+ - HistogramToolbar
+ 
 (C) 2007-2010 by the GRASS Development Team
 (C) 2007-2010 by the GRASS Development Team
 This program is free software under the GNU General Public License
 This program is free software under the GNU General Public License
 (>=v2). Read the file COPYING that comes with GRASS for details.
 (>=v2). Read the file COPYING that comes with GRASS for details.
@@ -1447,5 +1448,52 @@ class ModelToolbar(AbstractToolbar):
              wx.ITEM_NORMAL, Icons['quit'].GetLabel(), Icons['quit'].GetDesc(),
              wx.ITEM_NORMAL, Icons['quit'].GetLabel(), Icons['quit'].GetDesc(),
              self.parent.OnCloseWindow),
              self.parent.OnCloseWindow),
             )
             )
-    
+
+class HistogramToolbar(AbstractToolbar):
+    """!Histogram modeler toolbar (see histogram.py)
+    """
+    def __init__(self, parent):
+        AbstractToolbar.__init__(self, parent)
+        
+        self.InitToolbar(self.ToolbarData())
+        
+        # realize the toolbar
+        self.Realize()
+        
+    def ToolbarData(self):
+        """!Toolbar data"""
+        self.histogram = wx.NewId()
+        self.rendermap = wx.NewId()
+        self.erase = wx.NewId()
+        self.font = wx.NewId()
+        self.save = wx.NewId()
+        self.hprint = wx.NewId()
+        self.quit = wx.NewId()
+        
+        # tool, label, bitmap, kind, shortHelp, longHelp, handler
+        return (
+            (self.histogram, 'histogram', Icons["histogram"].GetBitmap(),
+             wx.ITEM_NORMAL, Icons["histogram"].GetLabel(), Icons["histogram"].GetDesc(),
+             self.parent.OnOptions),
+            (self.rendermap, 'rendermap', Icons["displaymap"].GetBitmap(),
+             wx.ITEM_NORMAL, Icons["displaymap"].GetLabel(), Icons["displaymap"].GetDesc(),
+             self.parent.OnRender),
+            (self.erase, 'erase', Icons["erase"].GetBitmap(),
+             wx.ITEM_NORMAL, Icons["erase"].GetLabel(), Icons["erase"].GetDesc(),
+             self.parent.OnErase),
+            (self.font, 'font', Icons["font"].GetBitmap(),
+             wx.ITEM_NORMAL, Icons["font"].GetLabel(), Icons["font"].GetDesc(),
+             self.parent.SetHistFont),
+            ('', '', '', '', '', '', ''),
+            (self.save, 'save', Icons["savefile"].GetBitmap(),
+             wx.ITEM_NORMAL, Icons["savefile"].GetLabel(), Icons["savefile"].GetDesc(),
+             self.parent.SaveToFile),
+            (self.hprint, 'print', Icons["printmap"].GetBitmap(),
+             wx.ITEM_NORMAL, Icons["printmap"].GetLabel(), Icons["printmap"].GetDesc(),
+             self.parent.PrintMenu),
+            ('', '', '', '', '', '', ''),
+            (self.quit, 'quit', Icons["quit"].GetBitmap(),
+             wx.ITEM_NORMAL, Icons["quit"].GetLabel(), Icons["quit"].GetDesc(),
+             self.parent.OnQuit)
+            )