decorations.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. """
  2. @package mapwin.decorations
  3. @brief Map display decorations (overlays) - text, barscale and legend
  4. Classes:
  5. - decorations::OverlayController
  6. - decorations::BarscaleController
  7. - decorations::ArrowController
  8. - decorations::LegendController
  9. - decorations::TextLayerDialog
  10. (C) 2006-2014 by the GRASS Development Team
  11. This program is free software under the GNU General Public License
  12. (>=v2). Read the file COPYING that comes with GRASS for details.
  13. @author Anna Kratochvilova <kratochanna gmail.com>
  14. """
  15. import os
  16. from core.utils import _
  17. import wx
  18. from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
  19. from grass.pydispatch.signal import Signal
  20. try:
  21. from PIL import Image
  22. hasPIL = True
  23. except ImportError:
  24. hasPIL = False
  25. class OverlayId:
  26. legendId = 0
  27. barscaleId = 1
  28. arrowId = 2
  29. class OverlayController(object):
  30. """Base class for decorations (barscale, legend) controller."""
  31. def __init__(self, renderer, giface):
  32. self._giface = giface
  33. self._renderer = renderer
  34. self._overlay = None
  35. self._coords = None
  36. self._pdcType = 'image'
  37. self._propwin = None
  38. self._defaultAt = ''
  39. self._cmd = None # to be set by user
  40. self._name = None # to be defined by subclass
  41. self._id = None # to be defined by subclass
  42. self._dialog = None
  43. # signals that overlay or its visibility changed
  44. self.overlayChanged = Signal('OverlayController::overlayChanged')
  45. def SetCmd(self, cmd):
  46. hasAt = False
  47. for i in cmd:
  48. if i.startswith("at="):
  49. hasAt = True
  50. # reset coordinates, 'at' values will be used, see GetCoords
  51. self._coords = None
  52. break
  53. if not hasAt:
  54. cmd.append(self._defaultAt)
  55. self._cmd = cmd
  56. def GetCmd(self):
  57. return self._cmd
  58. cmd = property(fset=SetCmd, fget=GetCmd)
  59. def SetCoords(self, coords):
  60. self._coords = list(coords)
  61. def GetCoords(self):
  62. if self._coords is None: # initial position
  63. x, y = self.GetPlacement((self._renderer.width, self._renderer.height))
  64. self._coords = [x, y]
  65. return self._coords
  66. coords = property(fset=SetCoords, fget=GetCoords)
  67. def GetPdcType(self):
  68. return self._pdcType
  69. pdcType = property(fget=GetPdcType)
  70. def GetName(self):
  71. return self._name
  72. name = property(fget=GetName)
  73. def GetId(self):
  74. return self._id
  75. id = property(fget=GetId)
  76. def GetPropwin(self):
  77. return self._propwin
  78. def SetPropwin(self, win):
  79. self._propwin = win
  80. propwin = property(fget=GetPropwin, fset=SetPropwin)
  81. def GetLayer(self):
  82. return self._overlay
  83. layer = property(fget=GetLayer)
  84. def GetDialog(self):
  85. return self._dialog
  86. def SetDialog(self, win):
  87. self._dialog = win
  88. dialog = property(fget=GetDialog, fset=SetDialog)
  89. def IsShown(self):
  90. if self._overlay and self._overlay.IsActive() and self._overlay.IsRendered():
  91. return True
  92. return False
  93. def Show(self, show=True):
  94. """Activate or deactivate overlay."""
  95. if show:
  96. if not self._overlay:
  97. self._add()
  98. self._overlay.SetActive(True)
  99. self._update()
  100. else:
  101. self.Hide()
  102. self.overlayChanged.emit()
  103. def Hide(self):
  104. if self._overlay:
  105. self._overlay.SetActive(False)
  106. self.overlayChanged.emit()
  107. def GetOptData(self, dcmd, layer, params, propwin):
  108. """Called after options are set through module dialog.
  109. :param dcmd: resulting command
  110. :param layer: not used
  111. :param params: module parameters (not used)
  112. :param propwin: dialog window
  113. """
  114. if not dcmd:
  115. return
  116. self._cmd = dcmd
  117. self._dialog = propwin
  118. self.Show()
  119. def _add(self):
  120. self._overlay = self._renderer.AddOverlay(id=self._id, ltype=self._name,
  121. command=self.cmd, active=False,
  122. render=True, hidden=True)
  123. # check if successful
  124. def _update(self):
  125. self._renderer.ChangeOverlay(id=self._id, command=self._cmd)
  126. def CmdIsValid(self):
  127. """If command is valid"""
  128. return True
  129. def GetPlacement(self, screensize):
  130. """Get coordinates where to place overlay in a reasonable way
  131. :param screensize: screen size
  132. """
  133. if not hasPIL:
  134. self._giface.WriteWarning(_("Please install Python Imaging Library (PIL)\n"
  135. "for better control of legend and other decorations."))
  136. return 0, 0
  137. for param in self._cmd:
  138. if not param.startswith('at'):
  139. continue
  140. x, y = [float(number) for number in param.split('=')[1].split(',')]
  141. x = int((x / 100.) * screensize[0])
  142. y = int((1 - y / 100.) * screensize[1])
  143. return x, y
  144. class BarscaleController(OverlayController):
  145. def __init__(self, renderer, giface):
  146. OverlayController.__init__(self, renderer, giface)
  147. self._id = OverlayId.barscaleId
  148. self._name = 'barscale'
  149. # different from default because the reference point is not in the middle
  150. self._defaultAt = 'at=0,98'
  151. self._cmd = ['d.barscale', self._defaultAt]
  152. class ArrowController(OverlayController):
  153. def __init__(self, renderer, giface):
  154. OverlayController.__init__(self, renderer, giface)
  155. self._id = OverlayId.arrowId
  156. self._name = 'arrow'
  157. # different from default because the reference point is not in the middle
  158. self._defaultAt = 'at=85.0,25.0'
  159. self._cmd = ['d.northarrow', self._defaultAt]
  160. class LegendController(OverlayController):
  161. def __init__(self, renderer, giface):
  162. OverlayController.__init__(self, renderer, giface)
  163. self._id = OverlayId.legendId
  164. self._name = 'legend'
  165. # TODO: synchronize with d.legend?
  166. self._defaultAt = 'at=5,50,7,10'
  167. self._cmd = ['d.legend', self._defaultAt]
  168. def GetPlacement(self, screensize):
  169. if not hasPIL:
  170. self._giface.WriteWarning(_("Please install Python Imaging Library (PIL)\n"
  171. "for better control of legend and other decorations."))
  172. return 0, 0
  173. for param in self._cmd:
  174. if not param.startswith('at'):
  175. continue
  176. b, t, l, r = [float(number) for number in param.split('=')[1].split(',')] # pylint: disable-msg=W0612
  177. x = int((l / 100.) * screensize[0])
  178. y = int((1 - t / 100.) * screensize[1])
  179. return x, y
  180. def CmdIsValid(self):
  181. inputs = 0
  182. for param in self._cmd[1:]:
  183. param = param.split('=')
  184. if len(param) == 1:
  185. inputs += 1
  186. else:
  187. if param[0] == 'raster' and len(param) == 2:
  188. inputs += 1
  189. elif param[0] == 'raster_3d' and len(param) == 2:
  190. inputs += 1
  191. if inputs == 1:
  192. return True
  193. return False
  194. def ResizeLegend(self, begin, end, screenSize):
  195. """Resize legend according to given bbox coordinates."""
  196. w = abs(begin[0] - end[0])
  197. h = abs(begin[1] - end[1])
  198. if begin[0] < end[0]:
  199. x = begin[0]
  200. else:
  201. x = end[0]
  202. if begin[1] < end[1]:
  203. y = begin[1]
  204. else:
  205. y = end[1]
  206. at = [(screenSize[1] - (y + h)) / float(screenSize[1]) * 100,
  207. (screenSize[1] - y) / float(screenSize[1]) * 100,
  208. x / float(screenSize[0]) * 100,
  209. (x + w) / float(screenSize[0]) * 100]
  210. atStr = "at=%d,%d,%d,%d" % (at[0], at[1], at[2], at[3])
  211. for i, subcmd in enumerate(self._cmd):
  212. if subcmd.startswith('at='):
  213. self._cmd[i] = atStr
  214. break
  215. self._coords = None
  216. self.Show()
  217. def StartResizing(self):
  218. """Tool in toolbar or button itself were pressed"""
  219. # prepare for resizing
  220. window = self._giface.GetMapWindow()
  221. window.SetNamedCursor('cross')
  222. window.mouse['use'] = None
  223. window.mouse['box'] = 'box'
  224. window.pen = wx.Pen(colour='Black', width=2, style=wx.SHORT_DASH)
  225. window.mouseLeftUp.connect(self._finishResizing)
  226. def _finishResizing(self):
  227. window = self._giface.GetMapWindow()
  228. window.mouseLeftUp.disconnect(self._finishResizing)
  229. screenSize = window.GetClientSizeTuple()
  230. self.ResizeLegend(window.mouse["begin"], window.mouse["end"], screenSize)
  231. self._giface.GetMapDisplay().GetMapToolbar().SelectDefault()
  232. # redraw
  233. self.overlayChanged.emit()
  234. class TextLayerDialog(wx.Dialog):
  235. """!Controls setting options and displaying/hiding map overlay decorations
  236. """
  237. def __init__(self, parent, ovlId, title, name='text', size=wx.DefaultSize,
  238. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  239. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title, style=style, size=size)
  240. self.ovlId = ovlId
  241. self.parent = parent
  242. if self.ovlId in self.parent.MapWindow.textdict.keys():
  243. self.currText = self.parent.MapWindow.textdict[self.ovlId]['text']
  244. self.currFont = self.parent.MapWindow.textdict[self.ovlId]['font']
  245. self.currClr = self.parent.MapWindow.textdict[self.ovlId]['color']
  246. self.currRot = self.parent.MapWindow.textdict[self.ovlId]['rotation']
  247. self.currCoords = self.parent.MapWindow.textdict[self.ovlId]['coords']
  248. self.currBB = self.parent.MapWindow.textdict[self.ovlId]['bbox']
  249. else:
  250. self.currClr = wx.BLACK
  251. self.currText = ''
  252. self.currFont = self.GetFont()
  253. self.currRot = 0.0
  254. self.currCoords = [10, 10]
  255. self.currBB = wx.Rect()
  256. self.sizer = wx.BoxSizer(wx.VERTICAL)
  257. box = wx.GridBagSizer(vgap=5, hgap=5)
  258. # show/hide
  259. self.chkbox = wx.CheckBox(parent=self, id=wx.ID_ANY,
  260. label=_('Show text object'))
  261. if self.parent.Map.GetOverlay(self.ovlId) is None:
  262. self.chkbox.SetValue(True)
  263. else:
  264. self.chkbox.SetValue(self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive())
  265. box.Add(item=self.chkbox, span=(1, 2),
  266. pos=(0, 0))
  267. # text entry
  268. box.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Text:")),
  269. flag=wx.ALIGN_CENTER_VERTICAL,
  270. pos=(1, 0))
  271. self.textentry = ExpandoTextCtrl(parent=self, id=wx.ID_ANY, value="", size=(300, -1))
  272. self.textentry.SetFont(self.currFont)
  273. self.textentry.SetForegroundColour(self.currClr)
  274. self.textentry.SetValue(self.currText)
  275. # get rid of unneeded scrollbar when text box first opened
  276. self.textentry.SetClientSize((300, -1))
  277. box.Add(item=self.textentry,
  278. flag=wx.EXPAND,
  279. pos=(1, 1))
  280. # rotation
  281. box.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Rotation:")),
  282. flag=wx.ALIGN_CENTER_VERTICAL,
  283. pos=(2, 0))
  284. self.rotation = wx.SpinCtrl(parent=self, id=wx.ID_ANY, value="", pos=(30, 50),
  285. size=(75, -1), style=wx.SP_ARROW_KEYS)
  286. self.rotation.SetRange(-360, 360)
  287. self.rotation.SetValue(int(self.currRot))
  288. box.Add(item=self.rotation,
  289. flag=wx.ALIGN_RIGHT,
  290. pos=(2, 1))
  291. # font
  292. box.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Font:")),
  293. flag=wx.ALIGN_CENTER_VERTICAL,
  294. pos=(3, 0))
  295. fontbtn = wx.Button(parent=self, id=wx.ID_ANY, label=_("Set font"))
  296. box.Add(item=fontbtn,
  297. flag=wx.ALIGN_RIGHT,
  298. pos=(3, 1))
  299. box.AddGrowableCol(1)
  300. box.AddGrowableRow(1)
  301. self.sizer.Add(item=box, proportion=1,
  302. flag=wx.ALL | wx.EXPAND, border=10)
  303. # note
  304. box = wx.BoxSizer(wx.HORIZONTAL)
  305. label = wx.StaticText(parent=self, id=wx.ID_ANY,
  306. label=_("Drag text with mouse in pointer mode "
  307. "to position.\nDouble-click to change options"))
  308. box.Add(item=label, proportion=0,
  309. flag=wx.ALIGN_CENTRE | wx.ALL, border=5)
  310. self.sizer.Add(item=box, proportion=0,
  311. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.ALL, border=5)
  312. line = wx.StaticLine(parent=self, id=wx.ID_ANY,
  313. size=(20, -1), style=wx.LI_HORIZONTAL)
  314. self.sizer.Add(item=line, proportion=0,
  315. flag=wx.EXPAND | wx.ALIGN_CENTRE | wx.ALL, border=5)
  316. btnsizer = wx.StdDialogButtonSizer()
  317. btn = wx.Button(parent=self, id=wx.ID_OK)
  318. btn.SetDefault()
  319. btnsizer.AddButton(btn)
  320. btn = wx.Button(parent=self, id=wx.ID_CANCEL)
  321. btnsizer.AddButton(btn)
  322. btnsizer.Realize()
  323. self.sizer.Add(item=btnsizer, proportion=0,
  324. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  325. self.SetSizer(self.sizer)
  326. self.sizer.Fit(self)
  327. # bindings
  328. self.Bind(EVT_ETC_LAYOUT_NEEDED, self.OnRefit, self.textentry)
  329. self.Bind(wx.EVT_BUTTON, self.OnSelectFont, fontbtn)
  330. self.Bind(wx.EVT_TEXT, self.OnText, self.textentry)
  331. self.Bind(wx.EVT_SPINCTRL, self.OnRotation, self.rotation)
  332. self.SetMinSize((400, 230))
  333. def OnRefit(self, event):
  334. """Resize text entry to match text"""
  335. self.sizer.Fit(self)
  336. def OnText(self, event):
  337. """Change text string"""
  338. self.currText = event.GetString()
  339. def OnRotation(self, event):
  340. """Change rotation"""
  341. self.currRot = event.GetInt()
  342. event.Skip()
  343. def OnSelectFont(self, event):
  344. """Change font"""
  345. data = wx.FontData()
  346. data.EnableEffects(True)
  347. data.SetColour(self.currClr) # set colour
  348. data.SetInitialFont(self.currFont)
  349. dlg = wx.FontDialog(self, data)
  350. if dlg.ShowModal() == wx.ID_OK:
  351. data = dlg.GetFontData()
  352. self.currFont = data.GetChosenFont()
  353. self.currClr = data.GetColour()
  354. self.textentry.SetFont(self.currFont)
  355. self.textentry.SetForegroundColour(self.currClr)
  356. self.Layout()
  357. dlg.Destroy()
  358. def GetValues(self):
  359. """Get text properties"""
  360. return {'text': self.currText,
  361. 'font': self.currFont,
  362. 'color': self.currClr,
  363. 'rotation': self.currRot,
  364. 'coords': self.currCoords,
  365. 'active': self.chkbox.IsChecked()}