frame.py 91 KB

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