frame.py 93 KB

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