histogram.py 18 KB

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