histogram.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. """
  2. @package modules.histogram
  3. Plotting histogram based on d.histogram
  4. Classes:
  5. - histogram::BufferedWindow
  6. - histogram::HistogramFrame
  7. - histogram::HistogramToolbar
  8. (C) 2007, 2010-2011 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Michael Barton
  12. @author Various updates by Martin Landa <landa.martin gmail.com>
  13. """
  14. import os
  15. import sys
  16. import wx
  17. from core import globalvar
  18. from core.render import Map
  19. from gui_core.forms import GUI
  20. from mapdisp.gprint import PrintOptions
  21. from core.utils import GetLayerNameFromCmd, _
  22. from gui_core.dialogs import GetImageHandlers, ImageSizeDialog
  23. from gui_core.preferences import DefaultFontDialog
  24. from core.debug import Debug
  25. from core.gcmd import GError
  26. from gui_core.toolbars import BaseToolbar, BaseIcons
  27. class BufferedWindow(wx.Window):
  28. """A Buffered window class.
  29. When the drawing needs to change, you app needs to call the
  30. UpdateHist() method. Since the drawing is stored in a bitmap, you
  31. can also save the drawing to file by calling the
  32. SaveToFile(self,file_name,file_type) method.
  33. """
  34. def __init__(self, parent, id = wx.ID_ANY,
  35. style = wx.NO_FULL_REPAINT_ON_RESIZE,
  36. Map = None, **kwargs):
  37. wx.Window.__init__(self, parent, id = id, style = style, **kwargs)
  38. self.parent = parent
  39. self.Map = Map
  40. self.mapname = self.parent.mapname
  41. #
  42. # Flags
  43. #
  44. self.render = True # re-render the map from GRASS or just redraw image
  45. self.resize = False # indicates whether or not a resize event has taken place
  46. self.dragimg = None # initialize variable for map panning
  47. self.pen = None # pen for drawing zoom boxes, etc.
  48. #
  49. # Event bindings
  50. #
  51. self.Bind(wx.EVT_PAINT, self.OnPaint)
  52. self.Bind(wx.EVT_SIZE, self.OnSize)
  53. self.Bind(wx.EVT_IDLE, self.OnIdle)
  54. #
  55. # Render output objects
  56. #
  57. self.mapfile = None # image file to be rendered
  58. self.img = "" # wx.Image object (self.mapfile)
  59. self.imagedict = {} # images and their PseudoDC ID's for painting and dragging
  60. self.pdc = wx.PseudoDC()
  61. # will store an off screen empty bitmap for saving to file
  62. self._buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
  63. # make sure that extents are updated at init
  64. self.Map.region = self.Map.GetRegion()
  65. self.Map.SetRegion()
  66. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x:None)
  67. def Draw(self, pdc, img = None, drawid = None, pdctype = 'image', coords = [0,0,0,0]):
  68. """Draws histogram or clears window
  69. """
  70. if drawid == None:
  71. if pdctype == 'image' :
  72. drawid = imagedict[img]
  73. elif pdctype == 'clear':
  74. drawid == None
  75. else:
  76. drawid = wx.NewId()
  77. else:
  78. pdc.SetId(drawid)
  79. pdc.BeginDrawing()
  80. Debug.msg (3, "BufferedWindow.Draw(): id=%s, pdctype=%s, coord=%s" % (drawid, pdctype, coords))
  81. if pdctype == 'clear': # erase the display
  82. bg = wx.WHITE_BRUSH
  83. pdc.SetBackground(bg)
  84. pdc.Clear()
  85. self.Refresh()
  86. pdc.EndDrawing()
  87. return
  88. if pdctype == 'image':
  89. bg = wx.TRANSPARENT_BRUSH
  90. pdc.SetBackground(bg)
  91. bitmap = wx.BitmapFromImage(img)
  92. w,h = bitmap.GetSize()
  93. pdc.DrawBitmap(bitmap, coords[0], coords[1], True) # draw the composite map
  94. pdc.SetIdBounds(drawid, (coords[0],coords[1],w,h))
  95. pdc.EndDrawing()
  96. self.Refresh()
  97. def OnPaint(self, event):
  98. """Draw psuedo DC to buffer
  99. """
  100. dc = wx.BufferedPaintDC(self, self._buffer)
  101. # use PrepareDC to set position correctly
  102. # probably does nothing, removed from wxPython 2.9
  103. # self.PrepareDC(dc)
  104. # we need to clear the dc BEFORE calling PrepareDC
  105. bg = wx.Brush(self.GetBackgroundColour())
  106. dc.SetBackground(bg)
  107. dc.Clear()
  108. # create a clipping rect from our position and size
  109. # and the Update Region
  110. rgn = self.GetUpdateRegion()
  111. r = rgn.GetBox()
  112. # draw to the dc using the calculated clipping rect
  113. self.pdc.DrawToDCClipped(dc,r)
  114. def OnSize(self, event):
  115. """Init image size to match window size
  116. """
  117. # set size of the input image
  118. self.Map.width, self.Map.height = self.GetClientSize()
  119. # Make new off screen bitmap: this bitmap will always have the
  120. # current drawing in it, so it can be used to save the image to
  121. # a file, or whatever.
  122. self._buffer = wx.EmptyBitmap(self.Map.width, self.Map.height)
  123. # get the image to be rendered
  124. self.img = self.GetImage()
  125. # update map display
  126. if self.img and self.Map.width + self.Map.height > 0: # scale image during resize
  127. self.img = self.img.Scale(self.Map.width, self.Map.height)
  128. self.render = False
  129. self.UpdateHist()
  130. # re-render image on idle
  131. self.resize = True
  132. def OnIdle(self, event):
  133. """Only re-render a histogram image from GRASS during idle
  134. time instead of multiple times during resizing.
  135. """
  136. if self.resize:
  137. self.render = True
  138. self.UpdateHist()
  139. event.Skip()
  140. def SaveToFile(self, FileName, FileType, width, height):
  141. """This will save the contents of the buffer to the specified
  142. file. See the wx.Windows docs for wx.Bitmap::SaveFile for the
  143. details
  144. """
  145. busy = wx.BusyInfo(message=_("Please wait, exporting image..."),
  146. parent=self)
  147. wx.Yield()
  148. self.Map.ChangeMapSize((width, height))
  149. ibuffer = wx.EmptyBitmap(max(1, width), max(1, height))
  150. self.Map.Render(force=True, windres = True)
  151. img = self.GetImage()
  152. self.Draw(self.pdc, img, drawid = 99)
  153. dc = wx.BufferedDC(None, ibuffer)
  154. dc.Clear()
  155. # probably does nothing, removed from wxPython 2.9
  156. # self.PrepareDC(dc)
  157. self.pdc.DrawToDC(dc)
  158. ibuffer.SaveFile(FileName, FileType)
  159. busy.Destroy()
  160. def GetImage(self):
  161. """Converts files to wx.Image
  162. """
  163. if self.Map.mapfile and os.path.isfile(self.Map.mapfile) and \
  164. os.path.getsize(self.Map.mapfile):
  165. img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
  166. else:
  167. img = None
  168. self.imagedict[img] = 99 # set image PeudoDC ID
  169. return img
  170. def UpdateHist(self, img = None):
  171. """Update canvas if histogram options changes or window
  172. changes geometry
  173. """
  174. Debug.msg (2, "BufferedWindow.UpdateHist(%s): render=%s" % (img, self.render))
  175. oldfont = ""
  176. oldencoding = ""
  177. if self.render:
  178. # render new map images
  179. # set default font and encoding environmental variables
  180. if "GRASS_FONT" in os.environ:
  181. oldfont = os.environ["GRASS_FONT"]
  182. if self.parent.font != "": os.environ["GRASS_FONT"] = self.parent.font
  183. if "GRASS_ENCODING" in os.environ:
  184. oldencoding = os.environ["GRASS_ENCODING"]
  185. if self.parent.encoding != None and self.parent.encoding != "ISO-8859-1":
  186. os.environ[GRASS_ENCODING] = self.parent.encoding
  187. # using active comp region
  188. self.Map.GetRegion(update = True)
  189. self.Map.width, self.Map.height = self.GetClientSize()
  190. self.mapfile = self.Map.Render(force = self.render)
  191. self.img = self.GetImage()
  192. self.resize = False
  193. if not self.img: return
  194. try:
  195. id = self.imagedict[self.img]
  196. except:
  197. return
  198. # paint images to PseudoDC
  199. self.pdc.Clear()
  200. self.pdc.RemoveAll()
  201. self.Draw(self.pdc, self.img, drawid = id) # draw map image background
  202. self.resize = False
  203. # update statusbar
  204. # Debug.msg (3, "BufferedWindow.UpdateHist(%s): region=%s" % self.Map.region)
  205. self.Map.SetRegion()
  206. self.parent.statusbar.SetStatusText("Image/Raster map <%s>" % self.parent.mapname)
  207. # set default font and encoding environmental variables
  208. if oldfont != "":
  209. os.environ["GRASS_FONT"] = oldfont
  210. if oldencoding != "":
  211. os.environ["GRASS_ENCODING"] = oldencoding
  212. def EraseMap(self):
  213. """Erase the map display
  214. """
  215. self.Draw(self.pdc, pdctype = 'clear')
  216. class HistogramFrame(wx.Frame):
  217. """Main frame for hisgram display window. Uses d.histogram
  218. rendered onto canvas
  219. """
  220. def __init__(self, parent, giface, id=wx.ID_ANY,
  221. title = _("GRASS GIS Histogramming Tool (d.histogram)"),
  222. size = wx.Size(500, 350),
  223. style = wx.DEFAULT_FRAME_STYLE, **kwargs):
  224. wx.Frame.__init__(self, parent, id, title, size = size, style = style, **kwargs)
  225. self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  226. self._giface = giface
  227. self.Map = Map() # instance of render.Map to be associated with display
  228. self.layer = None # reference to layer with histogram
  229. # Init variables
  230. self.params = {} # previously set histogram parameters
  231. self.propwin = '' # ID of properties dialog
  232. self.font = ""
  233. self.encoding = 'ISO-8859-1' # default encoding for display fonts
  234. self.toolbar = HistogramToolbar(parent = self)
  235. # workaround for http://trac.wxwidgets.org/ticket/13888
  236. if sys.platform != 'darwin':
  237. self.SetToolBar(self.toolbar)
  238. # find selected map
  239. # might by moved outside this class
  240. # setting to None but honestly we do not handle no map case
  241. # TODO: when self.mapname is None content of map window is showed
  242. self.mapname = None
  243. layers = self._giface.GetLayerList().GetSelectedLayers(checkedOnly=False)
  244. if len(layers) > 0:
  245. self.mapname = layers[0].maplayer.name
  246. # Add statusbar
  247. self.statusbar = self.CreateStatusBar(number = 1, style = 0)
  248. # self.statusbar.SetStatusWidths([-2, -1])
  249. hist_frame_statusbar_fields = ["Histogramming %s" % self.mapname]
  250. for i in range(len(hist_frame_statusbar_fields)):
  251. self.statusbar.SetStatusText(hist_frame_statusbar_fields[i], i)
  252. # Init map display
  253. self.InitDisplay() # initialize region values
  254. # initialize buffered DC
  255. self.HistWindow = BufferedWindow(self, id = wx.ID_ANY, Map = self.Map) # initialize buffered DC
  256. # Bind various events
  257. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  258. # Init print module and classes
  259. self.printopt = PrintOptions(self, self.HistWindow)
  260. # Add layer to the map
  261. self.layer = self.Map.AddLayer(ltype = "command", name = 'histogram', command = [['d.histogram']],
  262. active = False, hidden = False, opacity = 1, render = False)
  263. if self.mapname:
  264. self.SetHistLayer(self.mapname, None)
  265. else:
  266. self.OnErase(None)
  267. wx.CallAfter(self.OnOptions, None)
  268. def InitDisplay(self):
  269. """Initialize histogram display, set dimensions and region
  270. """
  271. self.width, self.height = self.GetClientSize()
  272. self.Map.geom = self.width, self.height
  273. def OnOptions(self, event):
  274. """Change histogram settings"""
  275. cmd = ['d.histogram']
  276. if self.mapname != '':
  277. cmd.append('map=%s' % self.mapname)
  278. module = GUI(parent = self)
  279. module.ParseCommand(cmd, completed = (self.GetOptData, None, self.params))
  280. def GetOptData(self, dcmd, layer, params, propwin):
  281. """Callback method for histogram command generated by dialog
  282. created in menuform.py
  283. """
  284. if dcmd:
  285. name, found = GetLayerNameFromCmd(dcmd, fullyQualified = True,
  286. layerType = 'raster')
  287. if not found:
  288. GError(parent = propwin,
  289. message = _("Raster map <%s> not found") % name)
  290. return
  291. self.SetHistLayer(name, dcmd)
  292. self.params = params
  293. self.propwin = propwin
  294. self.HistWindow.UpdateHist()
  295. def SetHistLayer(self, name, cmd = None):
  296. """Set histogram layer
  297. """
  298. self.mapname = name
  299. if not cmd:
  300. cmd = ['d.histogram',('map=%s' % self.mapname)]
  301. self.layer = self.Map.ChangeLayer(layer = self.layer,
  302. command = [cmd],
  303. active = True)
  304. return self.layer
  305. def SetHistFont(self, event):
  306. """Set font for histogram. If not set, font will be default
  307. display font.
  308. """
  309. dlg = DefaultFontDialog(parent = self, id = wx.ID_ANY,
  310. title = _('Select font for histogram text'))
  311. dlg.fontlb.SetStringSelection(self.font, True)
  312. if dlg.ShowModal() == wx.ID_CANCEL:
  313. dlg.Destroy()
  314. return
  315. # set default font type, font, and encoding to whatever selected in dialog
  316. if dlg.font != None:
  317. self.font = dlg.font
  318. if dlg.encoding != None:
  319. self.encoding = dlg.encoding
  320. dlg.Destroy()
  321. self.HistWindow.UpdateHist()
  322. def OnErase(self, event):
  323. """Erase the histogram display
  324. """
  325. self.HistWindow.Draw(self.HistWindow.pdc, pdctype = 'clear')
  326. def OnRender(self, event):
  327. """Re-render histogram
  328. """
  329. self.HistWindow.UpdateHist()
  330. def GetWindow(self):
  331. """Get buffered window"""
  332. return self.HistWindow
  333. def SaveToFile(self, event):
  334. """Save to file
  335. """
  336. filetype, ltype = GetImageHandlers(self.HistWindow.img)
  337. # get size
  338. dlg = ImageSizeDialog(self)
  339. dlg.CentreOnParent()
  340. if dlg.ShowModal() != wx.ID_OK:
  341. dlg.Destroy()
  342. return
  343. width, height = dlg.GetValues()
  344. dlg.Destroy()
  345. # get filename
  346. dlg = wx.FileDialog(parent = self,
  347. message = _("Choose a file name to save the image "
  348. "(no need to add extension)"),
  349. wildcard = filetype,
  350. style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
  351. if dlg.ShowModal() == wx.ID_OK:
  352. path = dlg.GetPath()
  353. if not path:
  354. dlg.Destroy()
  355. return
  356. base, ext = os.path.splitext(path)
  357. fileType = ltype[dlg.GetFilterIndex()]['type']
  358. extType = ltype[dlg.GetFilterIndex()]['ext']
  359. if ext != extType:
  360. path = base + '.' + extType
  361. self.HistWindow.SaveToFile(path, fileType,
  362. width, height)
  363. self.HistWindow.UpdateHist()
  364. dlg.Destroy()
  365. def PrintMenu(self, event):
  366. """Print options and output menu
  367. """
  368. point = wx.GetMousePosition()
  369. printmenu = wx.Menu()
  370. # Add items to the menu
  371. setup = wx.MenuItem(printmenu, id = wx.ID_ANY, text = _('Page setup'))
  372. printmenu.AppendItem(setup)
  373. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  374. preview = wx.MenuItem(printmenu, id = wx.ID_ANY, text = _('Print preview'))
  375. printmenu.AppendItem(preview)
  376. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  377. doprint = wx.MenuItem(printmenu, id = wx.ID_ANY, text = _('Print display'))
  378. printmenu.AppendItem(doprint)
  379. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  380. # Popup the menu. If an item is selected then its handler
  381. # will be called before PopupMenu returns.
  382. self.PopupMenu(printmenu)
  383. printmenu.Destroy()
  384. def OnQuit(self, event):
  385. self.Close(True)
  386. def OnCloseWindow(self, event):
  387. """Window closed
  388. Also remove associated rendered images
  389. """
  390. try:
  391. self.propwin.Close(True)
  392. except:
  393. pass
  394. self.Map.Clean()
  395. self.Destroy()
  396. class HistogramToolbar(BaseToolbar):
  397. """Histogram toolbar (see histogram.py)
  398. """
  399. def __init__(self, parent):
  400. BaseToolbar.__init__(self, parent)
  401. # workaround for http://trac.wxwidgets.org/ticket/13888
  402. if sys.platform == 'darwin':
  403. parent.SetToolBar(self)
  404. self.InitToolbar(self._toolbarData())
  405. # realize the toolbar
  406. self.Realize()
  407. def _toolbarData(self):
  408. """Toolbar data"""
  409. return self._getToolbarData((('histogram', BaseIcons["histogramD"],
  410. self.parent.OnOptions),
  411. ('render', BaseIcons["display"],
  412. self.parent.OnRender),
  413. ('erase', BaseIcons["erase"],
  414. self.parent.OnErase),
  415. ('font', BaseIcons["font"],
  416. self.parent.SetHistFont),
  417. (None, ),
  418. ('save', BaseIcons["saveFile"],
  419. self.parent.SaveToFile),
  420. ('hprint', BaseIcons["print"],
  421. self.parent.PrintMenu),
  422. (None, ),
  423. ('quit', BaseIcons["quit"],
  424. self.parent.OnQuit))
  425. )