histogram.py 19 KB

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