frame.py 75 KB

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