decorations.py 14 KB

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