psmap.py 68 KB

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