decorations.py 14 KB

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