decorations.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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:
  177. param = param.split('=')
  178. if param[0] == 'raster' and len(param) == 2:
  179. inputs += 1
  180. elif param[0] == '3draster' and len(param) == 2:
  181. inputs += 1
  182. if inputs == 1:
  183. return True
  184. return False
  185. def ResizeLegend(self, begin, end, screenSize):
  186. """Resize legend according to given bbox coordinates."""
  187. w = abs(begin[0] - end[0])
  188. h = abs(begin[1] - end[1])
  189. if begin[0] < end[0]:
  190. x = begin[0]
  191. else:
  192. x = end[0]
  193. if begin[1] < end[1]:
  194. y = begin[1]
  195. else:
  196. y = end[1]
  197. at = [(screenSize[1] - (y + h)) / float(screenSize[1]) * 100,
  198. (screenSize[1] - y) / float(screenSize[1]) * 100,
  199. x / float(screenSize[0]) * 100,
  200. (x + w) / float(screenSize[0]) * 100]
  201. atStr = "at=%d,%d,%d,%d" % (at[0], at[1], at[2], at[3])
  202. for i, subcmd in enumerate(self._cmd):
  203. if subcmd.startswith('at='):
  204. self._cmd[i] = atStr
  205. break
  206. self._coords = None
  207. self.Show()
  208. def StartResizing(self):
  209. """Tool in toolbar or button itself were pressed"""
  210. # prepare for resizing
  211. window = self._giface.GetMapWindow()
  212. window.SetNamedCursor('cross')
  213. window.mouse['use'] = None
  214. window.mouse['box'] = 'box'
  215. window.pen = wx.Pen(colour='Black', width=2, style=wx.SHORT_DASH)
  216. window.mouseLeftUp.connect(self._finishResizing)
  217. def _finishResizing(self):
  218. window = self._giface.GetMapWindow()
  219. window.mouseLeftUp.disconnect(self._finishResizing)
  220. screenSize = window.GetClientSizeTuple()
  221. self.ResizeLegend(window.mouse["begin"], window.mouse["end"], screenSize)
  222. self._giface.GetMapDisplay().GetMapToolbar().SelectDefault()
  223. # redraw
  224. self.overlayChanged.emit()
  225. class TextLayerDialog(wx.Dialog):
  226. """!Controls setting options and displaying/hiding map overlay decorations
  227. """
  228. def __init__(self, parent, ovlId, title, name='text', size=wx.DefaultSize,
  229. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  230. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title, style=style, size=size)
  231. self.ovlId = ovlId
  232. self.parent = parent
  233. if self.ovlId in self.parent.MapWindow.textdict.keys():
  234. self.currText = self.parent.MapWindow.textdict[self.ovlId]['text']
  235. self.currFont = self.parent.MapWindow.textdict[self.ovlId]['font']
  236. self.currClr = self.parent.MapWindow.textdict[self.ovlId]['color']
  237. self.currRot = self.parent.MapWindow.textdict[self.ovlId]['rotation']
  238. self.currCoords = self.parent.MapWindow.textdict[self.ovlId]['coords']
  239. self.currBB = self.parent.MapWindow.textdict[self.ovlId]['bbox']
  240. else:
  241. self.currClr = wx.BLACK
  242. self.currText = ''
  243. self.currFont = self.GetFont()
  244. self.currRot = 0.0
  245. self.currCoords = [10, 10]
  246. self.currBB = wx.Rect()
  247. self.sizer = wx.BoxSizer(wx.VERTICAL)
  248. box = wx.GridBagSizer(vgap=5, hgap=5)
  249. box.AddGrowableCol(1)
  250. box.AddGrowableRow(1)
  251. # show/hide
  252. self.chkbox = wx.CheckBox(parent=self, id=wx.ID_ANY,
  253. label=_('Show text object'))
  254. if self.parent.Map.GetOverlay(self.ovlId) is None:
  255. self.chkbox.SetValue(True)
  256. else:
  257. self.chkbox.SetValue(self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive())
  258. box.Add(item=self.chkbox, span=(1, 2),
  259. pos=(0, 0))
  260. # text entry
  261. box.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Text:")),
  262. flag=wx.ALIGN_CENTER_VERTICAL,
  263. pos=(1, 0))
  264. self.textentry = ExpandoTextCtrl(parent=self, id=wx.ID_ANY, value="", size=(300, -1))
  265. self.textentry.SetFont(self.currFont)
  266. self.textentry.SetForegroundColour(self.currClr)
  267. self.textentry.SetValue(self.currText)
  268. # get rid of unneeded scrollbar when text box first opened
  269. self.textentry.SetClientSize((300, -1))
  270. box.Add(item=self.textentry,
  271. flag=wx.EXPAND,
  272. pos=(1, 1))
  273. # rotation
  274. box.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Rotation:")),
  275. flag=wx.ALIGN_CENTER_VERTICAL,
  276. pos=(2, 0))
  277. self.rotation = wx.SpinCtrl(parent=self, id=wx.ID_ANY, value="", pos=(30, 50),
  278. size=(75, -1), style=wx.SP_ARROW_KEYS)
  279. self.rotation.SetRange(-360, 360)
  280. self.rotation.SetValue(int(self.currRot))
  281. box.Add(item=self.rotation,
  282. flag=wx.ALIGN_RIGHT,
  283. pos=(2, 1))
  284. # font
  285. box.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Font:")),
  286. flag=wx.ALIGN_CENTER_VERTICAL,
  287. pos=(3, 0))
  288. fontbtn = wx.Button(parent=self, id=wx.ID_ANY, label=_("Set font"))
  289. box.Add(item=fontbtn,
  290. flag=wx.ALIGN_RIGHT,
  291. pos=(3, 1))
  292. self.sizer.Add(item=box, proportion=1,
  293. flag=wx.ALL | wx.EXPAND, border=10)
  294. # note
  295. box = wx.BoxSizer(wx.HORIZONTAL)
  296. label = wx.StaticText(parent=self, id=wx.ID_ANY,
  297. label=_("Drag text with mouse in pointer mode "
  298. "to position.\nDouble-click to change options"))
  299. box.Add(item=label, proportion=0,
  300. flag=wx.ALIGN_CENTRE | wx.ALL, border=5)
  301. self.sizer.Add(item=box, proportion=0,
  302. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.ALL, border=5)
  303. line = wx.StaticLine(parent=self, id=wx.ID_ANY,
  304. size=(20, -1), style=wx.LI_HORIZONTAL)
  305. self.sizer.Add(item=line, proportion=0,
  306. flag=wx.EXPAND | wx.ALIGN_CENTRE | wx.ALL, border=5)
  307. btnsizer = wx.StdDialogButtonSizer()
  308. btn = wx.Button(parent=self, id=wx.ID_OK)
  309. btn.SetDefault()
  310. btnsizer.AddButton(btn)
  311. btn = wx.Button(parent=self, id=wx.ID_CANCEL)
  312. btnsizer.AddButton(btn)
  313. btnsizer.Realize()
  314. self.sizer.Add(item=btnsizer, proportion=0,
  315. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  316. self.SetSizer(self.sizer)
  317. self.sizer.Fit(self)
  318. # bindings
  319. self.Bind(EVT_ETC_LAYOUT_NEEDED, self.OnRefit, self.textentry)
  320. self.Bind(wx.EVT_BUTTON, self.OnSelectFont, fontbtn)
  321. self.Bind(wx.EVT_TEXT, self.OnText, self.textentry)
  322. self.Bind(wx.EVT_SPINCTRL, self.OnRotation, self.rotation)
  323. self.SetMinSize((400, 230))
  324. def OnRefit(self, event):
  325. """Resize text entry to match text"""
  326. self.sizer.Fit(self)
  327. def OnText(self, event):
  328. """Change text string"""
  329. self.currText = event.GetString()
  330. def OnRotation(self, event):
  331. """Change rotation"""
  332. self.currRot = event.GetInt()
  333. event.Skip()
  334. def OnSelectFont(self, event):
  335. """Change font"""
  336. data = wx.FontData()
  337. data.EnableEffects(True)
  338. data.SetColour(self.currClr) # set colour
  339. data.SetInitialFont(self.currFont)
  340. dlg = wx.FontDialog(self, data)
  341. if dlg.ShowModal() == wx.ID_OK:
  342. data = dlg.GetFontData()
  343. self.currFont = data.GetChosenFont()
  344. self.currClr = data.GetColour()
  345. self.textentry.SetFont(self.currFont)
  346. self.textentry.SetForegroundColour(self.currClr)
  347. self.Layout()
  348. dlg.Destroy()
  349. def GetValues(self):
  350. """Get text properties"""
  351. return {'text': self.currText,
  352. 'font': self.currFont,
  353. 'color': self.currClr,
  354. 'rotation': self.currRot,
  355. 'coords': self.currCoords,
  356. 'active': self.chkbox.IsChecked()}