frame.py 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804
  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, Icons['psMap']["addNorthArrow"].GetLabel())
  520. AddNorthArrow.SetBitmap(Icons['psMap']["addNorthArrow"].GetBitmap(self.iconsize))
  521. decmenu.AppendItem(AddNorthArrow)
  522. self.Bind(wx.EVT_MENU, self.OnAddNorthArrow, AddNorthArrow)
  523. # Popup the menu. If an item is selected then its handler
  524. # will be called before PopupMenu returns.
  525. self.PopupMenu(decmenu)
  526. decmenu.Destroy()
  527. def OnAddScalebar(self, event):
  528. """!Add scalebar"""
  529. if projInfo()['proj'] == 'll':
  530. GMessage(message = _("Scalebar is not appropriate for this projection"))
  531. return
  532. if self.instruction.FindInstructionByType('scalebar'):
  533. id = self.instruction.FindInstructionByType('scalebar').id
  534. else: id = None
  535. if 'scalebar' not in self.openDialogs:
  536. dlg = ScalebarDialog(self, id = id, settings = self.instruction)
  537. self.openDialogs['scalebar'] = dlg
  538. self.openDialogs['scalebar'].Show()
  539. def OnAddLegend(self, event, page = 0):
  540. """!Add raster or vector legend"""
  541. if self.instruction.FindInstructionByType('rasterLegend'):
  542. idR = self.instruction.FindInstructionByType('rasterLegend').id
  543. else: idR = None
  544. if self.instruction.FindInstructionByType('vectorLegend'):
  545. idV = self.instruction.FindInstructionByType('vectorLegend').id
  546. else: idV = None
  547. if 'rasterLegend' not in self.openDialogs:
  548. dlg = LegendDialog(self, id = [idR, idV], settings = self.instruction, page = page)
  549. self.openDialogs['rasterLegend'] = dlg
  550. self.openDialogs['vectorLegend'] = dlg
  551. self.openDialogs['rasterLegend'].notebook.ChangeSelection(page)
  552. self.openDialogs['rasterLegend'].Show()
  553. def OnAddMapinfo(self, event):
  554. if self.instruction.FindInstructionByType('mapinfo'):
  555. id = self.instruction.FindInstructionByType('mapinfo').id
  556. else: id = None
  557. if 'mapinfo' not in self.openDialogs:
  558. dlg = MapinfoDialog(self, id = id, settings = self.instruction)
  559. self.openDialogs['mapinfo'] = dlg
  560. self.openDialogs['mapinfo'].Show()
  561. def OnAddImage(self, event, id = None):
  562. """!Show dialog for image adding and editing"""
  563. position = None
  564. if 'image' in self.openDialogs:
  565. position = self.openDialogs['image'].GetPosition()
  566. self.openDialogs['image'].OnApply(event = None)
  567. self.openDialogs['image'].Destroy()
  568. dlg = ImageDialog(self, id = id, settings = self.instruction)
  569. self.openDialogs['image'] = dlg
  570. if position:
  571. dlg.SetPosition(position)
  572. dlg.Show()
  573. def OnAddNorthArrow(self, event, id = None):
  574. """!Show dialog for north arrow adding and editing"""
  575. if self.instruction.FindInstructionByType('northArrow'):
  576. id = self.instruction.FindInstructionByType('northArrow').id
  577. else: id = None
  578. if 'northArrow' not in self.openDialogs:
  579. dlg = NorthArrowDialog(self, id = id, settings = self.instruction)
  580. self.openDialogs['northArrow'] = dlg
  581. self.openDialogs['northArrow'].Show()
  582. def OnAddText(self, event, id = None):
  583. """!Show dialog for text adding and editing"""
  584. position = None
  585. if 'text' in self.openDialogs:
  586. position = self.openDialogs['text'].GetPosition()
  587. self.openDialogs['text'].OnApply(event = None)
  588. self.openDialogs['text'].Destroy()
  589. dlg = TextDialog(self, id = id, settings = self.instruction)
  590. self.openDialogs['text'] = dlg
  591. if position:
  592. dlg.SetPosition(position)
  593. dlg.Show()
  594. def getModifiedTextBounds(self, x, y, textExtent, rotation):
  595. """!computes bounding box of rotated text, not very precisely"""
  596. w, h = textExtent
  597. rotation = float(rotation)/180*pi
  598. H = float(w) * sin(rotation)
  599. W = float(w) * cos(rotation)
  600. X, Y = x, y
  601. if pi/2 < rotation <= 3*pi/2:
  602. X = x + W
  603. if 0 < rotation < pi:
  604. Y = y - H
  605. if rotation == 0:
  606. return wx.Rect(x,y, *textExtent)
  607. else:
  608. return wx.Rect(X, Y, abs(W), abs(H)).Inflate(h,h)
  609. def makePSFont(self, textDict):
  610. """!creates a wx.Font object from selected postscript font. To be
  611. used for estimating bounding rectangle of text"""
  612. fontsize = textDict['fontsize'] * self.canvas.currScale
  613. fontface = textDict['font'].split('-')[0]
  614. try:
  615. fontstyle = textDict['font'].split('-')[1]
  616. except IndexError:
  617. fontstyle = ''
  618. if fontface == "Times":
  619. family = wx.FONTFAMILY_ROMAN
  620. face = "times"
  621. elif fontface == "Helvetica":
  622. family = wx.FONTFAMILY_SWISS
  623. face = 'helvetica'
  624. elif fontface == "Courier":
  625. family = wx.FONTFAMILY_TELETYPE
  626. face = 'courier'
  627. else:
  628. family = wx.FONTFAMILY_DEFAULT
  629. face = ''
  630. style = wx.FONTSTYLE_NORMAL
  631. weight = wx.FONTWEIGHT_NORMAL
  632. if 'Oblique' in fontstyle:
  633. style = wx.FONTSTYLE_SLANT
  634. if 'Italic' in fontstyle:
  635. style = wx.FONTSTYLE_ITALIC
  636. if 'Bold' in fontstyle:
  637. weight = wx.FONTWEIGHT_BOLD
  638. try:
  639. fn = wx.Font(pointSize = fontsize, family = family, style = style,
  640. weight = weight, face = face)
  641. except:
  642. fn = wx.Font(pointSize = fontsize, family = wx.FONTFAMILY_DEFAULT,
  643. style = wx.FONTSTYLE_NORMAL, weight = wx.FONTWEIGHT_NORMAL)
  644. return fn
  645. def getTextExtent(self, textDict):
  646. """!Estimates bounding rectangle of text"""
  647. #fontsize = str(fontsize if fontsize >= 4 else 4)
  648. dc = wx.PaintDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  649. fn = self.makePSFont(textDict)
  650. try:
  651. dc.SetFont(fn)
  652. w,h,lh = dc.GetMultiLineTextExtent(textDict['text'])
  653. return (w,h)
  654. except:
  655. return (0,0)
  656. def getInitMap(self):
  657. """!Create default map frame when no map is selected, needed for coordinates in map units"""
  658. instrFile = grass.tempfile()
  659. instrFileFd = open(instrFile, mode = 'w')
  660. instrFileFd.write(self.InstructionFile())
  661. instrFileFd.flush()
  662. instrFileFd.close()
  663. page = self.instruction.FindInstructionByType('page')
  664. mapInitRect = GetMapBounds(instrFile, portrait = (page['Orientation'] == 'Portrait'))
  665. grass.try_remove(instrFile)
  666. region = grass.region()
  667. units = UnitConversion(self)
  668. realWidth = units.convert(value = abs(region['w'] - region['e']), fromUnit = 'meter', toUnit = 'inch')
  669. scale = mapInitRect.Get()[2]/realWidth
  670. initMap = self.instruction.FindInstructionByType('initMap')
  671. if initMap:
  672. id = initMap.id
  673. else:
  674. id = None
  675. if not id:
  676. id = wx.NewId()
  677. initMap = InitMap(id)
  678. self.instruction.AddInstruction(initMap)
  679. self.instruction[id].SetInstruction(dict(rect = mapInitRect, scale = scale))
  680. def OnDelete(self, event):
  681. if self.canvas.dragId != -1 and self.currentPage == 0:
  682. if self.instruction[self.canvas.dragId].type == 'map':
  683. self.deleteObject(self.canvas.dragId)
  684. self.getInitMap()
  685. self.canvas.RecalculateEN()
  686. else:
  687. self.deleteObject(self.canvas.dragId)
  688. def deleteObject(self, id):
  689. """!Deletes object, his id and redraws"""
  690. #delete from canvas
  691. self.canvas.pdcObj.RemoveId(id)
  692. if id == self.canvas.dragId:
  693. self.canvas.pdcTmp.RemoveAll()
  694. self.canvas.dragId = -1
  695. self.canvas.Refresh()
  696. # delete from instructions
  697. del self.instruction[id]
  698. def DialogDataChanged(self, id):
  699. ids = id
  700. if type(id) == int:
  701. ids = [id]
  702. for id in ids:
  703. itype = self.instruction[id].type
  704. if itype in ('scalebar', 'mapinfo', 'image'):
  705. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  706. self.canvas.UpdateLabel(itype = itype, id = id)
  707. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  708. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  709. self.canvas.RedrawSelectBox(id)
  710. if itype == 'northArrow':
  711. self.canvas.UpdateLabel(itype = itype, id = id)
  712. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  713. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  714. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'bitmap', bb = drawRectangle)
  715. self.canvas.RedrawSelectBox(id)
  716. if itype == 'text':
  717. if self.instruction[id]['rotate']:
  718. rot = float(self.instruction[id]['rotate'])
  719. else:
  720. rot = 0
  721. extent = self.getTextExtent(textDict = self.instruction[id].GetInstruction())
  722. rect = wx.Rect2D(self.instruction[id]['where'][0], self.instruction[id]['where'][1], 0, 0)
  723. self.instruction[id]['coords'] = list(self.canvas.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)[:2])
  724. #computes text coordinates according to reference point, not precisely
  725. if self.instruction[id]['ref'].split()[0] == 'lower':
  726. self.instruction[id]['coords'][1] -= extent[1]
  727. elif self.instruction[id]['ref'].split()[0] == 'center':
  728. self.instruction[id]['coords'][1] -= extent[1]/2
  729. if self.instruction[id]['ref'].split()[1] == 'right':
  730. self.instruction[id]['coords'][0] -= extent[0] * cos(rot/180*pi)
  731. self.instruction[id]['coords'][1] += extent[0] * sin(rot/180*pi)
  732. elif self.instruction[id]['ref'].split()[1] == 'center':
  733. self.instruction[id]['coords'][0] -= extent[0]/2 * cos(rot/180*pi)
  734. self.instruction[id]['coords'][1] += extent[0]/2 * sin(rot/180*pi)
  735. self.instruction[id]['coords'][0] += self.instruction[id]['xoffset']
  736. self.instruction[id]['coords'][1] -= self.instruction[id]['yoffset']
  737. coords = self.instruction[id]['coords']
  738. self.instruction[id]['rect'] = bounds = self.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  739. self.canvas.DrawRotText(pdc = self.canvas.pdcObj, drawId = id,
  740. textDict = self.instruction[id].GetInstruction(),
  741. coords = coords, bounds = bounds)
  742. self.canvas.RedrawSelectBox(id)
  743. if itype in ('map', 'vector', 'raster'):
  744. if itype == 'raster':#set resolution
  745. info = grass.raster_info(self.instruction[id]['raster'])
  746. RunCommand('g.region', nsres = info['nsres'], ewres = info['ewres'])
  747. # change current raster in raster legend
  748. if 'rasterLegend' in self.openDialogs:
  749. self.openDialogs['rasterLegend'].updateDialog()
  750. id = self.instruction.FindInstructionByType('map').id
  751. #check resolution
  752. if itype == 'raster':
  753. SetResolution(dpi = self.instruction[id]['resolution'],
  754. width = self.instruction[id]['rect'].width,
  755. height = self.instruction[id]['rect'].height)
  756. rectCanvas = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'],
  757. canvasToPaper = False)
  758. self.canvas.RecalculateEN()
  759. self.canvas.UpdateMapLabel()
  760. self.canvas.Draw(pen = self.pen['map'], brush = self.brush['map'],
  761. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = rectCanvas)
  762. # redraw select box
  763. self.canvas.RedrawSelectBox(id)
  764. self.canvas.pdcTmp.RemoveId(self.canvas.idZoomBoxTmp)
  765. # redraw to get map to the bottom layer
  766. #self.canvas.Zoom(zoomFactor = 1, view = (0, 0))
  767. if itype == 'rasterLegend':
  768. if self.instruction[id]['rLegend']:
  769. self.canvas.UpdateLabel(itype = itype, id = id)
  770. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  771. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  772. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  773. self.canvas.RedrawSelectBox(id)
  774. else:
  775. self.deleteObject(id)
  776. if itype == 'vectorLegend':
  777. if not self.instruction.FindInstructionByType('vector'):
  778. self.deleteObject(id)
  779. elif self.instruction[id]['vLegend']:
  780. self.canvas.UpdateLabel(itype = itype, id = id)
  781. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  782. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  783. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  784. self.canvas.RedrawSelectBox(id)
  785. else:
  786. self.deleteObject(id)
  787. def OnPageChanged(self, event):
  788. """!Flatnotebook page has changed"""
  789. self.currentPage = self.book.GetPageIndex(self.book.GetCurrentPage())
  790. def OnPageChanging(self, event):
  791. """!Flatnotebook page is changing"""
  792. if self.currentPage == 0 and self.mouse['use'] == 'addMap':
  793. event.Veto()
  794. def OnHelp(self, event):
  795. """!Show help"""
  796. if self.parent and self.parent.GetName() == 'LayerManager':
  797. log = self.parent.GetLogWindow()
  798. log.RunCmd(['g.manual',
  799. 'entry=wxGUI.PsMap'])
  800. else:
  801. RunCommand('g.manual',
  802. quiet = True,
  803. entry = 'wxGUI.PsMap')
  804. def OnAbout(self, event):
  805. """!Display About window"""
  806. info = wx.AboutDialogInfo()
  807. info.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  808. info.SetName(_('wxGUI Cartographic Composer'))
  809. info.SetWebSite('http://grass.osgeo.org')
  810. info.SetDescription(_('(C) 2011 by the GRASS Development Team\n\n') +
  811. '\n'.join(textwrap.wrap(_('This program is free software under the GNU General Public License'
  812. '(>=v2). Read the file COPYING that comes with GRASS for details.'), 75)))
  813. wx.AboutBox(info)
  814. def OnCloseWindow(self, event):
  815. """!Close window"""
  816. try:
  817. os.remove(self.imgName)
  818. except OSError:
  819. pass
  820. grass.set_raise_on_error(False)
  821. self.Destroy()
  822. class PsMapBufferedWindow(wx.Window):
  823. """!A buffered window class.
  824. @param parent parent window
  825. @param kwargs other wx.Window parameters
  826. """
  827. def __init__(self, parent, id = wx.ID_ANY,
  828. style = wx.NO_FULL_REPAINT_ON_RESIZE,
  829. **kwargs):
  830. wx.Window.__init__(self, parent, id = id, style = style)
  831. self.parent = parent
  832. self.FitInside()
  833. # store an off screen empty bitmap for saving to file
  834. self._buffer = None
  835. # indicates whether or not a resize event has taken place
  836. self.resize = False
  837. self.mouse = kwargs['mouse']
  838. self.cursors = kwargs['cursors']
  839. self.preview = kwargs['preview']
  840. self.pen = kwargs['pen']
  841. self.brush = kwargs['brush']
  842. if kwargs.has_key('instruction'):
  843. self.instruction = kwargs['instruction']
  844. if kwargs.has_key('openDialogs'):
  845. self.openDialogs = kwargs['openDialogs']
  846. if kwargs.has_key('pageId'):
  847. self.pageId = kwargs['pageId']
  848. if kwargs.has_key('objectId'):
  849. self.objectId = kwargs['objectId']
  850. #labels
  851. self.itemLabelsDict = { 'map': 'MAP FRAME',
  852. 'rasterLegend': 'RASTER LEGEND',
  853. 'vectorLegend': 'VECTOR LEGEND',
  854. 'mapinfo': 'MAP INFO',
  855. 'scalebar': 'SCALE BAR',
  856. 'image': 'IMAGE',
  857. 'northArrow': 'NORTH ARROW'}
  858. self.itemLabels = {}
  859. # define PseudoDC
  860. self.pdc = wx.PseudoDC()
  861. self.pdcObj = wx.PseudoDC()
  862. self.pdcPaper = wx.PseudoDC()
  863. self.pdcTmp = wx.PseudoDC()
  864. self.pdcImage = wx.PseudoDC()
  865. dc = wx.PaintDC(self)
  866. self.font = dc.GetFont()
  867. self.SetClientSize((700,510))#?
  868. self._buffer = wx.EmptyBitmap(*self.GetClientSize())
  869. self.idBoxTmp = wx.NewId()
  870. self.idZoomBoxTmp = wx.NewId()
  871. self.idResizeBoxTmp = wx.NewId()
  872. self.dragId = -1
  873. if self.preview:
  874. self.image = None
  875. self.imageId = 2000
  876. self.imgName = self.parent.imgName
  877. self.currScale = None
  878. self.Clear()
  879. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
  880. self.Bind(wx.EVT_PAINT, self.OnPaint)
  881. self.Bind(wx.EVT_SIZE, self.OnSize)
  882. self.Bind(wx.EVT_IDLE, self.OnIdle)
  883. self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
  884. def Clear(self):
  885. """!Clear canvas and set paper
  886. """
  887. bg = wx.LIGHT_GREY_BRUSH
  888. self.pdcPaper.BeginDrawing()
  889. self.pdcPaper.SetBackground(bg)
  890. self.pdcPaper.Clear()
  891. self.pdcPaper.EndDrawing()
  892. self.pdcObj.RemoveAll()
  893. self.pdcTmp.RemoveAll()
  894. if not self.preview:
  895. self.SetPage()
  896. def CanvasPaperCoordinates(self, rect, canvasToPaper = True):
  897. """!Converts canvas (pixel) -> paper (inch) coordinates and size and vice versa"""
  898. units = UnitConversion(self)
  899. fromU = 'pixel'
  900. toU = 'inch'
  901. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  902. pRectx, pRecty = pRect.x, pRect.y
  903. scale = 1/self.currScale
  904. if not canvasToPaper: # paper -> canvas
  905. fromU = 'inch'
  906. toU = 'pixel'
  907. scale = self.currScale
  908. pRectx = units.convert(value = - pRect.x, fromUnit = 'pixel', toUnit = 'inch' ) /scale #inch, real, negative
  909. pRecty = units.convert(value = - pRect.y, fromUnit = 'pixel', toUnit = 'inch' ) /scale
  910. Width = units.convert(value = rect.width, fromUnit = fromU, toUnit = toU) * scale
  911. Height = units.convert(value = rect.height, fromUnit = fromU, toUnit = toU) * scale
  912. X = units.convert(value = (rect.x - pRectx), fromUnit = fromU, toUnit = toU) * scale
  913. Y = units.convert(value = (rect.y - pRecty), fromUnit = fromU, toUnit = toU) * scale
  914. return wx.Rect2D(X, Y, Width, Height)
  915. def SetPage(self):
  916. """!Sets and changes page, redraws paper"""
  917. page = self.instruction[self.pageId]
  918. if not page:
  919. page = PageSetup(id = self.pageId)
  920. self.instruction.AddInstruction(page)
  921. ppi = wx.PaintDC(self).GetPPI()
  922. cW, cH = self.GetClientSize()
  923. pW, pH = page['Width']*ppi[0], page['Height']*ppi[1]
  924. if self.currScale is None:
  925. self.currScale = min(cW/pW, cH/pH)
  926. pW = pW * self.currScale
  927. pH = pH * self.currScale
  928. x = cW/2 - pW/2
  929. y = cH/2 - pH/2
  930. self.DrawPaper(wx.Rect(x, y, pW, pH))
  931. def modifyRectangle(self, r):
  932. """! Recalculates rectangle not to have negative size"""
  933. if r.GetWidth() < 0:
  934. r.SetX(r.GetX() + r.GetWidth())
  935. if r.GetHeight() < 0:
  936. r.SetY(r.GetY() + r.GetHeight())
  937. r.SetWidth(abs(r.GetWidth()))
  938. r.SetHeight(abs(r.GetHeight()))
  939. return r
  940. def RecalculateEN(self):
  941. """!Recalculate east and north for texts (eps, points) after their or map's movement"""
  942. try:
  943. mapId = self.instruction.FindInstructionByType('map').id
  944. except AttributeError:
  945. mapId = self.instruction.FindInstructionByType('initMap').id
  946. for itemType in ('text', 'image', 'northArrow'):
  947. items = self.instruction.FindInstructionByType(itemType, list = True)
  948. for item in items:
  949. e, n = PaperMapCoordinates(map = self.instruction[mapId], x = self.instruction[item.id]['where'][0],
  950. y = self.instruction[item.id]['where'][1], paperToMap = True)
  951. self.instruction[item.id]['east'], self.instruction[item.id]['north'] = e, n
  952. def OnPaint(self, event):
  953. """!Draw pseudo DC to buffer
  954. """
  955. if not self._buffer:
  956. return
  957. dc = wx.BufferedPaintDC(self, self._buffer)
  958. # use PrepareDC to set position correctly
  959. self.PrepareDC(dc)
  960. dc.SetBackground(wx.LIGHT_GREY_BRUSH)
  961. dc.Clear()
  962. # draw paper
  963. if not self.preview:
  964. self.pdcPaper.DrawToDC(dc)
  965. # draw to the DC using the calculated clipping rect
  966. rgn = self.GetUpdateRegion()
  967. if not self.preview:
  968. self.pdcObj.DrawToDCClipped(dc, rgn.GetBox())
  969. else:
  970. self.pdcImage.DrawToDCClipped(dc, rgn.GetBox())
  971. self.pdcTmp.DrawToDCClipped(dc, rgn.GetBox())
  972. def OnMouse(self, event):
  973. if event.GetWheelRotation():
  974. zoom = event.GetWheelRotation()
  975. use = self.mouse['use']
  976. self.mouse['begin'] = event.GetPosition()
  977. if zoom > 0:
  978. self.mouse['use'] = 'zoomin'
  979. else:
  980. self.mouse['use'] = 'zoomout'
  981. zoomFactor, view = self.ComputeZoom(wx.Rect(0,0,0,0))
  982. self.Zoom(zoomFactor, view)
  983. self.mouse['use'] = use
  984. if event.Moving():
  985. if self.mouse['use'] in ('pointer', 'resize'):
  986. pos = event.GetPosition()
  987. foundResize = self.pdcTmp.FindObjects(pos[0], pos[1])
  988. if foundResize and foundResize[0] == self.idResizeBoxTmp:
  989. self.SetCursor(self.cursors["sizenwse"])
  990. self.parent.SetStatusText(_('Click and drag to resize object'), 0)
  991. else:
  992. self.parent.SetStatusText('', 0)
  993. self.SetCursor(self.cursors["default"])
  994. elif event.LeftDown():
  995. self.mouse['begin'] = event.GetPosition()
  996. self.begin = self.mouse['begin']
  997. if self.mouse['use'] in ('pan', 'zoomin', 'zoomout', 'addMap'):
  998. pass
  999. #select
  1000. if self.mouse['use'] == 'pointer':
  1001. found = self.pdcObj.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  1002. foundResize = self.pdcTmp.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  1003. if foundResize and foundResize[0] == self.idResizeBoxTmp:
  1004. self.mouse['use'] = 'resize'
  1005. # when resizing, proportions match region
  1006. if self.instruction[self.dragId].type == 'map':
  1007. self.constraint = False
  1008. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1009. if self.instruction[self.dragId]['scaleType'] in (0, 1, 2):
  1010. self.constraint = True
  1011. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1012. elif found:
  1013. self.dragId = found[0]
  1014. self.RedrawSelectBox(self.dragId)
  1015. if self.instruction[self.dragId].type != 'map':
  1016. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1017. self.Refresh()
  1018. else:
  1019. self.dragId = -1
  1020. self.pdcTmp.RemoveId(self.idBoxTmp)
  1021. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1022. self.Refresh()
  1023. elif event.Dragging() and event.LeftIsDown():
  1024. #draw box when zooming, creating map
  1025. if self.mouse['use'] in ('zoomin', 'zoomout', 'addMap'):
  1026. self.mouse['end'] = event.GetPosition()
  1027. r = wx.Rect(self.mouse['begin'][0], self.mouse['begin'][1],
  1028. self.mouse['end'][0]-self.mouse['begin'][0], self.mouse['end'][1]-self.mouse['begin'][1])
  1029. r = self.modifyRectangle(r)
  1030. self.Draw(pen = self.pen['box'], brush = self.brush['box'], pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
  1031. pdctype = 'rect', bb = r)
  1032. # panning
  1033. if self.mouse["use"] == 'pan':
  1034. self.mouse['end'] = event.GetPosition()
  1035. view = self.mouse['begin'][0] - self.mouse['end'][0], self.mouse['begin'][1] - self.mouse['end'][1]
  1036. zoomFactor = 1
  1037. self.Zoom(zoomFactor, view)
  1038. self.mouse['begin'] = event.GetPosition()
  1039. #move object
  1040. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1041. self.mouse['end'] = event.GetPosition()
  1042. dx, dy = self.mouse['end'][0] - self.begin[0], self.mouse['end'][1] - self.begin[1]
  1043. self.pdcObj.TranslateId(self.dragId, dx, dy)
  1044. self.pdcTmp.TranslateId(self.idBoxTmp, dx, dy)
  1045. self.pdcTmp.TranslateId(self.idResizeBoxTmp, dx, dy)
  1046. if self.instruction[self.dragId].type == 'text':
  1047. self.instruction[self.dragId]['coords'] = self.instruction[self.dragId]['coords'][0] + dx,\
  1048. self.instruction[self.dragId]['coords'][1] + dy
  1049. self.begin = event.GetPosition()
  1050. self.Refresh()
  1051. # resize object
  1052. if self.mouse['use'] == 'resize':
  1053. type = self.instruction[self.dragId].type
  1054. pos = event.GetPosition()
  1055. x, y = self.mapBounds.GetX(), self.mapBounds.GetY()
  1056. width, height = self.mapBounds.GetWidth(), self.mapBounds.GetHeight()
  1057. diffX = pos[0] - self.mouse['begin'][0]
  1058. diffY = pos[1] - self.mouse['begin'][1]
  1059. # match given region
  1060. if self.constraint:
  1061. if width > height:
  1062. newWidth = width + diffX
  1063. newHeight = height + diffX * (float(height) / width)
  1064. else:
  1065. newWidth = width + diffY * (float(width) / height)
  1066. newHeight = height + diffY
  1067. else:
  1068. newWidth = width + diffX
  1069. newHeight = height + diffY
  1070. if newWidth < 10 or newHeight < 10:
  1071. return
  1072. bounds = wx.Rect(x, y, newWidth, newHeight)
  1073. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj, drawid = self.dragId,
  1074. pdctype = 'rectText', bb = bounds)
  1075. self.RedrawSelectBox(self.dragId)
  1076. elif event.LeftUp():
  1077. # zoom in, zoom out
  1078. if self.mouse['use'] in ('zoomin','zoomout'):
  1079. zoomR = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1080. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1081. self.Refresh()
  1082. zoomFactor, view = self.ComputeZoom(zoomR)
  1083. self.Zoom(zoomFactor, view)
  1084. # draw map frame
  1085. if self.mouse['use'] == 'addMap':
  1086. rectTmp = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1087. # too small rectangle, it's usually some mistake
  1088. if rectTmp.GetWidth() < 20 or rectTmp.GetHeight() < 20:
  1089. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1090. self.Refresh()
  1091. return
  1092. rectPaper = self.CanvasPaperCoordinates(rect = rectTmp, canvasToPaper = True)
  1093. dlg = MapDialog(parent = self.parent, id = [None, None, None], settings = self.instruction,
  1094. rect = rectPaper)
  1095. self.openDialogs['map'] = dlg
  1096. self.openDialogs['map'].Show()
  1097. self.mouse['use'] = self.parent.mouseOld
  1098. self.SetCursor(self.parent.cursorOld)
  1099. self.parent.toolbar.ToggleTool(self.parent.actionOld, True)
  1100. self.parent.toolbar.ToggleTool(self.parent.toolbar.action['id'], False)
  1101. self.parent.toolbar.action['id'] = self.parent.actionOld
  1102. # resize resizable objects (only map sofar)
  1103. if self.mouse['use'] == 'resize':
  1104. mapId = self.instruction.FindInstructionByType('map').id
  1105. if self.dragId == mapId:
  1106. # necessary to change either map frame (scaleType 0,1,2) or region (scaletype 3)
  1107. newRectCanvas = self.pdcObj.GetIdBounds(mapId)
  1108. newRectPaper = self.CanvasPaperCoordinates(rect = newRectCanvas, canvasToPaper = True)
  1109. self.instruction[mapId]['rect'] = newRectPaper
  1110. if self.instruction[mapId]['scaleType'] in (0, 1, 2):
  1111. if self.instruction[mapId]['scaleType'] == 0:
  1112. scale, foo, rect = AutoAdjust(self, scaleType = 0,
  1113. map = self.instruction[mapId]['map'],
  1114. mapType = self.instruction[mapId]['mapType'],
  1115. rect = self.instruction[mapId]['rect'])
  1116. elif self.instruction[mapId]['scaleType'] == 1:
  1117. scale, foo, rect = AutoAdjust(self, scaleType = 1,
  1118. region = self.instruction[mapId]['region'],
  1119. rect = self.instruction[mapId]['rect'])
  1120. else:
  1121. scale, foo, rect = AutoAdjust(self, scaleType = 2,
  1122. rect = self.instruction[mapId]['rect'])
  1123. self.instruction[mapId]['rect'] = rect
  1124. self.instruction[mapId]['scale'] = scale
  1125. rectCanvas = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)
  1126. self.Draw(pen = self.pen['map'], brush = self.brush['map'],
  1127. pdc = self.pdcObj, drawid = mapId, pdctype = 'rectText', bb = rectCanvas)
  1128. elif self.instruction[mapId]['scaleType'] == 3:
  1129. ComputeSetRegion(self, mapDict = self.instruction[mapId].GetInstruction())
  1130. #check resolution
  1131. SetResolution(dpi = self.instruction[mapId]['resolution'],
  1132. width = self.instruction[mapId]['rect'].width,
  1133. height = self.instruction[mapId]['rect'].height)
  1134. self.RedrawSelectBox(mapId)
  1135. self.Zoom(zoomFactor = 1, view = (0, 0))
  1136. self.mouse['use'] = 'pointer'
  1137. # recalculate the position of objects after dragging
  1138. if self.mouse['use'] in ('pointer', 'resize') and self.dragId != -1:
  1139. if self.mouse['begin'] != event.GetPosition(): #for double click
  1140. self.RecalculatePosition(ids = [self.dragId])
  1141. if self.instruction[self.dragId].type in self.openDialogs:
  1142. self.openDialogs[self.instruction[self.dragId].type].updateDialog()
  1143. # double click launches dialogs
  1144. elif event.LeftDClick():
  1145. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1146. itemCall = { 'text':self.parent.OnAddText, 'mapinfo': self.parent.OnAddMapinfo,
  1147. 'scalebar': self.parent.OnAddScalebar, 'image': self.parent.OnAddImage,
  1148. 'northArrow' : self.parent.OnAddNorthArrow,
  1149. 'rasterLegend': self.parent.OnAddLegend, 'vectorLegend': self.parent.OnAddLegend,
  1150. 'map': self.parent.OnAddMap}
  1151. itemArg = { 'text': dict(event = None, id = self.dragId), 'mapinfo': dict(event = None),
  1152. 'scalebar': dict(event = None), 'image': dict(event = None, id = self.dragId),
  1153. 'northArrow': dict(event = None, id = self.dragId),
  1154. 'rasterLegend': dict(event = None), 'vectorLegend': dict(event = None, page = 1),
  1155. 'map': dict(event = None, notebook = True)}
  1156. type = self.instruction[self.dragId].type
  1157. itemCall[type](**itemArg[type])
  1158. def RecalculatePosition(self, ids):
  1159. for id in ids:
  1160. itype = self.instruction[id].type
  1161. if itype == 'map':
  1162. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1163. canvasToPaper = True)
  1164. self.RecalculateEN()
  1165. elif itype in ('mapinfo' ,'rasterLegend', 'vectorLegend', 'image', 'northArrow'):
  1166. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1167. canvasToPaper = True)
  1168. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1169. canvasToPaper = True)[:2]
  1170. if itype in ('image', 'northArrow'):
  1171. self.RecalculateEN()
  1172. elif itype == 'scalebar':
  1173. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1174. canvasToPaper = True)
  1175. self.instruction[id]['where'] = self.instruction[id]['rect'].GetCentre()
  1176. elif itype == 'text':
  1177. x, y = self.instruction[id]['coords'][0] - self.instruction[id]['xoffset'],\
  1178. self.instruction[id]['coords'][1] + self.instruction[id]['yoffset']
  1179. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1180. if self.instruction[id]['rotate'] is not None:
  1181. rot = float(self.instruction[id]['rotate'])/180*pi
  1182. else:
  1183. rot = 0
  1184. if self.instruction[id]['ref'].split()[0] == 'lower':
  1185. y += extent[1]
  1186. elif self.instruction[id]['ref'].split()[0] == 'center':
  1187. y += extent[1]/2
  1188. if self.instruction[id]['ref'].split()[1] == 'right':
  1189. x += extent[0] * cos(rot)
  1190. y -= extent[0] * sin(rot)
  1191. elif self.instruction[id]['ref'].split()[1] == 'center':
  1192. x += extent[0]/2 * cos(rot)
  1193. y -= extent[0]/2 * sin(rot)
  1194. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = wx.Rect2D(x, y, 0, 0),
  1195. canvasToPaper = True)[:2]
  1196. self.RecalculateEN()
  1197. def ComputeZoom(self, rect):
  1198. """!Computes zoom factor and scroll view"""
  1199. zoomFactor = 1
  1200. cW, cH = self.GetClientSize()
  1201. cW = float(cW)
  1202. if rect.IsEmpty(): # clicked on canvas
  1203. zoomFactor = 1.5
  1204. if self.mouse['use'] == 'zoomout':
  1205. zoomFactor = 1./zoomFactor
  1206. x,y = self.mouse['begin']
  1207. xView = x - x/zoomFactor#x - cW/(zoomFactor * 2)
  1208. yView = y - y/zoomFactor#y - cH/(zoomFactor * 2)
  1209. else: #dragging
  1210. rW, rH = float(rect.GetWidth()), float(rect.GetHeight())
  1211. zoomFactor = 1/max(rW/cW, rH/cH)
  1212. # when zooming to full extent, in some cases, there was zoom 1.01..., which causes problem
  1213. if abs(zoomFactor - 1) > 0.01:
  1214. zoomFactor = zoomFactor
  1215. else:
  1216. zoomFactor = 1.
  1217. if self.mouse['use'] == 'zoomout':
  1218. zoomFactor = min(rW/cW, rH/cH)
  1219. if rW/rH > cW/cH:
  1220. yView = rect.GetY() - (rW*(cH/cW) - rH)/2
  1221. xView = rect.GetX()
  1222. if self.mouse['use'] == 'zoomout':
  1223. x,y = rect.GetX() + (rW-(cW/cH)*rH)/2, rect.GetY()
  1224. xView, yView = -x, -y
  1225. else:
  1226. xView = rect.GetX() - (rH*(cW/cH) - rW)/2
  1227. yView = rect.GetY()
  1228. if self.mouse['use'] == 'zoomout':
  1229. x,y = rect.GetX(), rect.GetY() + (rH-(cH/cW)*rW)/2
  1230. xView, yView = -x, -y
  1231. return zoomFactor, (int(xView), int(yView))
  1232. def Zoom(self, zoomFactor, view):
  1233. """! Zoom to specified region, scroll view, redraw"""
  1234. if not self.currScale:
  1235. return
  1236. self.currScale = self.currScale*zoomFactor
  1237. if self.currScale > 10 or self.currScale < 0.1:
  1238. self.currScale = self.currScale/zoomFactor
  1239. return
  1240. if not self.preview:
  1241. # redraw paper
  1242. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  1243. pRect.OffsetXY(-view[0], -view[1])
  1244. pRect = self.ScaleRect(rect = pRect, scale = zoomFactor)
  1245. self.DrawPaper(pRect)
  1246. #redraw objects
  1247. for id in self.objectId:
  1248. oRect = self.CanvasPaperCoordinates(
  1249. rect = self.instruction[id]['rect'], canvasToPaper = False)
  1250. type = self.instruction[id].type
  1251. if type == 'text':
  1252. coords = self.instruction[id]['coords']# recalculate coordinates, they are not equal to BB
  1253. self.instruction[id]['coords'] = coords = [(int(coord) - view[i]) * zoomFactor
  1254. for i, coord in enumerate(coords)]
  1255. self.DrawRotText(pdc = self.pdcObj, drawId = id, textDict = self.instruction[id],
  1256. coords = coords, bounds = oRect )
  1257. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1258. if self.instruction[id]['rotate']:
  1259. rot = float(self.instruction[id]['rotate'])
  1260. else:
  1261. rot = 0
  1262. self.instruction[id]['rect'] = bounds = self.parent.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  1263. self.pdcObj.SetIdBounds(id, bounds)
  1264. elif type == 'northArrow':
  1265. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1266. drawid = id, pdctype = 'bitmap', bb = oRect)
  1267. else:
  1268. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1269. drawid = id, pdctype = 'rectText', bb = oRect)
  1270. #redraw tmp objects
  1271. if self.dragId != -1:
  1272. self.RedrawSelectBox(self.dragId)
  1273. #redraw preview
  1274. else: # preview mode
  1275. imageRect = self.pdcImage.GetIdBounds(self.imageId)
  1276. imageRect.OffsetXY(-view[0], -view[1])
  1277. imageRect = self.ScaleRect(rect = imageRect, scale = zoomFactor)
  1278. self.DrawImage(imageRect)
  1279. def ZoomAll(self):
  1280. """! Zoom to full extent"""
  1281. if not self.preview:
  1282. bounds = self.pdcPaper.GetIdBounds(self.pageId)
  1283. else:
  1284. bounds = self.pdcImage.GetIdBounds(self.imageId)
  1285. zoomP = bounds.Inflate(bounds.width/20, bounds.height/20)
  1286. zoomFactor, view = self.ComputeZoom(zoomP)
  1287. self.Zoom(zoomFactor, view)
  1288. def Draw(self, pen, brush, pdc, drawid = None, pdctype = 'rect', bb = wx.Rect(0,0,0,0)):
  1289. """! Draw object"""
  1290. if drawid is None:
  1291. drawid = wx.NewId()
  1292. bb = bb.Get()
  1293. pdc.BeginDrawing()
  1294. pdc.RemoveId(drawid)
  1295. pdc.SetId(drawid)
  1296. pdc.SetPen(pen)
  1297. pdc.SetBrush(brush)
  1298. if pdctype == 'bitmap':
  1299. if havePILImage:
  1300. file = self.instruction[drawid]['epsfile']
  1301. rotation = self.instruction[drawid]['rotate']
  1302. self.DrawBitmap(pdc = pdc, filePath = file, rotation = rotation, bbox = bb)
  1303. else: # draw only rectangle with label
  1304. pdctype = 'rectText'
  1305. if pdctype in ('rect', 'rectText'):
  1306. pdc.DrawRectangle(*bb)
  1307. if pdctype == 'rectText':
  1308. dc = wx.PaintDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  1309. font = self.font
  1310. size = 10
  1311. font.SetPointSize(size)
  1312. font.SetStyle(wx.ITALIC)
  1313. dc.SetFont(font)
  1314. pdc.SetFont(font)
  1315. text = '\n'.join(self.itemLabels[drawid])
  1316. w,h,lh = dc.GetMultiLineTextExtent(text)
  1317. textExtent = (w,h)
  1318. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1319. r = map(int, bb)
  1320. while not wx.Rect(*r).ContainsRect(textRect) and size >= 8:
  1321. size -= 2
  1322. font.SetPointSize(size)
  1323. dc.SetFont(font)
  1324. pdc.SetFont(font)
  1325. textExtent = dc.GetTextExtent(text)
  1326. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1327. pdc.SetTextForeground(wx.Color(100,100,100,200))
  1328. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1329. pdc.DrawText(text = text, x = textRect.x, y = textRect.y)
  1330. pdc.SetIdBounds(drawid, bb)
  1331. pdc.EndDrawing()
  1332. self.Refresh()
  1333. return drawid
  1334. def DrawBitmap(self, pdc, filePath, rotation, bbox):
  1335. """!Draw bitmap using PIL"""
  1336. pImg = PILImage.open(filePath)
  1337. if rotation:
  1338. # get rid of black background
  1339. pImg = pImg.convert("RGBA")
  1340. rot = pImg.rotate(rotation, expand = 1)
  1341. new = PILImage.new('RGBA', rot.size, (255,) * 4)
  1342. pImg = PILImage.composite(rot, new, rot)
  1343. pImg = pImg.resize((int(bbox[2]), int(bbox[3])), resample = PILImage.BICUBIC)
  1344. img = PilImageToWxImage(pImg)
  1345. bitmap = img.ConvertToBitmap()
  1346. mask = wx.Mask(bitmap, wx.WHITE)
  1347. bitmap.SetMask(mask)
  1348. pdc.DrawBitmap(bitmap, bbox[0], bbox[1], useMask = True)
  1349. def DrawRotText(self, pdc, drawId, textDict, coords, bounds):
  1350. if textDict['rotate']:
  1351. rot = float(textDict['rotate'])
  1352. else:
  1353. rot = 0
  1354. fontsize = textDict['fontsize'] * self.currScale
  1355. if textDict['background'] != 'none':
  1356. background = textDict['background']
  1357. else:
  1358. background = None
  1359. pdc.RemoveId(drawId)
  1360. pdc.SetId(drawId)
  1361. pdc.BeginDrawing()
  1362. # border is not redrawn when zoom changes, why?
  1363. ## if textDict['border'] != 'none' and not rot:
  1364. ## units = UnitConversion(self)
  1365. ## borderWidth = units.convert(value = textDict['width'],
  1366. ## fromUnit = 'point', toUnit = 'pixel' ) * self.currScale
  1367. ## pdc.SetPen(wx.Pen(colour = convertRGB(textDict['border']), width = borderWidth))
  1368. ## pdc.DrawRectangle(*bounds)
  1369. if background:
  1370. pdc.SetTextBackground(convertRGB(background))
  1371. pdc.SetBackgroundMode(wx.SOLID)
  1372. else:
  1373. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1374. fn = self.parent.makePSFont(textDict)
  1375. pdc.SetFont(fn)
  1376. pdc.SetTextForeground(convertRGB(textDict['color']))
  1377. pdc.DrawRotatedText(textDict['text'], coords[0], coords[1], rot)
  1378. pdc.SetIdBounds(drawId, wx.Rect(*bounds))
  1379. self.Refresh()
  1380. pdc.EndDrawing()
  1381. def DrawImage(self, rect):
  1382. """!Draw preview image to pseudoDC"""
  1383. self.pdcImage.ClearId(self.imageId)
  1384. self.pdcImage.SetId(self.imageId)
  1385. img = self.image
  1386. if img.GetWidth() != rect.width or img.GetHeight() != rect.height:
  1387. img = img.Scale(rect.width, rect.height)
  1388. bitmap = img.ConvertToBitmap()
  1389. self.pdcImage.BeginDrawing()
  1390. self.pdcImage.DrawBitmap(bitmap, rect.x, rect.y)
  1391. self.pdcImage.SetIdBounds(self.imageId, rect)
  1392. self.pdcImage.EndDrawing()
  1393. self.Refresh()
  1394. def DrawPaper(self, rect):
  1395. """!Draw paper and margins"""
  1396. page = self.instruction[self.pageId]
  1397. scale = page['Width'] / rect.GetWidth()
  1398. w = (page['Width'] - page['Right'] - page['Left']) / scale
  1399. h = (page['Height'] - page['Top'] - page['Bottom']) / scale
  1400. x = page['Left'] / scale + rect.GetX()
  1401. y = page['Top'] / scale + rect.GetY()
  1402. self.pdcPaper.BeginDrawing()
  1403. self.pdcPaper.RemoveId(self.pageId)
  1404. self.pdcPaper.SetId(self.pageId)
  1405. self.pdcPaper.SetPen(self.pen['paper'])
  1406. self.pdcPaper.SetBrush(self.brush['paper'])
  1407. self.pdcPaper.DrawRectangleRect(rect)
  1408. self.pdcPaper.SetPen(self.pen['margins'])
  1409. self.pdcPaper.SetBrush(self.brush['margins'])
  1410. self.pdcPaper.DrawRectangle(x, y, w, h)
  1411. self.pdcPaper.SetIdBounds(self.pageId, rect)
  1412. self.pdcPaper.EndDrawing()
  1413. self.Refresh()
  1414. def ImageRect(self):
  1415. """!Returns image centered in canvas, computes scale"""
  1416. img = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  1417. cW, cH = self.GetClientSize()
  1418. iW, iH = img.GetWidth(), img.GetHeight()
  1419. self.currScale = min(float(cW)/iW, float(cH)/iH)
  1420. iW = iW * self.currScale
  1421. iH = iH * self.currScale
  1422. x = cW/2 - iW/2
  1423. y = cH/2 - iH/2
  1424. imageRect = wx.Rect(x, y, iW, iH)
  1425. return imageRect
  1426. def RedrawSelectBox(self, id):
  1427. """!Redraws select box when selected object changes its size"""
  1428. if self.dragId == id:
  1429. rect = [self.pdcObj.GetIdBounds(id).Inflate(3,3)]
  1430. type = ['select']
  1431. ids = [self.idBoxTmp]
  1432. if self.instruction[id].type == 'map':
  1433. controlP = self.pdcObj.GetIdBounds(id).GetBottomRight()
  1434. rect.append(wx.Rect(controlP.x, controlP.y, 10,10))
  1435. type.append('resize')
  1436. ids.append(self.idResizeBoxTmp)
  1437. for id, type, rect in zip(ids, type, rect):
  1438. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcTmp,
  1439. drawid = id, pdctype = 'rect', bb = rect)
  1440. def UpdateMapLabel(self):
  1441. """!Updates map frame label"""
  1442. vector = self.instruction.FindInstructionByType('vector')
  1443. if vector:
  1444. vectorId = vector.id
  1445. else:
  1446. vectorId = None
  1447. raster = self.instruction.FindInstructionByType('raster')
  1448. if raster:
  1449. rasterId = raster.id
  1450. else:
  1451. rasterId = None
  1452. rasterName = 'None'
  1453. if rasterId:
  1454. rasterName = self.instruction[rasterId]['raster'].split('@')[0]
  1455. mapId = self.instruction.FindInstructionByType('map').id
  1456. self.itemLabels[mapId] = []
  1457. self.itemLabels[mapId].append(self.itemLabelsDict['map'])
  1458. self.itemLabels[mapId].append("raster: " + rasterName)
  1459. if vectorId:
  1460. for map in self.instruction[vectorId]['list']:
  1461. self.itemLabels[mapId].append('vector: ' + map[0].split('@')[0])
  1462. def UpdateLabel(self, itype, id):
  1463. self.itemLabels[id] = []
  1464. self.itemLabels[id].append(self.itemLabelsDict[itype])
  1465. if itype == 'image':
  1466. file = os.path.basename(self.instruction[id]['epsfile'])
  1467. self.itemLabels[id].append(file)
  1468. def OnSize(self, event):
  1469. """!Init image size to match window size
  1470. """
  1471. # not zoom all when notebook page is changed
  1472. if self.preview and self.parent.currentPage == 1 or not self.preview and self.parent.currentPage == 0:
  1473. self.ZoomAll()
  1474. self.OnIdle(None)
  1475. event.Skip()
  1476. def OnIdle(self, event):
  1477. """!Only re-render a image during idle time instead of
  1478. multiple times during resizing.
  1479. """
  1480. width, height = self.GetClientSize()
  1481. # Make new off screen bitmap: this bitmap will always have the
  1482. # current drawing in it, so it can be used to save the image
  1483. # to a file, or whatever.
  1484. self._buffer = wx.EmptyBitmap(width, height)
  1485. # re-render image on idle
  1486. self.resize = True
  1487. def ScaleRect(self, rect, scale):
  1488. """! Scale rectangle"""
  1489. return wx.Rect(rect.GetLeft()*scale, rect.GetTop()*scale,
  1490. rect.GetSize()[0]*scale, rect.GetSize()[1]*scale)
  1491. def main():
  1492. import gettext
  1493. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1494. app = wx.PySimpleApp()
  1495. wx.InitAllImageHandlers()
  1496. frame = PsMapFrame()
  1497. frame.Show()
  1498. app.MainLoop()
  1499. if __name__ == "__main__":
  1500. main()