decorations.py 15 KB

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