frame.py 91 KB

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