frame.py 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805
  1. """!
  2. @package psmap.frame
  3. @brief GUI for ps.map
  4. Classes:
  5. - frame::PsMapFrame
  6. - frame::PsMapBufferedWindow
  7. (C) 2011 by Anna Kratochvilova, and the GRASS Development Team
  8. This program is free software under the GNU General Public License
  9. (>=v2). Read the file COPYING that comes with GRASS for details.
  10. @author Anna Kratochvilova <kratochanna gmail.com> (bachelor's project)
  11. @author Martin Landa <landa.martin gmail.com> (mentor)
  12. """
  13. import os
  14. import sys
  15. import textwrap
  16. import Queue
  17. from math import sin, cos, pi
  18. try:
  19. import Image as PILImage
  20. havePILImage = True
  21. except ImportError:
  22. havePILImage = False
  23. if __name__ == "__main__":
  24. sys.path.append(os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython'))
  25. from core import globalvar
  26. import wx
  27. try:
  28. import wx.lib.agw.flatnotebook as fnb
  29. except ImportError:
  30. import wx.lib.flatnotebook as fnb
  31. import grass.script as grass
  32. from gui_core.menu import Menu
  33. from gui_core.goutput import CmdThread, EVT_CMD_DONE
  34. from psmap.toolbars import PsMapToolbar
  35. from icon import Icons
  36. from core.gcmd import RunCommand, GError, GMessage
  37. from gui_core.forms import GUI
  38. from psmap.menudata import PsMapData
  39. from psmap.dialogs import *
  40. class PsMapFrame(wx.Frame):
  41. def __init__(self, parent = None, id = wx.ID_ANY,
  42. title = _("GRASS GIS Cartographic Composer"), **kwargs):
  43. """!Main window of ps.map GUI
  44. @param parent parent window
  45. @param id window id
  46. @param title window title
  47. @param kwargs wx.Frames' arguments
  48. """
  49. self.parent = parent
  50. wx.Frame.__init__(self, parent = parent, id = id, title = title, name = "PsMap", **kwargs)
  51. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  52. #menubar
  53. self.menubar = Menu(parent = self, data = PsMapData())
  54. self.SetMenuBar(self.menubar)
  55. #toolbar
  56. self.toolbar = PsMapToolbar(parent = self)
  57. self.SetToolBar(self.toolbar)
  58. self.actionOld = self.toolbar.action['id']
  59. self.iconsize = (16, 16)
  60. #satusbar
  61. self.statusbar = self.CreateStatusBar(number = 1)
  62. # mouse attributes -- position on the screen, begin and end of
  63. # dragging, and type of drawing
  64. self.mouse = {
  65. 'begin': [0, 0], # screen coordinates
  66. 'end' : [0, 0],
  67. 'use' : "pointer",
  68. }
  69. # available cursors
  70. self.cursors = {
  71. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  72. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  73. "hand" : wx.StockCursor(wx.CURSOR_HAND),
  74. "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
  75. }
  76. # pen and brush
  77. self.pen = {
  78. 'paper': wx.Pen(colour = "BLACK", width = 1),
  79. 'margins': wx.Pen(colour = "GREY", width = 1),
  80. 'map': wx.Pen(colour = wx.Color(86, 122, 17), width = 2),
  81. 'rasterLegend': wx.Pen(colour = wx.Color(219, 216, 4), width = 2),
  82. 'vectorLegend': wx.Pen(colour = wx.Color(219, 216, 4), width = 2),
  83. 'mapinfo': wx.Pen(colour = wx.Color(5, 184, 249), width = 2),
  84. 'scalebar': wx.Pen(colour = wx.Color(150, 150, 150), width = 2),
  85. 'image': wx.Pen(colour = wx.Color(255, 150, 50), width = 2),
  86. 'northArrow': wx.Pen(colour = wx.Color(200, 200, 200), width = 2),
  87. 'box': wx.Pen(colour = 'RED', width = 2, style = wx.SHORT_DASH),
  88. 'select': wx.Pen(colour = 'BLACK', width = 1, style = wx.SHORT_DASH),
  89. 'resize': wx.Pen(colour = 'BLACK', width = 1)
  90. }
  91. self.brush = {
  92. 'paper': wx.WHITE_BRUSH,
  93. 'margins': wx.TRANSPARENT_BRUSH,
  94. 'map': wx.Brush(wx.Color(151, 214, 90)),
  95. 'rasterLegend': wx.Brush(wx.Color(250, 247, 112)),
  96. 'vectorLegend': wx.Brush(wx.Color(250, 247, 112)),
  97. 'mapinfo': wx.Brush(wx.Color(127, 222, 252)),
  98. 'scalebar': wx.Brush(wx.Color(200, 200, 200)),
  99. 'image': wx.Brush(wx.Color(255, 200, 50)),
  100. 'northArrow': wx.Brush(wx.Color(255, 255, 255)),
  101. 'box': wx.TRANSPARENT_BRUSH,
  102. 'select':wx.TRANSPARENT_BRUSH,
  103. 'resize': wx.BLACK_BRUSH
  104. }
  105. # list of objects to draw
  106. self.objectId = []
  107. # instructions
  108. self.instruction = Instruction(parent = self, objectsToDraw = self.objectId)
  109. # open dialogs
  110. self.openDialogs = dict()
  111. self.pageId = wx.NewId()
  112. #current page of flatnotebook
  113. self.currentPage = 0
  114. #canvas for draft mode
  115. self.canvas = PsMapBufferedWindow(parent = self, mouse = self.mouse, pen = self.pen,
  116. brush = self.brush, cursors = self.cursors,
  117. instruction = self.instruction, openDialogs = self.openDialogs,
  118. pageId = self.pageId, objectId = self.objectId,
  119. preview = False)
  120. self.canvas.SetCursor(self.cursors["default"])
  121. self.getInitMap()
  122. # image path
  123. env = grass.gisenv()
  124. self.imgName = os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'], '.tmp', 'tmpImage.png')
  125. #canvas for preview
  126. self.previewCanvas = PsMapBufferedWindow(parent = self, mouse = self.mouse, cursors = self.cursors,
  127. pen = self.pen, brush = self.brush, preview = True)
  128. # set WIND_OVERRIDE
  129. grass.use_temp_region()
  130. # create queues
  131. self.requestQ = Queue.Queue()
  132. self.resultQ = Queue.Queue()
  133. # thread
  134. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  135. self._layout()
  136. self.SetMinSize(wx.Size(750, 600))
  137. self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
  138. self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
  139. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  140. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  141. if not havePILImage:
  142. wx.CallAfter(self._showErrMsg)
  143. def _showErrMsg(self):
  144. """!Show error message (missing preview)
  145. """
  146. GError(parent = self,
  147. message = _("Python Imaging Library is not available.\n"
  148. "'Preview' functionality won't work."),
  149. showTraceback = False)
  150. def _layout(self):
  151. """!Do layout
  152. """
  153. mainSizer = wx.BoxSizer(wx.VERTICAL)
  154. if globalvar.hasAgw:
  155. self.book = fnb.FlatNotebook(parent = self, id = wx.ID_ANY,
  156. agwStyle = fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
  157. fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
  158. else:
  159. self.book = fnb.FlatNotebook(parent = self, id = wx.ID_ANY,
  160. style = fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
  161. fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
  162. #self.book = fnb.FlatNotebook(self, wx.ID_ANY, style = fnb.FNB_BOTTOM)
  163. self.book.AddPage(self.canvas, "Draft mode")
  164. self.book.AddPage(self.previewCanvas, "Preview")
  165. self.book.SetSelection(0)
  166. mainSizer.Add(self.book,1, wx.EXPAND)
  167. self.SetSizer(mainSizer)
  168. mainSizer.Fit(self)
  169. def InstructionFile(self):
  170. """!Creates mapping instructions"""
  171. return str(self.instruction)
  172. def OnPSFile(self, event):
  173. """!Generate PostScript"""
  174. filename = self.getFile(wildcard = "PostScript (*.ps)|*.ps|Encapsulated PostScript (*.eps)|*.eps")
  175. if filename:
  176. self.PSFile(filename)
  177. def OnPsMapDialog(self, event):
  178. """!Launch ps.map dialog
  179. """
  180. GUI(parent = self).ParseCommand(cmd = ['ps.map'])
  181. def OnPDFFile(self, event):
  182. """!Generate PDF from PS with ps2pdf if available"""
  183. try:
  184. p = grass.Popen(["ps2pdf"], stderr = grass.PIPE)
  185. p.stderr.close()
  186. except OSError:
  187. GMessage(parent = self,
  188. message = _("Program ps2pdf is not available. Please install it first to create PDF."))
  189. return
  190. filename = self.getFile(wildcard = "PDF (*.pdf)|*.pdf")
  191. if filename:
  192. self.PSFile(filename, pdf = True)
  193. def OnPreview(self, event):
  194. """!Run ps.map and show result"""
  195. self.PSFile()
  196. def PSFile(self, filename = None, pdf = False):
  197. """!Create temporary instructions file and run ps.map with output = filename"""
  198. instrFile = grass.tempfile()
  199. instrFileFd = open(instrFile, mode = 'w')
  200. instrFileFd.write(self.InstructionFile())
  201. instrFileFd.flush()
  202. instrFileFd.close()
  203. temp = False
  204. regOld = grass.region()
  205. if pdf:
  206. pdfname = filename
  207. else:
  208. pdfname = None
  209. #preview or pdf
  210. if not filename or (filename and pdf):
  211. temp = True
  212. filename = grass.tempfile()
  213. if not pdf: # lower resolution for preview
  214. if self.instruction.FindInstructionByType('map'):
  215. mapId = self.instruction.FindInstructionByType('map').id
  216. SetResolution(dpi = 100, width = self.instruction[mapId]['rect'][2],
  217. height = self.instruction[mapId]['rect'][3])
  218. cmd = ['ps.map', '--overwrite']
  219. if os.path.splitext(filename)[1] == '.eps':
  220. cmd.append('-e')
  221. if self.instruction[self.pageId]['Orientation'] == 'Landscape':
  222. cmd.append('-r')
  223. cmd.append('input=%s' % instrFile)
  224. cmd.append('output=%s' % filename)
  225. if pdf:
  226. self.SetStatusText(_('Generating PDF...'), 0)
  227. elif not temp:
  228. self.SetStatusText(_('Generating PostScript...'), 0)
  229. else:
  230. self.SetStatusText(_('Generating preview...'), 0)
  231. self.cmdThread.RunCmd(cmd, userData = {'instrFile' : instrFile, 'filename' : filename,
  232. 'pdfname' : pdfname, 'temp' : temp, 'regionOld' : regOld})
  233. def OnCmdDone(self, event):
  234. """!ps.map process finished"""
  235. if event.returncode != 0:
  236. GMessage(parent = self,
  237. message = _("Ps.map exited with return code %s") % event.returncode)
  238. grass.try_remove(event.userData['instrFile'])
  239. if event.userData['temp']:
  240. grass.try_remove(event.userData['filename'])
  241. return
  242. if event.userData['pdfname']:
  243. try:
  244. proc = grass.Popen(['ps2pdf', '-dPDFSETTINGS=/prepress', '-r1200',
  245. event.userData['filename'], event.userData['pdfname']])
  246. ret = proc.wait()
  247. if ret > 0:
  248. GMessage(parent = self,
  249. message = _("ps2pdf exited with return code %s") % ret)
  250. except OSError, e:
  251. GError(parent = self,
  252. message = _("Program ps2pdf is not available. Please install it to create PDF.\n\n %s") % e)
  253. # show preview only when user doesn't want to create ps or pdf
  254. if havePILImage and event.userData['temp'] and not event.userData['pdfname']:
  255. RunCommand('g.region', cols = event.userData['regionOld']['cols'], rows = event.userData['regionOld']['rows'])
  256. ## wx.BusyInfo does not display the message
  257. ## busy = wx.BusyInfo(message = "Generating preview, wait please", parent = self)
  258. try:
  259. im = PILImage.open(event.userData['filename'])
  260. if self.instruction[self.pageId]['Orientation'] == 'Landscape':
  261. im = im.rotate(270)
  262. im.save(self.imgName, format = 'png')
  263. except IOError, e:
  264. GError(parent = self,
  265. message = _("Unable to generate preview. %s") % e)
  266. rect = self.previewCanvas.ImageRect()
  267. self.previewCanvas.image = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  268. self.previewCanvas.DrawImage(rect = rect)
  269. ## busy.Destroy()
  270. self.SetStatusText(_('Preview generated'), 0)
  271. self.book.SetSelection(1)
  272. self.currentPage = 1
  273. grass.try_remove(event.userData['instrFile'])
  274. if event.userData['temp']:
  275. grass.try_remove(event.userData['filename'])
  276. def getFile(self, wildcard):
  277. suffix = []
  278. for filter in wildcard.split('|')[1::2]:
  279. s = filter.strip('*').split('.')[1]
  280. if s:
  281. s = '.' + s
  282. suffix.append(s)
  283. raster = self.instruction.FindInstructionByType('raster')
  284. if raster:
  285. rasterId = raster.id
  286. else:
  287. rasterId = None
  288. if rasterId and self.instruction[rasterId]['raster']:
  289. mapName = self.instruction[rasterId]['raster'].split('@')[0] + suffix[0]
  290. else:
  291. mapName = ''
  292. filename = ''
  293. dlg = wx.FileDialog(self, message = _("Save file as"), defaultDir = "",
  294. defaultFile = mapName, wildcard = wildcard,
  295. style = wx.CHANGE_DIR | wx.SAVE | wx.OVERWRITE_PROMPT)
  296. if dlg.ShowModal() == wx.ID_OK:
  297. filename = dlg.GetPath()
  298. suffix = suffix[dlg.GetFilterIndex()]
  299. if not os.path.splitext(filename)[1]:
  300. filename = filename + suffix
  301. elif os.path.splitext(filename)[1] != suffix and suffix != '':
  302. filename = os.path.splitext(filename)[0] + suffix
  303. dlg.Destroy()
  304. return filename
  305. def OnInstructionFile(self, event):
  306. filename = self.getFile(wildcard = "*.psmap|*.psmap|Text file(*.txt)|*.txt|All files(*.*)|*.*")
  307. if filename:
  308. instrFile = open(filename, "w")
  309. instrFile.write(self.InstructionFile())
  310. instrFile.close()
  311. def OnLoadFile(self, event):
  312. """!Load file and read instructions"""
  313. #find file
  314. filename = ''
  315. dlg = wx.FileDialog(self, message = "Find instructions file", defaultDir = "",
  316. defaultFile = '', wildcard = "All files (*.*)|*.*",
  317. style = wx.CHANGE_DIR|wx.OPEN)
  318. if dlg.ShowModal() == wx.ID_OK:
  319. filename = dlg.GetPath()
  320. dlg.Destroy()
  321. if not filename:
  322. return
  323. # load instructions
  324. readObjectId = []
  325. readInstruction = Instruction(parent = self, objectsToDraw = readObjectId)
  326. ok = readInstruction.Read(filename)
  327. if not ok:
  328. GMessage(_("Failed to read file %s.") % filename)
  329. else:
  330. self.instruction = self.canvas.instruction = readInstruction
  331. self.objectId = self.canvas.objectId = readObjectId
  332. self.pageId = self.canvas.pageId = self.instruction.FindInstructionByType('page').id
  333. self.canvas.UpdateMapLabel()
  334. self.canvas.dragId = -1
  335. self.canvas.Clear()
  336. self.canvas.SetPage()
  337. #self.canvas.ZoomAll()
  338. self.DialogDataChanged(self.objectId)
  339. def OnPageSetup(self, event = None):
  340. """!Specify paper size, margins and orientation"""
  341. id = self.instruction.FindInstructionByType('page').id
  342. dlg = PageSetupDialog(self, id = id, settings = self.instruction)
  343. dlg.CenterOnScreen()
  344. val = dlg.ShowModal()
  345. if val == wx.ID_OK:
  346. self.canvas.SetPage()
  347. self.getInitMap()
  348. self.canvas.RecalculatePosition(ids = self.objectId)
  349. dlg.Destroy()
  350. def OnPointer(self, event):
  351. self.toolbar.OnTool(event)
  352. self.mouse["use"] = "pointer"
  353. self.canvas.SetCursor(self.cursors["default"])
  354. self.previewCanvas.SetCursor(self.cursors["default"])
  355. def OnPan(self, event):
  356. self.toolbar.OnTool(event)
  357. self.mouse["use"] = "pan"
  358. self.canvas.SetCursor(self.cursors["hand"])
  359. self.previewCanvas.SetCursor(self.cursors["hand"])
  360. def OnZoomIn(self, event):
  361. self.toolbar.OnTool(event)
  362. self.mouse["use"] = "zoomin"
  363. self.canvas.SetCursor(self.cursors["cross"])
  364. self.previewCanvas.SetCursor(self.cursors["cross"])
  365. def OnZoomOut(self, event):
  366. self.toolbar.OnTool(event)
  367. self.mouse["use"] = "zoomout"
  368. self.canvas.SetCursor(self.cursors["cross"])
  369. self.previewCanvas.SetCursor(self.cursors["cross"])
  370. def OnZoomAll(self, event):
  371. self.mouseOld = self.mouse['use']
  372. if self.currentPage == 0:
  373. self.cursorOld = self.canvas.GetCursor()
  374. else:
  375. self.cursorOld = self.previewCanvas.GetCursor()
  376. self.previewCanvas.GetCursor()
  377. self.mouse["use"] = "zoomin"
  378. if self.currentPage == 0:
  379. self.canvas.ZoomAll()
  380. else:
  381. self.previewCanvas.ZoomAll()
  382. self.mouse["use"] = self.mouseOld
  383. if self.currentPage == 0:
  384. self.canvas.SetCursor(self.cursorOld)
  385. else:
  386. self.previewCanvas.SetCursor(self.cursorOld)
  387. def OnAddMap(self, event, notebook = False):
  388. """!Add or edit map frame"""
  389. if event is not None:
  390. if event.GetId() != self.toolbar.action['id']:
  391. self.actionOld = self.toolbar.action['id']
  392. self.mouseOld = self.mouse['use']
  393. self.cursorOld = self.canvas.GetCursor()
  394. self.toolbar.OnTool(event)
  395. if self.instruction.FindInstructionByType('map'):
  396. mapId = self.instruction.FindInstructionByType('map').id
  397. else: mapId = None
  398. id = [mapId, None, None]
  399. if notebook:
  400. if self.instruction.FindInstructionByType('vector'):
  401. vectorId = self.instruction.FindInstructionByType('vector').id
  402. else: vectorId = None
  403. if self.instruction.FindInstructionByType('raster'):
  404. rasterId = self.instruction.FindInstructionByType('raster').id
  405. else: rasterId = None
  406. id[1] = rasterId
  407. id[2] = vectorId
  408. if mapId: # map exists
  409. self.toolbar.ToggleTool(self.actionOld, True)
  410. self.toolbar.ToggleTool(self.toolbar.action['id'], False)
  411. self.toolbar.action['id'] = self.actionOld
  412. try:
  413. self.canvas.SetCursor(self.cursorOld)
  414. except AttributeError:
  415. pass
  416. ## dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  417. ## notebook = notebook)
  418. ## dlg.ShowModal()
  419. if notebook:
  420. #check map, raster, vector and save, destroy them
  421. if 'map' in self.openDialogs:
  422. self.openDialogs['map'].OnOK(event = None)
  423. if 'raster' in self.openDialogs:
  424. self.openDialogs['raster'].OnOK(event = None)
  425. if 'vector' in self.openDialogs:
  426. self.openDialogs['vector'].OnOK(event = None)
  427. if 'mapNotebook' not in self.openDialogs:
  428. dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  429. notebook = notebook)
  430. self.openDialogs['mapNotebook'] = dlg
  431. self.openDialogs['mapNotebook'].Show()
  432. else:
  433. if 'mapNotebook' in self.openDialogs:
  434. self.openDialogs['mapNotebook'].notebook.ChangeSelection(0)
  435. else:
  436. if 'map' not in self.openDialogs:
  437. dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  438. notebook = notebook)
  439. self.openDialogs['map'] = dlg
  440. self.openDialogs['map'].Show()
  441. else: # sofar no map
  442. self.mouse["use"] = "addMap"
  443. self.canvas.SetCursor(self.cursors["cross"])
  444. if self.currentPage == 1:
  445. self.book.SetSelection(0)
  446. self.currentPage = 0
  447. def OnAddRaster(self, event):
  448. """!Add raster map"""
  449. if self.instruction.FindInstructionByType('raster'):
  450. id = self.instruction.FindInstructionByType('raster').id
  451. else: id = None
  452. if self.instruction.FindInstructionByType('map'):
  453. mapId = self.instruction.FindInstructionByType('map').id
  454. else: mapId = None
  455. if not id:
  456. if not mapId:
  457. GMessage(message = _("Please, create map frame first."))
  458. return
  459. ## dlg = RasterDialog(self, id = id, settings = self.instruction)
  460. ## dlg.ShowModal()
  461. if 'mapNotebook' in self.openDialogs:
  462. self.openDialogs['mapNotebook'].notebook.ChangeSelection(1)
  463. else:
  464. if 'raster' not in self.openDialogs:
  465. dlg = RasterDialog(self, id = id, settings = self.instruction)
  466. self.openDialogs['raster'] = dlg
  467. self.openDialogs['raster'].Show()
  468. def OnAddVect(self, event):
  469. """!Add vector map"""
  470. if self.instruction.FindInstructionByType('vector'):
  471. id = self.instruction.FindInstructionByType('vector').id
  472. else: id = None
  473. if self.instruction.FindInstructionByType('map'):
  474. mapId = self.instruction.FindInstructionByType('map').id
  475. else: mapId = None
  476. if not id:
  477. if not mapId:
  478. GMessage(message = _("Please, create map frame first."))
  479. return
  480. ## dlg = MainVectorDialog(self, id = id, settings = self.instruction)
  481. ## dlg.ShowModal()
  482. if 'mapNotebook' in self.openDialogs:
  483. self.openDialogs['mapNotebook'].notebook.ChangeSelection(2)
  484. else:
  485. if 'vector' not in self.openDialogs:
  486. dlg = MainVectorDialog(self, id = id, settings = self.instruction)
  487. self.openDialogs['vector'] = dlg
  488. self.openDialogs['vector'].Show()
  489. def OnDecoration(self, event):
  490. """!Decorations overlay menu
  491. """
  492. decmenu = wx.Menu()
  493. # legend
  494. AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, Icons['psMap']["addLegend"].GetLabel())
  495. AddLegend.SetBitmap(Icons['psMap']["addLegend"].GetBitmap(self.iconsize))
  496. decmenu.AppendItem(AddLegend)
  497. self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
  498. # mapinfo
  499. AddMapinfo = wx.MenuItem(decmenu, wx.ID_ANY, Icons['psMap']["addMapinfo"].GetLabel())
  500. AddMapinfo.SetBitmap(Icons['psMap']["addMapinfo"].GetBitmap(self.iconsize))
  501. decmenu.AppendItem(AddMapinfo)
  502. self.Bind(wx.EVT_MENU, self.OnAddMapinfo, AddMapinfo)
  503. # scalebar
  504. AddScalebar = wx.MenuItem(decmenu, wx.ID_ANY, Icons['psMap']["addScalebar"].GetLabel())
  505. AddScalebar.SetBitmap(Icons['psMap']["addScalebar"].GetBitmap(self.iconsize))
  506. decmenu.AppendItem(AddScalebar)
  507. self.Bind(wx.EVT_MENU, self.OnAddScalebar, AddScalebar)
  508. # text
  509. AddText = wx.MenuItem(decmenu, wx.ID_ANY, Icons['psMap']["addText"].GetLabel())
  510. AddText.SetBitmap(Icons['psMap']["addText"].GetBitmap(self.iconsize))
  511. decmenu.AppendItem(AddText)
  512. self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
  513. # eps image
  514. AddImage = wx.MenuItem(decmenu, wx.ID_ANY, Icons['psMap']["addImage"].GetLabel())
  515. AddImage.SetBitmap(Icons['psMap']["addImage"].GetBitmap(self.iconsize))
  516. decmenu.AppendItem(AddImage)
  517. self.Bind(wx.EVT_MENU, self.OnAddImage, AddImage)
  518. # north arrow image
  519. AddNorthArrow = wx.MenuItem(decmenu, wx.ID_ANY, _("North arrow"))
  520. AddNorthArrow.SetBitmap(wx.ArtProvider.GetBitmap(id = wx.ART_MISSING_IMAGE,
  521. client = wx.ART_MENU, size = self.iconsize))
  522. decmenu.AppendItem(AddNorthArrow)
  523. self.Bind(wx.EVT_MENU, self.OnAddNorthArrow, AddNorthArrow)
  524. # Popup the menu. If an item is selected then its handler
  525. # will be called before PopupMenu returns.
  526. self.PopupMenu(decmenu)
  527. decmenu.Destroy()
  528. def OnAddScalebar(self, event):
  529. """!Add scalebar"""
  530. if projInfo()['proj'] == 'll':
  531. GMessage(message = _("Scalebar is not appropriate for this projection"))
  532. return
  533. if self.instruction.FindInstructionByType('scalebar'):
  534. id = self.instruction.FindInstructionByType('scalebar').id
  535. else: id = None
  536. if 'scalebar' not in self.openDialogs:
  537. dlg = ScalebarDialog(self, id = id, settings = self.instruction)
  538. self.openDialogs['scalebar'] = dlg
  539. self.openDialogs['scalebar'].Show()
  540. def OnAddLegend(self, event, page = 0):
  541. """!Add raster or vector legend"""
  542. if self.instruction.FindInstructionByType('rasterLegend'):
  543. idR = self.instruction.FindInstructionByType('rasterLegend').id
  544. else: idR = None
  545. if self.instruction.FindInstructionByType('vectorLegend'):
  546. idV = self.instruction.FindInstructionByType('vectorLegend').id
  547. else: idV = None
  548. if 'rasterLegend' not in self.openDialogs:
  549. dlg = LegendDialog(self, id = [idR, idV], settings = self.instruction, page = page)
  550. self.openDialogs['rasterLegend'] = dlg
  551. self.openDialogs['vectorLegend'] = dlg
  552. self.openDialogs['rasterLegend'].notebook.ChangeSelection(page)
  553. self.openDialogs['rasterLegend'].Show()
  554. def OnAddMapinfo(self, event):
  555. if self.instruction.FindInstructionByType('mapinfo'):
  556. id = self.instruction.FindInstructionByType('mapinfo').id
  557. else: id = None
  558. if 'mapinfo' not in self.openDialogs:
  559. dlg = MapinfoDialog(self, id = id, settings = self.instruction)
  560. self.openDialogs['mapinfo'] = dlg
  561. self.openDialogs['mapinfo'].Show()
  562. def OnAddImage(self, event, id = None):
  563. """!Show dialog for image adding and editing"""
  564. position = None
  565. if 'image' in self.openDialogs:
  566. position = self.openDialogs['image'].GetPosition()
  567. self.openDialogs['image'].OnApply(event = None)
  568. self.openDialogs['image'].Destroy()
  569. dlg = ImageDialog(self, id = id, settings = self.instruction)
  570. self.openDialogs['image'] = dlg
  571. if position:
  572. dlg.SetPosition(position)
  573. dlg.Show()
  574. def OnAddNorthArrow(self, event, id = None):
  575. """!Show dialog for north arrow adding and editing"""
  576. if self.instruction.FindInstructionByType('northArrow'):
  577. id = self.instruction.FindInstructionByType('northArrow').id
  578. else: id = None
  579. if 'northArrow' not in self.openDialogs:
  580. dlg = NorthArrowDialog(self, id = id, settings = self.instruction)
  581. self.openDialogs['northArrow'] = dlg
  582. self.openDialogs['northArrow'].Show()
  583. def OnAddText(self, event, id = None):
  584. """!Show dialog for text adding and editing"""
  585. position = None
  586. if 'text' in self.openDialogs:
  587. position = self.openDialogs['text'].GetPosition()
  588. self.openDialogs['text'].OnApply(event = None)
  589. self.openDialogs['text'].Destroy()
  590. dlg = TextDialog(self, id = id, settings = self.instruction)
  591. self.openDialogs['text'] = dlg
  592. if position:
  593. dlg.SetPosition(position)
  594. dlg.Show()
  595. def getModifiedTextBounds(self, x, y, textExtent, rotation):
  596. """!computes bounding box of rotated text, not very precisely"""
  597. w, h = textExtent
  598. rotation = float(rotation)/180*pi
  599. H = float(w) * sin(rotation)
  600. W = float(w) * cos(rotation)
  601. X, Y = x, y
  602. if pi/2 < rotation <= 3*pi/2:
  603. X = x + W
  604. if 0 < rotation < pi:
  605. Y = y - H
  606. if rotation == 0:
  607. return wx.Rect(x,y, *textExtent)
  608. else:
  609. return wx.Rect(X, Y, abs(W), abs(H)).Inflate(h,h)
  610. def makePSFont(self, textDict):
  611. """!creates a wx.Font object from selected postscript font. To be
  612. used for estimating bounding rectangle of text"""
  613. fontsize = textDict['fontsize'] * self.canvas.currScale
  614. fontface = textDict['font'].split('-')[0]
  615. try:
  616. fontstyle = textDict['font'].split('-')[1]
  617. except IndexError:
  618. fontstyle = ''
  619. if fontface == "Times":
  620. family = wx.FONTFAMILY_ROMAN
  621. face = "times"
  622. elif fontface == "Helvetica":
  623. family = wx.FONTFAMILY_SWISS
  624. face = 'helvetica'
  625. elif fontface == "Courier":
  626. family = wx.FONTFAMILY_TELETYPE
  627. face = 'courier'
  628. else:
  629. family = wx.FONTFAMILY_DEFAULT
  630. face = ''
  631. style = wx.FONTSTYLE_NORMAL
  632. weight = wx.FONTWEIGHT_NORMAL
  633. if 'Oblique' in fontstyle:
  634. style = wx.FONTSTYLE_SLANT
  635. if 'Italic' in fontstyle:
  636. style = wx.FONTSTYLE_ITALIC
  637. if 'Bold' in fontstyle:
  638. weight = wx.FONTWEIGHT_BOLD
  639. try:
  640. fn = wx.Font(pointSize = fontsize, family = family, style = style,
  641. weight = weight, face = face)
  642. except:
  643. fn = wx.Font(pointSize = fontsize, family = wx.FONTFAMILY_DEFAULT,
  644. style = wx.FONTSTYLE_NORMAL, weight = wx.FONTWEIGHT_NORMAL)
  645. return fn
  646. def getTextExtent(self, textDict):
  647. """!Estimates bounding rectangle of text"""
  648. #fontsize = str(fontsize if fontsize >= 4 else 4)
  649. dc = wx.PaintDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  650. fn = self.makePSFont(textDict)
  651. try:
  652. dc.SetFont(fn)
  653. w,h,lh = dc.GetMultiLineTextExtent(textDict['text'])
  654. return (w,h)
  655. except:
  656. return (0,0)
  657. def getInitMap(self):
  658. """!Create default map frame when no map is selected, needed for coordinates in map units"""
  659. instrFile = grass.tempfile()
  660. instrFileFd = open(instrFile, mode = 'w')
  661. instrFileFd.write(self.InstructionFile())
  662. instrFileFd.flush()
  663. instrFileFd.close()
  664. page = self.instruction.FindInstructionByType('page')
  665. mapInitRect = GetMapBounds(instrFile, portrait = (page['Orientation'] == 'Portrait'))
  666. grass.try_remove(instrFile)
  667. region = grass.region()
  668. units = UnitConversion(self)
  669. realWidth = units.convert(value = abs(region['w'] - region['e']), fromUnit = 'meter', toUnit = 'inch')
  670. scale = mapInitRect.Get()[2]/realWidth
  671. initMap = self.instruction.FindInstructionByType('initMap')
  672. if initMap:
  673. id = initMap.id
  674. else:
  675. id = None
  676. if not id:
  677. id = wx.NewId()
  678. initMap = InitMap(id)
  679. self.instruction.AddInstruction(initMap)
  680. self.instruction[id].SetInstruction(dict(rect = mapInitRect, scale = scale))
  681. def OnDelete(self, event):
  682. if self.canvas.dragId != -1 and self.currentPage == 0:
  683. if self.instruction[self.canvas.dragId].type == 'map':
  684. self.deleteObject(self.canvas.dragId)
  685. self.getInitMap()
  686. self.canvas.RecalculateEN()
  687. else:
  688. self.deleteObject(self.canvas.dragId)
  689. def deleteObject(self, id):
  690. """!Deletes object, his id and redraws"""
  691. #delete from canvas
  692. self.canvas.pdcObj.RemoveId(id)
  693. if id == self.canvas.dragId:
  694. self.canvas.pdcTmp.RemoveAll()
  695. self.canvas.dragId = -1
  696. self.canvas.Refresh()
  697. # delete from instructions
  698. del self.instruction[id]
  699. def DialogDataChanged(self, id):
  700. ids = id
  701. if type(id) == int:
  702. ids = [id]
  703. for id in ids:
  704. itype = self.instruction[id].type
  705. if itype in ('scalebar', 'mapinfo', 'image'):
  706. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  707. self.canvas.UpdateLabel(itype = itype, id = id)
  708. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  709. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  710. self.canvas.RedrawSelectBox(id)
  711. if itype == 'northArrow':
  712. self.canvas.UpdateLabel(itype = itype, id = id)
  713. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  714. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  715. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'bitmap', bb = drawRectangle)
  716. self.canvas.RedrawSelectBox(id)
  717. if itype == 'text':
  718. if self.instruction[id]['rotate']:
  719. rot = float(self.instruction[id]['rotate'])
  720. else:
  721. rot = 0
  722. extent = self.getTextExtent(textDict = self.instruction[id].GetInstruction())
  723. rect = wx.Rect2D(self.instruction[id]['where'][0], self.instruction[id]['where'][1], 0, 0)
  724. self.instruction[id]['coords'] = list(self.canvas.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)[:2])
  725. #computes text coordinates according to reference point, not precisely
  726. if self.instruction[id]['ref'].split()[0] == 'lower':
  727. self.instruction[id]['coords'][1] -= extent[1]
  728. elif self.instruction[id]['ref'].split()[0] == 'center':
  729. self.instruction[id]['coords'][1] -= extent[1]/2
  730. if self.instruction[id]['ref'].split()[1] == 'right':
  731. self.instruction[id]['coords'][0] -= extent[0] * cos(rot/180*pi)
  732. self.instruction[id]['coords'][1] += extent[0] * sin(rot/180*pi)
  733. elif self.instruction[id]['ref'].split()[1] == 'center':
  734. self.instruction[id]['coords'][0] -= extent[0]/2 * cos(rot/180*pi)
  735. self.instruction[id]['coords'][1] += extent[0]/2 * sin(rot/180*pi)
  736. self.instruction[id]['coords'][0] += self.instruction[id]['xoffset']
  737. self.instruction[id]['coords'][1] -= self.instruction[id]['yoffset']
  738. coords = self.instruction[id]['coords']
  739. self.instruction[id]['rect'] = bounds = self.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  740. self.canvas.DrawRotText(pdc = self.canvas.pdcObj, drawId = id,
  741. textDict = self.instruction[id].GetInstruction(),
  742. coords = coords, bounds = bounds)
  743. self.canvas.RedrawSelectBox(id)
  744. if itype in ('map', 'vector', 'raster'):
  745. if itype == 'raster':#set resolution
  746. info = grass.raster_info(self.instruction[id]['raster'])
  747. RunCommand('g.region', nsres = info['nsres'], ewres = info['ewres'])
  748. # change current raster in raster legend
  749. if 'rasterLegend' in self.openDialogs:
  750. self.openDialogs['rasterLegend'].updateDialog()
  751. id = self.instruction.FindInstructionByType('map').id
  752. #check resolution
  753. if itype == 'raster':
  754. SetResolution(dpi = self.instruction[id]['resolution'],
  755. width = self.instruction[id]['rect'].width,
  756. height = self.instruction[id]['rect'].height)
  757. rectCanvas = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'],
  758. canvasToPaper = False)
  759. self.canvas.RecalculateEN()
  760. self.canvas.UpdateMapLabel()
  761. self.canvas.Draw(pen = self.pen['map'], brush = self.brush['map'],
  762. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = rectCanvas)
  763. # redraw select box
  764. self.canvas.RedrawSelectBox(id)
  765. self.canvas.pdcTmp.RemoveId(self.canvas.idZoomBoxTmp)
  766. # redraw to get map to the bottom layer
  767. #self.canvas.Zoom(zoomFactor = 1, view = (0, 0))
  768. if itype == 'rasterLegend':
  769. if self.instruction[id]['rLegend']:
  770. self.canvas.UpdateLabel(itype = itype, id = id)
  771. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  772. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  773. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  774. self.canvas.RedrawSelectBox(id)
  775. else:
  776. self.deleteObject(id)
  777. if itype == 'vectorLegend':
  778. if not self.instruction.FindInstructionByType('vector'):
  779. self.deleteObject(id)
  780. elif self.instruction[id]['vLegend']:
  781. self.canvas.UpdateLabel(itype = itype, id = id)
  782. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  783. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  784. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  785. self.canvas.RedrawSelectBox(id)
  786. else:
  787. self.deleteObject(id)
  788. def OnPageChanged(self, event):
  789. """!Flatnotebook page has changed"""
  790. self.currentPage = self.book.GetPageIndex(self.book.GetCurrentPage())
  791. def OnPageChanging(self, event):
  792. """!Flatnotebook page is changing"""
  793. if self.currentPage == 0 and self.mouse['use'] == 'addMap':
  794. event.Veto()
  795. def OnHelp(self, event):
  796. """!Show help"""
  797. if self.parent and self.parent.GetName() == 'LayerManager':
  798. log = self.parent.GetLogWindow()
  799. log.RunCmd(['g.manual',
  800. 'entry=wxGUI.PsMap'])
  801. else:
  802. RunCommand('g.manual',
  803. quiet = True,
  804. entry = 'wxGUI.PsMap')
  805. def OnAbout(self, event):
  806. """!Display About window"""
  807. info = wx.AboutDialogInfo()
  808. info.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  809. info.SetName(_('wxGUI Cartographic Composer'))
  810. info.SetWebSite('http://grass.osgeo.org')
  811. info.SetDescription(_('(C) 2011 by the GRASS Development Team\n\n') +
  812. '\n'.join(textwrap.wrap(_('This program is free software under the GNU General Public License'
  813. '(>=v2). Read the file COPYING that comes with GRASS for details.'), 75)))
  814. wx.AboutBox(info)
  815. def OnCloseWindow(self, event):
  816. """!Close window"""
  817. try:
  818. os.remove(self.imgName)
  819. except OSError:
  820. pass
  821. grass.set_raise_on_error(False)
  822. self.Destroy()
  823. class PsMapBufferedWindow(wx.Window):
  824. """!A buffered window class.
  825. @param parent parent window
  826. @param kwargs other wx.Window parameters
  827. """
  828. def __init__(self, parent, id = wx.ID_ANY,
  829. style = wx.NO_FULL_REPAINT_ON_RESIZE,
  830. **kwargs):
  831. wx.Window.__init__(self, parent, id = id, style = style)
  832. self.parent = parent
  833. self.FitInside()
  834. # store an off screen empty bitmap for saving to file
  835. self._buffer = None
  836. # indicates whether or not a resize event has taken place
  837. self.resize = False
  838. self.mouse = kwargs['mouse']
  839. self.cursors = kwargs['cursors']
  840. self.preview = kwargs['preview']
  841. self.pen = kwargs['pen']
  842. self.brush = kwargs['brush']
  843. if kwargs.has_key('instruction'):
  844. self.instruction = kwargs['instruction']
  845. if kwargs.has_key('openDialogs'):
  846. self.openDialogs = kwargs['openDialogs']
  847. if kwargs.has_key('pageId'):
  848. self.pageId = kwargs['pageId']
  849. if kwargs.has_key('objectId'):
  850. self.objectId = kwargs['objectId']
  851. #labels
  852. self.itemLabelsDict = { 'map': 'MAP FRAME',
  853. 'rasterLegend': 'RASTER LEGEND',
  854. 'vectorLegend': 'VECTOR LEGEND',
  855. 'mapinfo': 'MAP INFO',
  856. 'scalebar': 'SCALE BAR',
  857. 'image': 'IMAGE',
  858. 'northArrow': 'NORTH ARROW'}
  859. self.itemLabels = {}
  860. # define PseudoDC
  861. self.pdc = wx.PseudoDC()
  862. self.pdcObj = wx.PseudoDC()
  863. self.pdcPaper = wx.PseudoDC()
  864. self.pdcTmp = wx.PseudoDC()
  865. self.pdcImage = wx.PseudoDC()
  866. dc = wx.PaintDC(self)
  867. self.font = dc.GetFont()
  868. self.SetClientSize((700,510))#?
  869. self._buffer = wx.EmptyBitmap(*self.GetClientSize())
  870. self.idBoxTmp = wx.NewId()
  871. self.idZoomBoxTmp = wx.NewId()
  872. self.idResizeBoxTmp = wx.NewId()
  873. self.dragId = -1
  874. if self.preview:
  875. self.image = None
  876. self.imageId = 2000
  877. self.imgName = self.parent.imgName
  878. self.currScale = None
  879. self.Clear()
  880. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
  881. self.Bind(wx.EVT_PAINT, self.OnPaint)
  882. self.Bind(wx.EVT_SIZE, self.OnSize)
  883. self.Bind(wx.EVT_IDLE, self.OnIdle)
  884. self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
  885. def Clear(self):
  886. """!Clear canvas and set paper
  887. """
  888. bg = wx.LIGHT_GREY_BRUSH
  889. self.pdcPaper.BeginDrawing()
  890. self.pdcPaper.SetBackground(bg)
  891. self.pdcPaper.Clear()
  892. self.pdcPaper.EndDrawing()
  893. self.pdcObj.RemoveAll()
  894. self.pdcTmp.RemoveAll()
  895. if not self.preview:
  896. self.SetPage()
  897. def CanvasPaperCoordinates(self, rect, canvasToPaper = True):
  898. """!Converts canvas (pixel) -> paper (inch) coordinates and size and vice versa"""
  899. units = UnitConversion(self)
  900. fromU = 'pixel'
  901. toU = 'inch'
  902. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  903. pRectx, pRecty = pRect.x, pRect.y
  904. scale = 1/self.currScale
  905. if not canvasToPaper: # paper -> canvas
  906. fromU = 'inch'
  907. toU = 'pixel'
  908. scale = self.currScale
  909. pRectx = units.convert(value = - pRect.x, fromUnit = 'pixel', toUnit = 'inch' ) /scale #inch, real, negative
  910. pRecty = units.convert(value = - pRect.y, fromUnit = 'pixel', toUnit = 'inch' ) /scale
  911. Width = units.convert(value = rect.width, fromUnit = fromU, toUnit = toU) * scale
  912. Height = units.convert(value = rect.height, fromUnit = fromU, toUnit = toU) * scale
  913. X = units.convert(value = (rect.x - pRectx), fromUnit = fromU, toUnit = toU) * scale
  914. Y = units.convert(value = (rect.y - pRecty), fromUnit = fromU, toUnit = toU) * scale
  915. return wx.Rect2D(X, Y, Width, Height)
  916. def SetPage(self):
  917. """!Sets and changes page, redraws paper"""
  918. page = self.instruction[self.pageId]
  919. if not page:
  920. page = PageSetup(id = self.pageId)
  921. self.instruction.AddInstruction(page)
  922. ppi = wx.PaintDC(self).GetPPI()
  923. cW, cH = self.GetClientSize()
  924. pW, pH = page['Width']*ppi[0], page['Height']*ppi[1]
  925. if self.currScale is None:
  926. self.currScale = min(cW/pW, cH/pH)
  927. pW = pW * self.currScale
  928. pH = pH * self.currScale
  929. x = cW/2 - pW/2
  930. y = cH/2 - pH/2
  931. self.DrawPaper(wx.Rect(x, y, pW, pH))
  932. def modifyRectangle(self, r):
  933. """! Recalculates rectangle not to have negative size"""
  934. if r.GetWidth() < 0:
  935. r.SetX(r.GetX() + r.GetWidth())
  936. if r.GetHeight() < 0:
  937. r.SetY(r.GetY() + r.GetHeight())
  938. r.SetWidth(abs(r.GetWidth()))
  939. r.SetHeight(abs(r.GetHeight()))
  940. return r
  941. def RecalculateEN(self):
  942. """!Recalculate east and north for texts (eps, points) after their or map's movement"""
  943. try:
  944. mapId = self.instruction.FindInstructionByType('map').id
  945. except AttributeError:
  946. mapId = self.instruction.FindInstructionByType('initMap').id
  947. for itemType in ('text', 'image', 'northArrow'):
  948. items = self.instruction.FindInstructionByType(itemType, list = True)
  949. for item in items:
  950. e, n = PaperMapCoordinates(map = self.instruction[mapId], x = self.instruction[item.id]['where'][0],
  951. y = self.instruction[item.id]['where'][1], paperToMap = True)
  952. self.instruction[item.id]['east'], self.instruction[item.id]['north'] = e, n
  953. def OnPaint(self, event):
  954. """!Draw pseudo DC to buffer
  955. """
  956. if not self._buffer:
  957. return
  958. dc = wx.BufferedPaintDC(self, self._buffer)
  959. # use PrepareDC to set position correctly
  960. self.PrepareDC(dc)
  961. dc.SetBackground(wx.LIGHT_GREY_BRUSH)
  962. dc.Clear()
  963. # draw paper
  964. if not self.preview:
  965. self.pdcPaper.DrawToDC(dc)
  966. # draw to the DC using the calculated clipping rect
  967. rgn = self.GetUpdateRegion()
  968. if not self.preview:
  969. self.pdcObj.DrawToDCClipped(dc, rgn.GetBox())
  970. else:
  971. self.pdcImage.DrawToDCClipped(dc, rgn.GetBox())
  972. self.pdcTmp.DrawToDCClipped(dc, rgn.GetBox())
  973. def OnMouse(self, event):
  974. if event.GetWheelRotation():
  975. zoom = event.GetWheelRotation()
  976. use = self.mouse['use']
  977. self.mouse['begin'] = event.GetPosition()
  978. if zoom > 0:
  979. self.mouse['use'] = 'zoomin'
  980. else:
  981. self.mouse['use'] = 'zoomout'
  982. zoomFactor, view = self.ComputeZoom(wx.Rect(0,0,0,0))
  983. self.Zoom(zoomFactor, view)
  984. self.mouse['use'] = use
  985. if event.Moving():
  986. if self.mouse['use'] in ('pointer', 'resize'):
  987. pos = event.GetPosition()
  988. foundResize = self.pdcTmp.FindObjects(pos[0], pos[1])
  989. if foundResize and foundResize[0] == self.idResizeBoxTmp:
  990. self.SetCursor(self.cursors["sizenwse"])
  991. self.parent.SetStatusText(_('Click and drag to resize object'), 0)
  992. else:
  993. self.parent.SetStatusText('', 0)
  994. self.SetCursor(self.cursors["default"])
  995. elif event.LeftDown():
  996. self.mouse['begin'] = event.GetPosition()
  997. self.begin = self.mouse['begin']
  998. if self.mouse['use'] in ('pan', 'zoomin', 'zoomout', 'addMap'):
  999. pass
  1000. #select
  1001. if self.mouse['use'] == 'pointer':
  1002. found = self.pdcObj.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  1003. foundResize = self.pdcTmp.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  1004. if foundResize and foundResize[0] == self.idResizeBoxTmp:
  1005. self.mouse['use'] = 'resize'
  1006. # when resizing, proportions match region
  1007. if self.instruction[self.dragId].type == 'map':
  1008. self.constraint = False
  1009. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1010. if self.instruction[self.dragId]['scaleType'] in (0, 1, 2):
  1011. self.constraint = True
  1012. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1013. elif found:
  1014. self.dragId = found[0]
  1015. self.RedrawSelectBox(self.dragId)
  1016. if self.instruction[self.dragId].type != 'map':
  1017. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1018. self.Refresh()
  1019. else:
  1020. self.dragId = -1
  1021. self.pdcTmp.RemoveId(self.idBoxTmp)
  1022. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1023. self.Refresh()
  1024. elif event.Dragging() and event.LeftIsDown():
  1025. #draw box when zooming, creating map
  1026. if self.mouse['use'] in ('zoomin', 'zoomout', 'addMap'):
  1027. self.mouse['end'] = event.GetPosition()
  1028. r = wx.Rect(self.mouse['begin'][0], self.mouse['begin'][1],
  1029. self.mouse['end'][0]-self.mouse['begin'][0], self.mouse['end'][1]-self.mouse['begin'][1])
  1030. r = self.modifyRectangle(r)
  1031. self.Draw(pen = self.pen['box'], brush = self.brush['box'], pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
  1032. pdctype = 'rect', bb = r)
  1033. # panning
  1034. if self.mouse["use"] == 'pan':
  1035. self.mouse['end'] = event.GetPosition()
  1036. view = self.mouse['begin'][0] - self.mouse['end'][0], self.mouse['begin'][1] - self.mouse['end'][1]
  1037. zoomFactor = 1
  1038. self.Zoom(zoomFactor, view)
  1039. self.mouse['begin'] = event.GetPosition()
  1040. #move object
  1041. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1042. self.mouse['end'] = event.GetPosition()
  1043. dx, dy = self.mouse['end'][0] - self.begin[0], self.mouse['end'][1] - self.begin[1]
  1044. self.pdcObj.TranslateId(self.dragId, dx, dy)
  1045. self.pdcTmp.TranslateId(self.idBoxTmp, dx, dy)
  1046. self.pdcTmp.TranslateId(self.idResizeBoxTmp, dx, dy)
  1047. if self.instruction[self.dragId].type == 'text':
  1048. self.instruction[self.dragId]['coords'] = self.instruction[self.dragId]['coords'][0] + dx,\
  1049. self.instruction[self.dragId]['coords'][1] + dy
  1050. self.begin = event.GetPosition()
  1051. self.Refresh()
  1052. # resize object
  1053. if self.mouse['use'] == 'resize':
  1054. type = self.instruction[self.dragId].type
  1055. pos = event.GetPosition()
  1056. x, y = self.mapBounds.GetX(), self.mapBounds.GetY()
  1057. width, height = self.mapBounds.GetWidth(), self.mapBounds.GetHeight()
  1058. diffX = pos[0] - self.mouse['begin'][0]
  1059. diffY = pos[1] - self.mouse['begin'][1]
  1060. # match given region
  1061. if self.constraint:
  1062. if width > height:
  1063. newWidth = width + diffX
  1064. newHeight = height + diffX * (float(height) / width)
  1065. else:
  1066. newWidth = width + diffY * (float(width) / height)
  1067. newHeight = height + diffY
  1068. else:
  1069. newWidth = width + diffX
  1070. newHeight = height + diffY
  1071. if newWidth < 10 or newHeight < 10:
  1072. return
  1073. bounds = wx.Rect(x, y, newWidth, newHeight)
  1074. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj, drawid = self.dragId,
  1075. pdctype = 'rectText', bb = bounds)
  1076. self.RedrawSelectBox(self.dragId)
  1077. elif event.LeftUp():
  1078. # zoom in, zoom out
  1079. if self.mouse['use'] in ('zoomin','zoomout'):
  1080. zoomR = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1081. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1082. self.Refresh()
  1083. zoomFactor, view = self.ComputeZoom(zoomR)
  1084. self.Zoom(zoomFactor, view)
  1085. # draw map frame
  1086. if self.mouse['use'] == 'addMap':
  1087. rectTmp = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1088. # too small rectangle, it's usually some mistake
  1089. if rectTmp.GetWidth() < 20 or rectTmp.GetHeight() < 20:
  1090. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1091. self.Refresh()
  1092. return
  1093. rectPaper = self.CanvasPaperCoordinates(rect = rectTmp, canvasToPaper = True)
  1094. dlg = MapDialog(parent = self.parent, id = [None, None, None], settings = self.instruction,
  1095. rect = rectPaper)
  1096. self.openDialogs['map'] = dlg
  1097. self.openDialogs['map'].Show()
  1098. self.mouse['use'] = self.parent.mouseOld
  1099. self.SetCursor(self.parent.cursorOld)
  1100. self.parent.toolbar.ToggleTool(self.parent.actionOld, True)
  1101. self.parent.toolbar.ToggleTool(self.parent.toolbar.action['id'], False)
  1102. self.parent.toolbar.action['id'] = self.parent.actionOld
  1103. # resize resizable objects (only map sofar)
  1104. if self.mouse['use'] == 'resize':
  1105. mapId = self.instruction.FindInstructionByType('map').id
  1106. if self.dragId == mapId:
  1107. # necessary to change either map frame (scaleType 0,1,2) or region (scaletype 3)
  1108. newRectCanvas = self.pdcObj.GetIdBounds(mapId)
  1109. newRectPaper = self.CanvasPaperCoordinates(rect = newRectCanvas, canvasToPaper = True)
  1110. self.instruction[mapId]['rect'] = newRectPaper
  1111. if self.instruction[mapId]['scaleType'] in (0, 1, 2):
  1112. if self.instruction[mapId]['scaleType'] == 0:
  1113. scale, foo, rect = AutoAdjust(self, scaleType = 0,
  1114. map = self.instruction[mapId]['map'],
  1115. mapType = self.instruction[mapId]['mapType'],
  1116. rect = self.instruction[mapId]['rect'])
  1117. elif self.instruction[mapId]['scaleType'] == 1:
  1118. scale, foo, rect = AutoAdjust(self, scaleType = 1,
  1119. region = self.instruction[mapId]['region'],
  1120. rect = self.instruction[mapId]['rect'])
  1121. else:
  1122. scale, foo, rect = AutoAdjust(self, scaleType = 2,
  1123. rect = self.instruction[mapId]['rect'])
  1124. self.instruction[mapId]['rect'] = rect
  1125. self.instruction[mapId]['scale'] = scale
  1126. rectCanvas = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)
  1127. self.Draw(pen = self.pen['map'], brush = self.brush['map'],
  1128. pdc = self.pdcObj, drawid = mapId, pdctype = 'rectText', bb = rectCanvas)
  1129. elif self.instruction[mapId]['scaleType'] == 3:
  1130. ComputeSetRegion(self, mapDict = self.instruction[mapId].GetInstruction())
  1131. #check resolution
  1132. SetResolution(dpi = self.instruction[mapId]['resolution'],
  1133. width = self.instruction[mapId]['rect'].width,
  1134. height = self.instruction[mapId]['rect'].height)
  1135. self.RedrawSelectBox(mapId)
  1136. self.Zoom(zoomFactor = 1, view = (0, 0))
  1137. self.mouse['use'] = 'pointer'
  1138. # recalculate the position of objects after dragging
  1139. if self.mouse['use'] in ('pointer', 'resize') and self.dragId != -1:
  1140. if self.mouse['begin'] != event.GetPosition(): #for double click
  1141. self.RecalculatePosition(ids = [self.dragId])
  1142. if self.instruction[self.dragId].type in self.openDialogs:
  1143. self.openDialogs[self.instruction[self.dragId].type].updateDialog()
  1144. # double click launches dialogs
  1145. elif event.LeftDClick():
  1146. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1147. itemCall = { 'text':self.parent.OnAddText, 'mapinfo': self.parent.OnAddMapinfo,
  1148. 'scalebar': self.parent.OnAddScalebar, 'image': self.parent.OnAddImage,
  1149. 'northArrow' : self.parent.OnAddNorthArrow,
  1150. 'rasterLegend': self.parent.OnAddLegend, 'vectorLegend': self.parent.OnAddLegend,
  1151. 'map': self.parent.OnAddMap}
  1152. itemArg = { 'text': dict(event = None, id = self.dragId), 'mapinfo': dict(event = None),
  1153. 'scalebar': dict(event = None), 'image': dict(event = None, id = self.dragId),
  1154. 'northArrow': dict(event = None, id = self.dragId),
  1155. 'rasterLegend': dict(event = None), 'vectorLegend': dict(event = None, page = 1),
  1156. 'map': dict(event = None, notebook = True)}
  1157. type = self.instruction[self.dragId].type
  1158. itemCall[type](**itemArg[type])
  1159. def RecalculatePosition(self, ids):
  1160. for id in ids:
  1161. itype = self.instruction[id].type
  1162. if itype == 'map':
  1163. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1164. canvasToPaper = True)
  1165. self.RecalculateEN()
  1166. elif itype in ('mapinfo' ,'rasterLegend', 'vectorLegend', 'image', 'northArrow'):
  1167. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1168. canvasToPaper = True)
  1169. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1170. canvasToPaper = True)[:2]
  1171. if itype in ('image', 'northArrow'):
  1172. self.RecalculateEN()
  1173. elif itype == 'scalebar':
  1174. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1175. canvasToPaper = True)
  1176. self.instruction[id]['where'] = self.instruction[id]['rect'].GetCentre()
  1177. elif itype == 'text':
  1178. x, y = self.instruction[id]['coords'][0] - self.instruction[id]['xoffset'],\
  1179. self.instruction[id]['coords'][1] + self.instruction[id]['yoffset']
  1180. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1181. if self.instruction[id]['rotate'] is not None:
  1182. rot = float(self.instruction[id]['rotate'])/180*pi
  1183. else:
  1184. rot = 0
  1185. if self.instruction[id]['ref'].split()[0] == 'lower':
  1186. y += extent[1]
  1187. elif self.instruction[id]['ref'].split()[0] == 'center':
  1188. y += extent[1]/2
  1189. if self.instruction[id]['ref'].split()[1] == 'right':
  1190. x += extent[0] * cos(rot)
  1191. y -= extent[0] * sin(rot)
  1192. elif self.instruction[id]['ref'].split()[1] == 'center':
  1193. x += extent[0]/2 * cos(rot)
  1194. y -= extent[0]/2 * sin(rot)
  1195. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = wx.Rect2D(x, y, 0, 0),
  1196. canvasToPaper = True)[:2]
  1197. self.RecalculateEN()
  1198. def ComputeZoom(self, rect):
  1199. """!Computes zoom factor and scroll view"""
  1200. zoomFactor = 1
  1201. cW, cH = self.GetClientSize()
  1202. cW = float(cW)
  1203. if rect.IsEmpty(): # clicked on canvas
  1204. zoomFactor = 1.5
  1205. if self.mouse['use'] == 'zoomout':
  1206. zoomFactor = 1./zoomFactor
  1207. x,y = self.mouse['begin']
  1208. xView = x - x/zoomFactor#x - cW/(zoomFactor * 2)
  1209. yView = y - y/zoomFactor#y - cH/(zoomFactor * 2)
  1210. else: #dragging
  1211. rW, rH = float(rect.GetWidth()), float(rect.GetHeight())
  1212. zoomFactor = 1/max(rW/cW, rH/cH)
  1213. # when zooming to full extent, in some cases, there was zoom 1.01..., which causes problem
  1214. if abs(zoomFactor - 1) > 0.01:
  1215. zoomFactor = zoomFactor
  1216. else:
  1217. zoomFactor = 1.
  1218. if self.mouse['use'] == 'zoomout':
  1219. zoomFactor = min(rW/cW, rH/cH)
  1220. if rW/rH > cW/cH:
  1221. yView = rect.GetY() - (rW*(cH/cW) - rH)/2
  1222. xView = rect.GetX()
  1223. if self.mouse['use'] == 'zoomout':
  1224. x,y = rect.GetX() + (rW-(cW/cH)*rH)/2, rect.GetY()
  1225. xView, yView = -x, -y
  1226. else:
  1227. xView = rect.GetX() - (rH*(cW/cH) - rW)/2
  1228. yView = rect.GetY()
  1229. if self.mouse['use'] == 'zoomout':
  1230. x,y = rect.GetX(), rect.GetY() + (rH-(cH/cW)*rW)/2
  1231. xView, yView = -x, -y
  1232. return zoomFactor, (int(xView), int(yView))
  1233. def Zoom(self, zoomFactor, view):
  1234. """! Zoom to specified region, scroll view, redraw"""
  1235. if not self.currScale:
  1236. return
  1237. self.currScale = self.currScale*zoomFactor
  1238. if self.currScale > 10 or self.currScale < 0.1:
  1239. self.currScale = self.currScale/zoomFactor
  1240. return
  1241. if not self.preview:
  1242. # redraw paper
  1243. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  1244. pRect.OffsetXY(-view[0], -view[1])
  1245. pRect = self.ScaleRect(rect = pRect, scale = zoomFactor)
  1246. self.DrawPaper(pRect)
  1247. #redraw objects
  1248. for id in self.objectId:
  1249. oRect = self.CanvasPaperCoordinates(
  1250. rect = self.instruction[id]['rect'], canvasToPaper = False)
  1251. type = self.instruction[id].type
  1252. if type == 'text':
  1253. coords = self.instruction[id]['coords']# recalculate coordinates, they are not equal to BB
  1254. self.instruction[id]['coords'] = coords = [(int(coord) - view[i]) * zoomFactor
  1255. for i, coord in enumerate(coords)]
  1256. self.DrawRotText(pdc = self.pdcObj, drawId = id, textDict = self.instruction[id],
  1257. coords = coords, bounds = oRect )
  1258. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1259. if self.instruction[id]['rotate']:
  1260. rot = float(self.instruction[id]['rotate'])
  1261. else:
  1262. rot = 0
  1263. self.instruction[id]['rect'] = bounds = self.parent.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  1264. self.pdcObj.SetIdBounds(id, bounds)
  1265. elif type == 'northArrow':
  1266. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1267. drawid = id, pdctype = 'bitmap', bb = oRect)
  1268. else:
  1269. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1270. drawid = id, pdctype = 'rectText', bb = oRect)
  1271. #redraw tmp objects
  1272. if self.dragId != -1:
  1273. self.RedrawSelectBox(self.dragId)
  1274. #redraw preview
  1275. else: # preview mode
  1276. imageRect = self.pdcImage.GetIdBounds(self.imageId)
  1277. imageRect.OffsetXY(-view[0], -view[1])
  1278. imageRect = self.ScaleRect(rect = imageRect, scale = zoomFactor)
  1279. self.DrawImage(imageRect)
  1280. def ZoomAll(self):
  1281. """! Zoom to full extent"""
  1282. if not self.preview:
  1283. bounds = self.pdcPaper.GetIdBounds(self.pageId)
  1284. else:
  1285. bounds = self.pdcImage.GetIdBounds(self.imageId)
  1286. zoomP = bounds.Inflate(bounds.width/20, bounds.height/20)
  1287. zoomFactor, view = self.ComputeZoom(zoomP)
  1288. self.Zoom(zoomFactor, view)
  1289. def Draw(self, pen, brush, pdc, drawid = None, pdctype = 'rect', bb = wx.Rect(0,0,0,0)):
  1290. """! Draw object"""
  1291. if drawid is None:
  1292. drawid = wx.NewId()
  1293. bb = bb.Get()
  1294. pdc.BeginDrawing()
  1295. pdc.RemoveId(drawid)
  1296. pdc.SetId(drawid)
  1297. pdc.SetPen(pen)
  1298. pdc.SetBrush(brush)
  1299. if pdctype == 'bitmap':
  1300. if havePILImage:
  1301. file = self.instruction[drawid]['epsfile']
  1302. rotation = self.instruction[drawid]['rotate']
  1303. self.DrawBitmap(pdc = pdc, filePath = file, rotation = rotation, bbox = bb)
  1304. else: # draw only rectangle with label
  1305. pdctype = 'rectText'
  1306. if pdctype in ('rect', 'rectText'):
  1307. pdc.DrawRectangle(*bb)
  1308. if pdctype == 'rectText':
  1309. dc = wx.PaintDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  1310. font = self.font
  1311. size = 10
  1312. font.SetPointSize(size)
  1313. font.SetStyle(wx.ITALIC)
  1314. dc.SetFont(font)
  1315. pdc.SetFont(font)
  1316. text = '\n'.join(self.itemLabels[drawid])
  1317. w,h,lh = dc.GetMultiLineTextExtent(text)
  1318. textExtent = (w,h)
  1319. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1320. r = map(int, bb)
  1321. while not wx.Rect(*r).ContainsRect(textRect) and size >= 8:
  1322. size -= 2
  1323. font.SetPointSize(size)
  1324. dc.SetFont(font)
  1325. pdc.SetFont(font)
  1326. textExtent = dc.GetTextExtent(text)
  1327. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1328. pdc.SetTextForeground(wx.Color(100,100,100,200))
  1329. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1330. pdc.DrawText(text = text, x = textRect.x, y = textRect.y)
  1331. pdc.SetIdBounds(drawid, bb)
  1332. pdc.EndDrawing()
  1333. self.Refresh()
  1334. return drawid
  1335. def DrawBitmap(self, pdc, filePath, rotation, bbox):
  1336. """!Draw bitmap using PIL"""
  1337. pImg = PILImage.open(filePath)
  1338. if rotation:
  1339. # get rid of black background
  1340. pImg = pImg.convert("RGBA")
  1341. rot = pImg.rotate(rotation, expand = 1)
  1342. new = PILImage.new('RGBA', rot.size, (255,) * 4)
  1343. pImg = PILImage.composite(rot, new, rot)
  1344. pImg = pImg.resize((int(bbox[2]), int(bbox[3])), resample = PILImage.BICUBIC)
  1345. img = PilImageToWxImage(pImg)
  1346. bitmap = img.ConvertToBitmap()
  1347. mask = wx.Mask(bitmap, wx.WHITE)
  1348. bitmap.SetMask(mask)
  1349. pdc.DrawBitmap(bitmap, bbox[0], bbox[1], useMask = True)
  1350. def DrawRotText(self, pdc, drawId, textDict, coords, bounds):
  1351. if textDict['rotate']:
  1352. rot = float(textDict['rotate'])
  1353. else:
  1354. rot = 0
  1355. fontsize = textDict['fontsize'] * self.currScale
  1356. if textDict['background'] != 'none':
  1357. background = textDict['background']
  1358. else:
  1359. background = None
  1360. pdc.RemoveId(drawId)
  1361. pdc.SetId(drawId)
  1362. pdc.BeginDrawing()
  1363. # border is not redrawn when zoom changes, why?
  1364. ## if textDict['border'] != 'none' and not rot:
  1365. ## units = UnitConversion(self)
  1366. ## borderWidth = units.convert(value = textDict['width'],
  1367. ## fromUnit = 'point', toUnit = 'pixel' ) * self.currScale
  1368. ## pdc.SetPen(wx.Pen(colour = convertRGB(textDict['border']), width = borderWidth))
  1369. ## pdc.DrawRectangle(*bounds)
  1370. if background:
  1371. pdc.SetTextBackground(convertRGB(background))
  1372. pdc.SetBackgroundMode(wx.SOLID)
  1373. else:
  1374. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1375. fn = self.parent.makePSFont(textDict)
  1376. pdc.SetFont(fn)
  1377. pdc.SetTextForeground(convertRGB(textDict['color']))
  1378. pdc.DrawRotatedText(textDict['text'], coords[0], coords[1], rot)
  1379. pdc.SetIdBounds(drawId, wx.Rect(*bounds))
  1380. self.Refresh()
  1381. pdc.EndDrawing()
  1382. def DrawImage(self, rect):
  1383. """!Draw preview image to pseudoDC"""
  1384. self.pdcImage.ClearId(self.imageId)
  1385. self.pdcImage.SetId(self.imageId)
  1386. img = self.image
  1387. if img.GetWidth() != rect.width or img.GetHeight() != rect.height:
  1388. img = img.Scale(rect.width, rect.height)
  1389. bitmap = img.ConvertToBitmap()
  1390. self.pdcImage.BeginDrawing()
  1391. self.pdcImage.DrawBitmap(bitmap, rect.x, rect.y)
  1392. self.pdcImage.SetIdBounds(self.imageId, rect)
  1393. self.pdcImage.EndDrawing()
  1394. self.Refresh()
  1395. def DrawPaper(self, rect):
  1396. """!Draw paper and margins"""
  1397. page = self.instruction[self.pageId]
  1398. scale = page['Width'] / rect.GetWidth()
  1399. w = (page['Width'] - page['Right'] - page['Left']) / scale
  1400. h = (page['Height'] - page['Top'] - page['Bottom']) / scale
  1401. x = page['Left'] / scale + rect.GetX()
  1402. y = page['Top'] / scale + rect.GetY()
  1403. self.pdcPaper.BeginDrawing()
  1404. self.pdcPaper.RemoveId(self.pageId)
  1405. self.pdcPaper.SetId(self.pageId)
  1406. self.pdcPaper.SetPen(self.pen['paper'])
  1407. self.pdcPaper.SetBrush(self.brush['paper'])
  1408. self.pdcPaper.DrawRectangleRect(rect)
  1409. self.pdcPaper.SetPen(self.pen['margins'])
  1410. self.pdcPaper.SetBrush(self.brush['margins'])
  1411. self.pdcPaper.DrawRectangle(x, y, w, h)
  1412. self.pdcPaper.SetIdBounds(self.pageId, rect)
  1413. self.pdcPaper.EndDrawing()
  1414. self.Refresh()
  1415. def ImageRect(self):
  1416. """!Returns image centered in canvas, computes scale"""
  1417. img = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  1418. cW, cH = self.GetClientSize()
  1419. iW, iH = img.GetWidth(), img.GetHeight()
  1420. self.currScale = min(float(cW)/iW, float(cH)/iH)
  1421. iW = iW * self.currScale
  1422. iH = iH * self.currScale
  1423. x = cW/2 - iW/2
  1424. y = cH/2 - iH/2
  1425. imageRect = wx.Rect(x, y, iW, iH)
  1426. return imageRect
  1427. def RedrawSelectBox(self, id):
  1428. """!Redraws select box when selected object changes its size"""
  1429. if self.dragId == id:
  1430. rect = [self.pdcObj.GetIdBounds(id).Inflate(3,3)]
  1431. type = ['select']
  1432. ids = [self.idBoxTmp]
  1433. if self.instruction[id].type == 'map':
  1434. controlP = self.pdcObj.GetIdBounds(id).GetBottomRight()
  1435. rect.append(wx.Rect(controlP.x, controlP.y, 10,10))
  1436. type.append('resize')
  1437. ids.append(self.idResizeBoxTmp)
  1438. for id, type, rect in zip(ids, type, rect):
  1439. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcTmp,
  1440. drawid = id, pdctype = 'rect', bb = rect)
  1441. def UpdateMapLabel(self):
  1442. """!Updates map frame label"""
  1443. vector = self.instruction.FindInstructionByType('vector')
  1444. if vector:
  1445. vectorId = vector.id
  1446. else:
  1447. vectorId = None
  1448. raster = self.instruction.FindInstructionByType('raster')
  1449. if raster:
  1450. rasterId = raster.id
  1451. else:
  1452. rasterId = None
  1453. rasterName = 'None'
  1454. if rasterId:
  1455. rasterName = self.instruction[rasterId]['raster'].split('@')[0]
  1456. mapId = self.instruction.FindInstructionByType('map').id
  1457. self.itemLabels[mapId] = []
  1458. self.itemLabels[mapId].append(self.itemLabelsDict['map'])
  1459. self.itemLabels[mapId].append("raster: " + rasterName)
  1460. if vectorId:
  1461. for map in self.instruction[vectorId]['list']:
  1462. self.itemLabels[mapId].append('vector: ' + map[0].split('@')[0])
  1463. def UpdateLabel(self, itype, id):
  1464. self.itemLabels[id] = []
  1465. self.itemLabels[id].append(self.itemLabelsDict[itype])
  1466. if itype == 'image':
  1467. file = os.path.basename(self.instruction[id]['epsfile'])
  1468. self.itemLabels[id].append(file)
  1469. def OnSize(self, event):
  1470. """!Init image size to match window size
  1471. """
  1472. # not zoom all when notebook page is changed
  1473. if self.preview and self.parent.currentPage == 1 or not self.preview and self.parent.currentPage == 0:
  1474. self.ZoomAll()
  1475. self.OnIdle(None)
  1476. event.Skip()
  1477. def OnIdle(self, event):
  1478. """!Only re-render a image during idle time instead of
  1479. multiple times during resizing.
  1480. """
  1481. width, height = self.GetClientSize()
  1482. # Make new off screen bitmap: this bitmap will always have the
  1483. # current drawing in it, so it can be used to save the image
  1484. # to a file, or whatever.
  1485. self._buffer = wx.EmptyBitmap(width, height)
  1486. # re-render image on idle
  1487. self.resize = True
  1488. def ScaleRect(self, rect, scale):
  1489. """! Scale rectangle"""
  1490. return wx.Rect(rect.GetLeft()*scale, rect.GetTop()*scale,
  1491. rect.GetSize()[0]*scale, rect.GetSize()[1]*scale)
  1492. def main():
  1493. import gettext
  1494. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1495. app = wx.PySimpleApp()
  1496. wx.InitAllImageHandlers()
  1497. frame = PsMapFrame()
  1498. frame.Show()
  1499. app.MainLoop()
  1500. if __name__ == "__main__":
  1501. main()