decorations.py 15 KB

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