histogram.py 18 KB

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