psmap.py 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655
  1. """!
  2. @package psmap
  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(
  626. rect = self.instruction[id]['rect'], canvasToPaper = False)
  627. self.canvas.Draw( pen = self.pen[itype], brush = self.brush[itype],
  628. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  629. self.canvas.RedrawSelectBox(id)
  630. if itype == 'text':
  631. if self.instruction[id]['rotate']:
  632. rot = float(self.instruction[id]['rotate'])
  633. else:
  634. rot = 0
  635. extent = self.getTextExtent(textDict = self.instruction[id].GetInstruction())
  636. rect = wx.Rect2D(self.instruction[id]['where'][0], self.instruction[id]['where'][1], 0, 0)
  637. self.instruction[id]['coords'] = list(self.canvas.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)[:2])
  638. #computes text coordinates according to reference point, not precisely
  639. if self.instruction[id]['ref'].split()[0] == 'lower':
  640. self.instruction[id]['coords'][1] -= extent[1]
  641. elif self.instruction[id]['ref'].split()[0] == 'center':
  642. self.instruction[id]['coords'][1] -= extent[1]/2
  643. if self.instruction[id]['ref'].split()[1] == 'right':
  644. self.instruction[id]['coords'][0] -= extent[0] * cos(rot/180*pi)
  645. self.instruction[id]['coords'][1] += extent[0] * sin(rot/180*pi)
  646. elif self.instruction[id]['ref'].split()[1] == 'center':
  647. self.instruction[id]['coords'][0] -= extent[0]/2 * cos(rot/180*pi)
  648. self.instruction[id]['coords'][1] += extent[0]/2 * sin(rot/180*pi)
  649. self.instruction[id]['coords'][0] += self.instruction[id]['xoffset']
  650. self.instruction[id]['coords'][1] -= self.instruction[id]['yoffset']
  651. coords = self.instruction[id]['coords']
  652. self.instruction[id]['rect'] = bounds = self.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  653. self.canvas.DrawRotText(pdc = self.canvas.pdcObj, drawId = id,
  654. textDict = self.instruction[id].GetInstruction(),
  655. coords = coords, bounds = bounds)
  656. self.canvas.RedrawSelectBox(id)
  657. if itype in ('map', 'vector', 'raster'):
  658. if itype == 'raster':#set resolution
  659. resol = RunCommand('r.info', read = True, flags = 's', map = self.instruction[id]['raster'])
  660. resol = grass.parse_key_val(resol, val_type = float)
  661. RunCommand('g.region', nsres = resol['nsres'], ewres = resol['ewres'])
  662. # change current raster in raster legend
  663. if 'rasterLegend' in self.openDialogs:
  664. self.openDialogs['rasterLegend'].updateDialog()
  665. id = self.instruction.FindInstructionByType('map').id
  666. #check resolution
  667. if itype == 'raster':
  668. SetResolution(dpi = self.instruction[id]['resolution'],
  669. width = self.instruction[id]['rect'].width,
  670. height = self.instruction[id]['rect'].height)
  671. rectCanvas = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'],
  672. canvasToPaper = False)
  673. self.canvas.RecalculateEN()
  674. self.canvas.UpdateMapLabel()
  675. self.canvas.Draw( pen = self.pen['map'], brush = self.brush['map'],
  676. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = rectCanvas)
  677. # redraw select box
  678. self.canvas.RedrawSelectBox(id)
  679. self.canvas.pdcTmp.RemoveId(self.canvas.idZoomBoxTmp)
  680. # redraw to get map to the bottom layer
  681. #self.canvas.Zoom(zoomFactor = 1, view = (0, 0))
  682. if itype == 'rasterLegend':
  683. if self.instruction[id]['rLegend']:
  684. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  685. self.canvas.Draw( pen = self.pen[itype], brush = self.brush[itype],
  686. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  687. self.canvas.RedrawSelectBox(id)
  688. else:
  689. self.deleteObject(id)
  690. if itype == 'vectorLegend':
  691. if not self.instruction.FindInstructionByType('vector'):
  692. self.deleteObject(id)
  693. elif self.instruction[id]['vLegend']:
  694. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  695. self.canvas.Draw( pen = self.pen[itype], brush = self.brush[itype],
  696. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  697. self.canvas.RedrawSelectBox(id)
  698. else:
  699. self.deleteObject(id)
  700. def OnPageChanged(self, event):
  701. """!Flatnotebook page has changed"""
  702. self.currentPage = self.book.GetPageIndex(self.book.GetCurrentPage())
  703. def OnPageChanging(self, event):
  704. """!Flatnotebook page is changing"""
  705. if self.currentPage == 0 and self.mouse['use'] == 'addMap':
  706. event.Veto()
  707. def OnHelp(self, event):
  708. """!Show help"""
  709. if self.parent and self.parent.GetName() == 'LayerManager':
  710. log = self.parent.GetLogWindow()
  711. log.RunCmd(['g.manual',
  712. 'entry=wxGUI.PsMap'])
  713. else:
  714. RunCommand('g.manual',
  715. quiet = True,
  716. entry = 'wxGUI.PsMap')
  717. def OnAbout(self, event):
  718. """!Display About window"""
  719. info = wx.AboutDialogInfo()
  720. info.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  721. info.SetName(_('wxGUI Hardcopy Map Utility'))
  722. info.SetWebSite('http://grass.osgeo.org')
  723. info.SetDescription(_('(C) 2011 by the GRASS Development Team\n\n') +
  724. '\n'.join(textwrap.wrap(_('This program is free software under the GNU General Public License'
  725. '(>=v2). Read the file COPYING that comes with GRASS for details.'), 75)))
  726. wx.AboutBox(info)
  727. def OnCloseWindow(self, event):
  728. """!Close window"""
  729. try:
  730. os.remove(self.imgName)
  731. except OSError:
  732. pass
  733. grass.set_raise_on_error(False)
  734. self.Destroy()
  735. class PsMapBufferedWindow(wx.Window):
  736. """!A buffered window class.
  737. @param parent parent window
  738. @param kwargs other wx.Window parameters
  739. """
  740. def __init__(self, parent, id = wx.ID_ANY,
  741. style = wx.NO_FULL_REPAINT_ON_RESIZE,
  742. **kwargs):
  743. wx.Window.__init__(self, parent, id = id, style = style)
  744. self.parent = parent
  745. self.FitInside()
  746. # store an off screen empty bitmap for saving to file
  747. self._buffer = None
  748. # indicates whether or not a resize event has taken place
  749. self.resize = False
  750. self.mouse = kwargs['mouse']
  751. self.cursors = kwargs['cursors']
  752. self.preview = kwargs['preview']
  753. self.pen = kwargs['pen']
  754. self.brush = kwargs['brush']
  755. if kwargs.has_key('instruction'):
  756. self.instruction = kwargs['instruction']
  757. if kwargs.has_key('openDialogs'):
  758. self.openDialogs = kwargs['openDialogs']
  759. if kwargs.has_key('pageId'):
  760. self.pageId = kwargs['pageId']
  761. if kwargs.has_key('objectId'):
  762. self.objectId = kwargs['objectId']
  763. #labels
  764. self.itemLabels = { 'map': ['MAP FRAME'],
  765. 'rasterLegend': ['RASTER LEGEND'],
  766. 'vectorLegend': ['VECTOR LEGEND'],
  767. 'mapinfo': ['MAP INFO'],
  768. 'scalebar': ['SCALE BAR']}
  769. # define PseudoDC
  770. self.pdc = wx.PseudoDC()
  771. self.pdcObj = wx.PseudoDC()
  772. self.pdcPaper = wx.PseudoDC()
  773. self.pdcTmp = wx.PseudoDC()
  774. self.pdcImage = wx.PseudoDC()
  775. dc = wx.PaintDC(self)
  776. self.font = dc.GetFont()
  777. self.SetClientSize((700,510))#?
  778. self._buffer = wx.EmptyBitmap(*self.GetClientSize())
  779. self.idBoxTmp = wx.NewId()
  780. self.idZoomBoxTmp = wx.NewId()
  781. self.idResizeBoxTmp = wx.NewId()
  782. self.dragId = -1
  783. if self.preview:
  784. self.image = None
  785. self.imageId = 2000
  786. self.imgName = self.parent.imgName
  787. self.currScale = None
  788. self.Clear()
  789. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
  790. self.Bind(wx.EVT_PAINT, self.OnPaint)
  791. self.Bind(wx.EVT_SIZE, self.OnSize)
  792. self.Bind(wx.EVT_IDLE, self.OnIdle)
  793. self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
  794. def Clear(self):
  795. """!Clear canvas and set paper
  796. """
  797. bg = wx.LIGHT_GREY_BRUSH
  798. self.pdcPaper.BeginDrawing()
  799. self.pdcPaper.SetBackground(bg)
  800. self.pdcPaper.Clear()
  801. self.pdcPaper.EndDrawing()
  802. self.pdcObj.RemoveAll()
  803. self.pdcTmp.RemoveAll()
  804. if not self.preview:
  805. self.SetPage()
  806. def CanvasPaperCoordinates(self, rect, canvasToPaper = True):
  807. """!Converts canvas (pixel) -> paper (inch) coordinates and size and vice versa"""
  808. units = UnitConversion(self)
  809. fromU = 'pixel'
  810. toU = 'inch'
  811. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  812. pRectx, pRecty = pRect.x, pRect.y
  813. scale = 1/self.currScale
  814. if not canvasToPaper: # paper -> canvas
  815. fromU = 'inch'
  816. toU = 'pixel'
  817. scale = self.currScale
  818. pRectx = units.convert(value = - pRect.x, fromUnit = 'pixel', toUnit = 'inch' ) /scale #inch, real, negative
  819. pRecty = units.convert(value = - pRect.y, fromUnit = 'pixel', toUnit = 'inch' ) /scale
  820. Width = units.convert(value = rect.width, fromUnit = fromU, toUnit = toU) * scale
  821. Height = units.convert(value = rect.height, fromUnit = fromU, toUnit = toU) * scale
  822. X = units.convert(value = (rect.x - pRectx), fromUnit = fromU, toUnit = toU) * scale
  823. Y = units.convert(value = (rect.y - pRecty), fromUnit = fromU, toUnit = toU) * scale
  824. return wx.Rect2D(X, Y, Width, Height)
  825. def SetPage(self):
  826. """!Sets and changes page, redraws paper"""
  827. page = self.instruction[self.pageId]
  828. if not page:
  829. page = PageSetup(id = self.pageId)
  830. self.instruction.AddInstruction(page)
  831. ppi = wx.PaintDC(self).GetPPI()
  832. cW, cH = self.GetClientSize()
  833. pW, pH = page['Width']*ppi[0], page['Height']*ppi[1]
  834. if self.currScale is None:
  835. self.currScale = min(cW/pW, cH/pH)
  836. pW = pW * self.currScale
  837. pH = pH * self.currScale
  838. x = cW/2 - pW/2
  839. y = cH/2 - pH/2
  840. self.DrawPaper(wx.Rect(x, y, pW, pH))
  841. def modifyRectangle(self, r):
  842. """! Recalculates rectangle not to have negative size"""
  843. if r.GetWidth() < 0:
  844. r.SetX(r.GetX() + r.GetWidth())
  845. if r.GetHeight() < 0:
  846. r.SetY(r.GetY() + r.GetHeight())
  847. r.SetWidth(abs(r.GetWidth()))
  848. r.SetHeight(abs(r.GetHeight()))
  849. return r
  850. def RecalculateEN(self):
  851. """!Recalculate east and north for texts (eps, points) after their or map's movement"""
  852. try:
  853. mapId = self.instruction.FindInstructionByType('map').id
  854. except AttributeError:
  855. mapId = self.instruction.FindInstructionByType('initMap').id
  856. texts = self.instruction.FindInstructionByType('text', list = True)
  857. for text in texts:
  858. e, n = PaperMapCoordinates(map = self.instruction[mapId], x = self.instruction[text.id]['where'][0],
  859. y = self.instruction[text.id]['where'][1], paperToMap = True)
  860. self.instruction[text.id]['east'], self.instruction[text.id]['north'] = e, n
  861. def OnPaint(self, event):
  862. """!Draw pseudo DC to buffer
  863. """
  864. if not self._buffer:
  865. return
  866. dc = wx.BufferedPaintDC(self, self._buffer)
  867. # use PrepareDC to set position correctly
  868. self.PrepareDC(dc)
  869. dc.SetBackground(wx.LIGHT_GREY_BRUSH)
  870. dc.Clear()
  871. # draw paper
  872. if not self.preview:
  873. self.pdcPaper.DrawToDC(dc)
  874. # draw to the DC using the calculated clipping rect
  875. rgn = self.GetUpdateRegion()
  876. if not self.preview:
  877. self.pdcObj.DrawToDCClipped(dc, rgn.GetBox())
  878. else:
  879. self.pdcImage.DrawToDCClipped(dc, rgn.GetBox())
  880. self.pdcTmp.DrawToDCClipped(dc, rgn.GetBox())
  881. def OnMouse(self, event):
  882. if event.GetWheelRotation():
  883. zoom = event.GetWheelRotation()
  884. use = self.mouse['use']
  885. self.mouse['begin'] = event.GetPosition()
  886. if zoom > 0:
  887. self.mouse['use'] = 'zoomin'
  888. else:
  889. self.mouse['use'] = 'zoomout'
  890. zoomFactor, view = self.ComputeZoom(wx.Rect(0,0,0,0))
  891. self.Zoom(zoomFactor, view)
  892. self.mouse['use'] = use
  893. if event.Moving():
  894. if self.mouse['use'] in ('pointer', 'resize'):
  895. pos = event.GetPosition()
  896. foundResize = self.pdcTmp.FindObjects(pos[0], pos[1])
  897. if foundResize and foundResize[0] == self.idResizeBoxTmp:
  898. self.SetCursor(self.cursors["sizenwse"])
  899. self.parent.SetStatusText(_('Click and drag to resize object'), 0)
  900. else:
  901. self.parent.SetStatusText(_(''), 0)
  902. self.SetCursor(self.cursors["default"])
  903. elif event.LeftDown():
  904. self.mouse['begin'] = event.GetPosition()
  905. self.begin = self.mouse['begin']
  906. if self.mouse['use'] in ('pan', 'zoomin', 'zoomout', 'addMap'):
  907. pass
  908. #select
  909. if self.mouse['use'] == 'pointer':
  910. found = self.pdcObj.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  911. foundResize = self.pdcTmp.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  912. if foundResize and foundResize[0] == self.idResizeBoxTmp:
  913. self.mouse['use'] = 'resize'
  914. # when resizing, proportions match region
  915. if self.instruction[self.dragId].type == 'map':
  916. self.constraint = False
  917. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  918. if self.instruction[self.dragId]['scaleType'] in (0, 1, 2):
  919. self.constraint = True
  920. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  921. elif found:
  922. self.dragId = found[0]
  923. self.RedrawSelectBox(self.dragId)
  924. if self.instruction[self.dragId].type != 'map':
  925. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  926. self.Refresh()
  927. else:
  928. self.dragId = -1
  929. self.pdcTmp.RemoveId(self.idBoxTmp)
  930. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  931. self.Refresh()
  932. elif event.Dragging() and event.LeftIsDown():
  933. #draw box when zooming, creating map
  934. if self.mouse['use'] in ('zoomin', 'zoomout', 'addMap'):
  935. self.mouse['end'] = event.GetPosition()
  936. r = wx.Rect(self.mouse['begin'][0], self.mouse['begin'][1],
  937. self.mouse['end'][0]-self.mouse['begin'][0], self.mouse['end'][1]-self.mouse['begin'][1])
  938. r = self.modifyRectangle(r)
  939. self.Draw(pen = self.pen['box'], brush = self.brush['box'], pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
  940. pdctype = 'rect', bb = r)
  941. # panning
  942. if self.mouse["use"] == 'pan':
  943. self.mouse['end'] = event.GetPosition()
  944. view = self.mouse['begin'][0] - self.mouse['end'][0], self.mouse['begin'][1] - self.mouse['end'][1]
  945. zoomFactor = 1
  946. self.Zoom(zoomFactor, view)
  947. self.mouse['begin'] = event.GetPosition()
  948. #move object
  949. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  950. self.mouse['end'] = event.GetPosition()
  951. dx, dy = self.mouse['end'][0] - self.begin[0], self.mouse['end'][1] - self.begin[1]
  952. self.pdcObj.TranslateId(self.dragId, dx, dy)
  953. self.pdcTmp.TranslateId(self.idBoxTmp, dx, dy)
  954. self.pdcTmp.TranslateId(self.idResizeBoxTmp, dx, dy)
  955. if self.instruction[self.dragId].type == 'text':
  956. self.instruction[self.dragId]['coords'] = self.instruction[self.dragId]['coords'][0] + dx,\
  957. self.instruction[self.dragId]['coords'][1] + dy
  958. self.begin = event.GetPosition()
  959. self.Refresh()
  960. # resize object
  961. if self.mouse['use'] == 'resize':
  962. type = self.instruction[self.dragId].type
  963. pos = event.GetPosition()
  964. x, y = self.mapBounds.GetX(), self.mapBounds.GetY()
  965. width, height = self.mapBounds.GetWidth(), self.mapBounds.GetHeight()
  966. diffX = pos[0] - self.mouse['begin'][0]
  967. diffY = pos[1] - self.mouse['begin'][1]
  968. # match given region
  969. if self.constraint:
  970. if width > height:
  971. newWidth = width + diffX
  972. newHeight = height + diffX * (float(height) / width)
  973. else:
  974. newWidth = width + diffY * (float(width) / height)
  975. newHeight = height + diffY
  976. else:
  977. newWidth = width + diffX
  978. newHeight = height + diffY
  979. if newWidth < 10 or newHeight < 10:
  980. return
  981. bounds = wx.Rect(x, y, newWidth, newHeight)
  982. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj, drawid = self.dragId,
  983. pdctype = 'rectText', bb = bounds)
  984. self.RedrawSelectBox(self.dragId)
  985. elif event.LeftUp():
  986. # zoom in, zoom out
  987. if self.mouse['use'] in ('zoomin','zoomout'):
  988. zoomR = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  989. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  990. self.Refresh()
  991. zoomFactor, view = self.ComputeZoom(zoomR)
  992. self.Zoom(zoomFactor, view)
  993. # draw map frame
  994. if self.mouse['use'] == 'addMap':
  995. rectTmp = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  996. # too small rectangle, it's usually some mistake
  997. if rectTmp.GetWidth() < 20 or rectTmp.GetHeight() < 20:
  998. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  999. self.Refresh()
  1000. return
  1001. rectPaper = self.CanvasPaperCoordinates(rect = rectTmp, canvasToPaper = True)
  1002. dlg = MapDialog(parent = self.parent, id = [None, None, None], settings = self.instruction,
  1003. rect = rectPaper)
  1004. self.openDialogs['map'] = dlg
  1005. self.openDialogs['map'].Show()
  1006. self.mouse['use'] = self.parent.mouseOld
  1007. self.SetCursor(self.parent.cursorOld)
  1008. self.parent.toolbar.ToggleTool(self.parent.actionOld, True)
  1009. self.parent.toolbar.ToggleTool(self.parent.toolbar.action['id'], False)
  1010. self.parent.toolbar.action['id'] = self.parent.actionOld
  1011. # resize resizable objects (only map sofar)
  1012. if self.mouse['use'] == 'resize':
  1013. mapId = self.instruction.FindInstructionByType('map').id
  1014. if self.dragId == mapId:
  1015. # necessary to change either map frame (scaleType 0,1,2) or region (scaletype 3)
  1016. newRectCanvas = self.pdcObj.GetIdBounds(mapId)
  1017. newRectPaper = self.CanvasPaperCoordinates(rect = newRectCanvas, canvasToPaper = True)
  1018. self.instruction[mapId]['rect'] = newRectPaper
  1019. if self.instruction[mapId]['scaleType'] in (0, 1, 2):
  1020. if self.instruction[mapId]['scaleType'] == 0:
  1021. scale, foo, rect = AutoAdjust(self, scaleType = 0,
  1022. map = self.instruction[mapId]['map'],
  1023. mapType = self.instruction[mapId]['mapType'],
  1024. rect = self.instruction[mapId]['rect'])
  1025. elif self.instruction[mapId]['scaleType'] == 1:
  1026. scale, foo, rect = AutoAdjust(self, scaleType = 1,
  1027. region = self.instruction[mapId]['region'],
  1028. rect = self.instruction[mapId]['rect'])
  1029. else:
  1030. scale, foo, rect = AutoAdjust(self, scaleType = 2,
  1031. rect = self.instruction[mapId]['rect'])
  1032. self.instruction[mapId]['rect'] = rect
  1033. self.instruction[mapId]['scale'] = scale
  1034. rectCanvas = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)
  1035. self.Draw(pen = self.pen['map'], brush = self.brush['map'],
  1036. pdc = self.pdcObj, drawid = mapId, pdctype = 'rectText', bb = rectCanvas)
  1037. elif self.instruction[mapId]['scaleType'] == 3:
  1038. ComputeSetRegion(self, mapDict = self.instruction[mapId].GetInstruction())
  1039. #check resolution
  1040. SetResolution(dpi = self.instruction[mapId]['resolution'],
  1041. width = self.instruction[mapId]['rect'].width,
  1042. height = self.instruction[mapId]['rect'].height)
  1043. self.RedrawSelectBox(mapId)
  1044. self.Zoom(zoomFactor = 1, view = (0, 0))
  1045. self.mouse['use'] = 'pointer'
  1046. # recalculate the position of objects after dragging
  1047. if self.mouse['use'] in ('pointer', 'resize') and self.dragId != -1:
  1048. if self.mouse['begin'] != event.GetPosition(): #for double click
  1049. self.RecalculatePosition(ids = [self.dragId])
  1050. if self.instruction[self.dragId].type in self.openDialogs:
  1051. self.openDialogs[self.instruction[self.dragId].type].updateDialog()
  1052. # double click launches dialogs
  1053. elif event.LeftDClick():
  1054. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1055. itemCall = { 'text':self.parent.OnAddText, 'mapinfo': self.parent.OnAddMapinfo,
  1056. 'scalebar': self.parent.OnAddScalebar,
  1057. 'rasterLegend': self.parent.OnAddLegend, 'vectorLegend': self.parent.OnAddLegend,
  1058. 'map': self.parent.OnAddMap}
  1059. itemArg = { 'text': dict(event = None, id = self.dragId), 'mapinfo': dict(event = None),
  1060. 'scalebar': dict(event = None),
  1061. 'rasterLegend': dict(event = None), 'vectorLegend': dict(event = None, page = 1),
  1062. 'map': dict(event = None, notebook = True)}
  1063. type = self.instruction[self.dragId].type
  1064. itemCall[type](**itemArg[type])
  1065. def RecalculatePosition(self, ids):
  1066. for id in ids:
  1067. itype = self.instruction[id].type
  1068. if itype == 'map':
  1069. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1070. canvasToPaper = True)
  1071. self.RecalculateEN()
  1072. elif itype in ('mapinfo' ,'rasterLegend', 'vectorLegend'):
  1073. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1074. canvasToPaper = True)
  1075. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1076. canvasToPaper = True)[:2]
  1077. elif itype == 'scalebar':
  1078. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1079. canvasToPaper = True)
  1080. self.instruction[id]['where'] = self.instruction[id]['rect'].GetCentre()
  1081. elif itype == 'text':
  1082. x, y = self.instruction[id]['coords'][0] - self.instruction[id]['xoffset'],\
  1083. self.instruction[id]['coords'][1] + self.instruction[id]['yoffset']
  1084. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1085. if self.instruction[id]['rotate'] is not None:
  1086. rot = float(self.instruction[id]['rotate'])/180*pi
  1087. else:
  1088. rot = 0
  1089. if self.instruction[id]['ref'].split()[0] == 'lower':
  1090. y += extent[1]
  1091. elif self.instruction[id]['ref'].split()[0] == 'center':
  1092. y += extent[1]/2
  1093. if self.instruction[id]['ref'].split()[1] == 'right':
  1094. x += extent[0] * cos(rot)
  1095. y -= extent[0] * sin(rot)
  1096. elif self.instruction[id]['ref'].split()[1] == 'center':
  1097. x += extent[0]/2 * cos(rot)
  1098. y -= extent[0]/2 * sin(rot)
  1099. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = wx.Rect2D(x, y, 0, 0),
  1100. canvasToPaper = True)[:2]
  1101. self.RecalculateEN()
  1102. def ComputeZoom(self, rect):
  1103. """!Computes zoom factor and scroll view"""
  1104. zoomFactor = 1
  1105. cW, cH = self.GetClientSize()
  1106. cW = float(cW)
  1107. if rect.IsEmpty(): # clicked on canvas
  1108. zoomFactor = 1.5
  1109. if self.mouse['use'] == 'zoomout':
  1110. zoomFactor = 1./zoomFactor
  1111. x,y = self.mouse['begin']
  1112. xView = x - x/zoomFactor#x - cW/(zoomFactor * 2)
  1113. yView = y - y/zoomFactor#y - cH/(zoomFactor * 2)
  1114. else: #dragging
  1115. rW, rH = float(rect.GetWidth()), float(rect.GetHeight())
  1116. zoomFactor = 1/max(rW/cW, rH/cH)
  1117. # when zooming to full extent, in some cases, there was zoom 1.01..., which causes problem
  1118. if abs(zoomFactor - 1) > 0.01:
  1119. zoomFactor = zoomFactor
  1120. else:
  1121. zoomFactor = 1.
  1122. if self.mouse['use'] == 'zoomout':
  1123. zoomFactor = min(rW/cW, rH/cH)
  1124. if rW/rH > cW/cH:
  1125. yView = rect.GetY() - (rW*(cH/cW) - rH)/2
  1126. xView = rect.GetX()
  1127. if self.mouse['use'] == 'zoomout':
  1128. x,y = rect.GetX() + (rW-(cW/cH)*rH)/2, rect.GetY()
  1129. xView, yView = -x, -y
  1130. else:
  1131. xView = rect.GetX() - (rH*(cW/cH) - rW)/2
  1132. yView = rect.GetY()
  1133. if self.mouse['use'] == 'zoomout':
  1134. x,y = rect.GetX(), rect.GetY() + (rH-(cH/cW)*rW)/2
  1135. xView, yView = -x, -y
  1136. return zoomFactor, (int(xView), int(yView))
  1137. def Zoom(self, zoomFactor, view):
  1138. """! Zoom to specified region, scroll view, redraw"""
  1139. if not self.currScale:
  1140. return
  1141. self.currScale = self.currScale*zoomFactor
  1142. if self.currScale > 10 or self.currScale < 0.1:
  1143. self.currScale = self.currScale/zoomFactor
  1144. return
  1145. if not self.preview:
  1146. # redraw paper
  1147. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  1148. pRect.OffsetXY(-view[0], -view[1])
  1149. pRect = self.ScaleRect(rect = pRect, scale = zoomFactor)
  1150. self.DrawPaper(pRect)
  1151. #redraw objects
  1152. for id in self.objectId:
  1153. oRect = self.CanvasPaperCoordinates(
  1154. rect = self.instruction[id]['rect'], canvasToPaper = False)
  1155. type = self.instruction[id].type
  1156. if type == 'text':
  1157. coords = self.instruction[id]['coords']# recalculate coordinates, they are not equal to BB
  1158. self.instruction[id]['coords'] = coords = [(int(coord) - view[i]) * zoomFactor
  1159. for i, coord in enumerate(coords)]
  1160. self.DrawRotText(pdc = self.pdcObj, drawId = id, textDict = self.instruction[id],
  1161. coords = coords, bounds = oRect )
  1162. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1163. if self.instruction[id]['rotate']:
  1164. rot = float(self.instruction[id]['rotate'])
  1165. else:
  1166. rot = 0
  1167. self.instruction[id]['rect'] = bounds = self.parent.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  1168. self.pdcObj.SetIdBounds(id, bounds)
  1169. else:
  1170. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1171. drawid = id, pdctype = 'rectText', bb = oRect)
  1172. #redraw tmp objects
  1173. if self.dragId != -1:
  1174. self.RedrawSelectBox(self.dragId)
  1175. #redraw preview
  1176. else: # preview mode
  1177. imageRect = self.pdcImage.GetIdBounds(self.imageId)
  1178. imageRect.OffsetXY(-view[0], -view[1])
  1179. imageRect = self.ScaleRect(rect = imageRect, scale = zoomFactor)
  1180. self.DrawImage(imageRect)
  1181. def ZoomAll(self):
  1182. """! Zoom to full extent"""
  1183. if not self.preview:
  1184. bounds = self.pdcPaper.GetIdBounds(self.pageId)
  1185. else:
  1186. bounds = self.pdcImage.GetIdBounds(self.imageId)
  1187. zoomP = bounds.Inflate(bounds.width/20, bounds.height/20)
  1188. zoomFactor, view = self.ComputeZoom(zoomP)
  1189. self.Zoom(zoomFactor, view)
  1190. def Draw(self, pen, brush, pdc, drawid = None, pdctype = 'rect', bb = wx.Rect(0,0,0,0)):
  1191. """! Draw object"""
  1192. if drawid is None:
  1193. drawid = wx.NewId()
  1194. bb = bb.Get()
  1195. pdc.BeginDrawing()
  1196. pdc.RemoveId(drawid)
  1197. pdc.SetId(drawid)
  1198. pdc.SetPen(pen)
  1199. pdc.SetBrush(brush)
  1200. if pdctype in ('rect', 'rectText'):
  1201. pdc.DrawRectangle(*bb)
  1202. if pdctype == 'rectText':
  1203. dc = wx.PaintDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  1204. font = self.font
  1205. size = 10
  1206. font.SetPointSize(size)
  1207. font.SetStyle(wx.ITALIC)
  1208. dc.SetFont(font)
  1209. pdc.SetFont(font)
  1210. text = '\n'.join(self.itemLabels[self.instruction[drawid].type])
  1211. textExtent = dc.GetTextExtent(text)
  1212. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1213. r = map(int, bb)
  1214. while not wx.Rect(*r).ContainsRect(textRect) and size >= 8:
  1215. size -= 2
  1216. font.SetPointSize(size)
  1217. dc.SetFont(font)
  1218. pdc.SetFont(font)
  1219. textExtent = dc.GetTextExtent(text)
  1220. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1221. pdc.SetTextForeground(wx.Color(100,100,100,200))
  1222. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1223. pdc.DrawText(text = text, x = textRect.x, y = textRect.y)
  1224. pdc.SetIdBounds(drawid, bb)
  1225. pdc.EndDrawing()
  1226. self.Refresh()
  1227. return drawid
  1228. def DrawRotText(self, pdc, drawId, textDict, coords, bounds):
  1229. if textDict['rotate']:
  1230. rot = float(textDict['rotate'])
  1231. else:
  1232. rot = 0
  1233. fontsize = str(textDict['fontsize'] * self.currScale)
  1234. if textDict['background'] != 'none':
  1235. background = textDict['background']
  1236. else:
  1237. background = None
  1238. pdc.RemoveId(drawId)
  1239. pdc.SetId(drawId)
  1240. pdc.BeginDrawing()
  1241. # doesn't work
  1242. if background:
  1243. pdc.SetBackground(wx.Brush(convertRGB(background)))
  1244. pdc.SetBackgroundMode(wx.SOLID)
  1245. else:
  1246. pdc.SetBackground(wx.TRANSPARENT_BRUSH)
  1247. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1248. pdc.SetFont(wx.FontFromNativeInfoString(textDict['font'] + " " + fontsize))
  1249. pdc.SetTextForeground(convertRGB(textDict['color']))
  1250. pdc.DrawRotatedText(textDict['text'], coords[0], coords[1], rot)
  1251. pdc.SetIdBounds(drawId, wx.Rect(*bounds))
  1252. self.Refresh()
  1253. pdc.EndDrawing()
  1254. def DrawImage(self, rect):
  1255. """!Draw preview image to pseudoDC"""
  1256. self.pdcImage.ClearId(self.imageId)
  1257. self.pdcImage.SetId(self.imageId)
  1258. img = self.image
  1259. if img.GetWidth() != rect.width or img.GetHeight() != rect.height:
  1260. img = img.Scale(rect.width, rect.height)
  1261. bitmap = img.ConvertToBitmap()
  1262. self.pdcImage.BeginDrawing()
  1263. self.pdcImage.DrawBitmap(bitmap, rect.x, rect.y)
  1264. self.pdcImage.SetIdBounds(self.imageId, rect)
  1265. self.pdcImage.EndDrawing()
  1266. self.Refresh()
  1267. def DrawPaper(self, rect):
  1268. """!Draw paper and margins"""
  1269. page = self.instruction[self.pageId]
  1270. scale = page['Width'] / rect.GetWidth()
  1271. w = (page['Width'] - page['Right'] - page['Left']) / scale
  1272. h = (page['Height'] - page['Top'] - page['Bottom']) / scale
  1273. x = page['Left'] / scale + rect.GetX()
  1274. y = page['Top'] / scale + rect.GetY()
  1275. self.pdcPaper.BeginDrawing()
  1276. self.pdcPaper.RemoveId(self.pageId)
  1277. self.pdcPaper.SetId(self.pageId)
  1278. self.pdcPaper.SetPen(self.pen['paper'])
  1279. self.pdcPaper.SetBrush(self.brush['paper'])
  1280. self.pdcPaper.DrawRectangleRect(rect)
  1281. self.pdcPaper.SetPen(self.pen['margins'])
  1282. self.pdcPaper.SetBrush(self.brush['margins'])
  1283. self.pdcPaper.DrawRectangle(x, y, w, h)
  1284. self.pdcPaper.SetIdBounds(self.pageId, rect)
  1285. self.pdcPaper.EndDrawing()
  1286. self.Refresh()
  1287. def ImageRect(self):
  1288. """!Returns image centered in canvas, computes scale"""
  1289. img = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  1290. cW, cH = self.GetClientSize()
  1291. iW, iH = img.GetWidth(), img.GetHeight()
  1292. self.currScale = min(float(cW)/iW, float(cH)/iH)
  1293. iW = iW * self.currScale
  1294. iH = iH * self.currScale
  1295. x = cW/2 - iW/2
  1296. y = cH/2 - iH/2
  1297. imageRect = wx.Rect(x, y, iW, iH)
  1298. return imageRect
  1299. def RedrawSelectBox(self, id):
  1300. """!Redraws select box when selected object changes its size"""
  1301. if self.dragId == id:
  1302. rect = [self.pdcObj.GetIdBounds(id).Inflate(3,3)]
  1303. type = ['select']
  1304. ids = [self.idBoxTmp]
  1305. if self.instruction[id].type == 'map':
  1306. controlP = self.pdcObj.GetIdBounds(id).GetBottomRight()
  1307. rect.append(wx.Rect(controlP.x, controlP.y, 10,10))
  1308. type.append('resize')
  1309. ids.append(self.idResizeBoxTmp)
  1310. for id, type, rect in zip(ids, type, rect):
  1311. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcTmp,
  1312. drawid = id, pdctype = 'rect', bb = rect)
  1313. def UpdateMapLabel(self):
  1314. """!Updates map frame label"""
  1315. vector = self.instruction.FindInstructionByType('vector')
  1316. if vector:
  1317. vectorId = vector.id
  1318. else:
  1319. vectorId = None
  1320. raster = self.instruction.FindInstructionByType('raster')
  1321. if raster:
  1322. rasterId = raster.id
  1323. else:
  1324. rasterId = None
  1325. rasterName = 'None'
  1326. if rasterId:
  1327. rasterName = self.instruction[rasterId]['raster'].split('@')[0]
  1328. self.itemLabels['map'] = self.itemLabels['map'][0:1]
  1329. self.itemLabels['map'].append("raster: " + rasterName)
  1330. if vectorId:
  1331. for map in self.instruction[vectorId]['list']:
  1332. self.itemLabels['map'].append('vector: ' + map[0].split('@')[0])
  1333. def OnSize(self, event):
  1334. """!Init image size to match window size
  1335. """
  1336. # not zoom all when notebook page is changed
  1337. if self.preview and self.parent.currentPage == 1 or not self.preview and self.parent.currentPage == 0:
  1338. self.ZoomAll()
  1339. self.OnIdle(None)
  1340. event.Skip()
  1341. def OnIdle(self, event):
  1342. """!Only re-render a image during idle time instead of
  1343. multiple times during resizing.
  1344. """
  1345. width, height = self.GetClientSize()
  1346. # Make new off screen bitmap: this bitmap will always have the
  1347. # current drawing in it, so it can be used to save the image
  1348. # to a file, or whatever.
  1349. self._buffer = wx.EmptyBitmap(width, height)
  1350. # re-render image on idle
  1351. self.resize = True
  1352. def ScaleRect(self, rect, scale):
  1353. """! Scale rectangle"""
  1354. return wx.Rect(rect.GetLeft()*scale, rect.GetTop()*scale,
  1355. rect.GetSize()[0]*scale, rect.GetSize()[1]*scale)
  1356. def main():
  1357. app = wx.PySimpleApp()
  1358. wx.InitAllImageHandlers()
  1359. frame = PsMapFrame()
  1360. frame.Show()
  1361. app.MainLoop()
  1362. if __name__ == "__main__":
  1363. main()