frame.py 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236
  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.Colour(86, 122, 17), width = 2),
  76. 'rasterLegend': wx.Pen(colour = wx.Colour(219, 216, 4), width = 2),
  77. 'vectorLegend': wx.Pen(colour = wx.Colour(219, 216, 4), width = 2),
  78. 'mapinfo': wx.Pen(colour = wx.Colour(5, 184, 249), width = 2),
  79. 'scalebar': wx.Pen(colour = wx.Colour(150, 150, 150), width = 2),
  80. 'image': wx.Pen(colour = wx.Colour(255, 150, 50), width = 2),
  81. 'northArrow': wx.Pen(colour = wx.Colour(200, 200, 200), width = 2),
  82. 'point': wx.Pen(colour = wx.Colour(100, 100, 100), width = 2),
  83. 'line': wx.Pen(colour = wx.Colour(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.Colour(151, 214, 90)),
  92. 'rasterLegend': wx.Brush(wx.Colour(250, 247, 112)),
  93. 'vectorLegend': wx.Brush(wx.Colour(250, 247, 112)),
  94. 'mapinfo': wx.Brush(wx.Colour(127, 222, 252)),
  95. 'scalebar': wx.Brush(wx.Colour(200, 200, 200)),
  96. 'image': wx.Brush(wx.Colour(255, 200, 50)),
  97. 'northArrow': wx.Brush(wx.Colour(255, 255, 255)),
  98. 'point': wx.Brush(wx.Colour(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. import types
  265. im.load = types.MethodType(loadPSForWindows, im)
  266. im.save(self.imgName, format = 'PNG')
  267. except IOError, e:
  268. GError(parent = self,
  269. message = _("Unable to generate preview. %s") % e)
  270. del busy
  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. del busy
  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. """!Launch file dialog and load selected file"""
  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. self.LoadFile(filename)
  331. def LoadFile(self, filename):
  332. """!Load file and read instructions"""
  333. readObjectId = []
  334. readInstruction = Instruction(parent = self, objectsToDraw = readObjectId)
  335. ok = readInstruction.Read(filename)
  336. if not ok:
  337. GMessage(_("Failed to read file %s.") % filename)
  338. else:
  339. self.instruction = self.canvas.instruction = readInstruction
  340. self.objectId = self.canvas.objectId = readObjectId
  341. self.pageId = self.canvas.pageId = self.instruction.FindInstructionByType('page').id
  342. self.canvas.UpdateMapLabel()
  343. self.canvas.dragId = -1
  344. self.canvas.Clear()
  345. self.canvas.SetPage()
  346. #self.canvas.ZoomAll()
  347. self.DialogDataChanged(self.objectId)
  348. def OnPageSetup(self, event = None):
  349. """!Specify paper size, margins and orientation"""
  350. id = self.instruction.FindInstructionByType('page').id
  351. dlg = PageSetupDialog(self, id = id, settings = self.instruction)
  352. dlg.CenterOnScreen()
  353. val = dlg.ShowModal()
  354. if val == wx.ID_OK:
  355. self.canvas.SetPage()
  356. self.getInitMap()
  357. self.canvas.RecalculatePosition(ids = self.objectId)
  358. dlg.Destroy()
  359. def OnPointer(self, event):
  360. self.toolbar.OnTool(event)
  361. self.mouse["use"] = "pointer"
  362. self.canvas.SetCursor(self.cursors["default"])
  363. self.previewCanvas.SetCursor(self.cursors["default"])
  364. def OnPan(self, event):
  365. self.toolbar.OnTool(event)
  366. self.mouse["use"] = "pan"
  367. self.canvas.SetCursor(self.cursors["hand"])
  368. self.previewCanvas.SetCursor(self.cursors["hand"])
  369. def OnZoomIn(self, event):
  370. self.toolbar.OnTool(event)
  371. self.mouse["use"] = "zoomin"
  372. self.canvas.SetCursor(self.cursors["cross"])
  373. self.previewCanvas.SetCursor(self.cursors["cross"])
  374. def OnZoomOut(self, event):
  375. self.toolbar.OnTool(event)
  376. self.mouse["use"] = "zoomout"
  377. self.canvas.SetCursor(self.cursors["cross"])
  378. self.previewCanvas.SetCursor(self.cursors["cross"])
  379. def OnZoomAll(self, event):
  380. self.mouseOld = self.mouse['use']
  381. if self.currentPage == 0:
  382. self.cursorOld = self.canvas.GetCursor()
  383. else:
  384. self.cursorOld = self.previewCanvas.GetCursor()
  385. self.previewCanvas.GetCursor()
  386. self.mouse["use"] = "zoomin"
  387. if self.currentPage == 0:
  388. self.canvas.ZoomAll()
  389. else:
  390. self.previewCanvas.ZoomAll()
  391. self.mouse["use"] = self.mouseOld
  392. if self.currentPage == 0:
  393. self.canvas.SetCursor(self.cursorOld)
  394. else:
  395. self.previewCanvas.SetCursor(self.cursorOld)
  396. def OnAddMap(self, event, notebook = False):
  397. """!Add or edit map frame"""
  398. if event is not None:
  399. if event.GetId() != self.toolbar.action['id']:
  400. self.actionOld = self.toolbar.action['id']
  401. self.mouseOld = self.mouse['use']
  402. self.cursorOld = self.canvas.GetCursor()
  403. self.toolbar.OnTool(event)
  404. if self.instruction.FindInstructionByType('map'):
  405. mapId = self.instruction.FindInstructionByType('map').id
  406. else: mapId = None
  407. id = [mapId, None, None]
  408. if notebook:
  409. if self.instruction.FindInstructionByType('vector'):
  410. vectorId = self.instruction.FindInstructionByType('vector').id
  411. else: vectorId = None
  412. if self.instruction.FindInstructionByType('raster'):
  413. rasterId = self.instruction.FindInstructionByType('raster').id
  414. else: rasterId = None
  415. id[1] = rasterId
  416. id[2] = vectorId
  417. if mapId: # map exists
  418. self.toolbar.ToggleTool(self.actionOld, True)
  419. self.toolbar.ToggleTool(self.toolbar.action['id'], False)
  420. self.toolbar.action['id'] = self.actionOld
  421. try:
  422. self.canvas.SetCursor(self.cursorOld)
  423. except AttributeError:
  424. pass
  425. ## dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  426. ## notebook = notebook)
  427. ## dlg.ShowModal()
  428. if notebook:
  429. #check map, raster, vector and save, destroy them
  430. if 'map' in self.openDialogs:
  431. self.openDialogs['map'].OnOK(event = None)
  432. if 'raster' in self.openDialogs:
  433. self.openDialogs['raster'].OnOK(event = None)
  434. if 'vector' in self.openDialogs:
  435. self.openDialogs['vector'].OnOK(event = None)
  436. if 'mapNotebook' not in self.openDialogs:
  437. dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  438. notebook = notebook)
  439. self.openDialogs['mapNotebook'] = dlg
  440. self.openDialogs['mapNotebook'].Show()
  441. else:
  442. if 'mapNotebook' in self.openDialogs:
  443. self.openDialogs['mapNotebook'].notebook.ChangeSelection(0)
  444. else:
  445. if 'map' not in self.openDialogs:
  446. dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  447. notebook = notebook)
  448. self.openDialogs['map'] = dlg
  449. self.openDialogs['map'].Show()
  450. else: # sofar no map
  451. self.mouse["use"] = "addMap"
  452. self.canvas.SetCursor(self.cursors["cross"])
  453. if self.currentPage == 1:
  454. self.book.SetSelection(0)
  455. self.currentPage = 0
  456. def OnAddRaster(self, event):
  457. """!Add raster map"""
  458. if self.instruction.FindInstructionByType('raster'):
  459. id = self.instruction.FindInstructionByType('raster').id
  460. else: id = None
  461. if self.instruction.FindInstructionByType('map'):
  462. mapId = self.instruction.FindInstructionByType('map').id
  463. else: mapId = None
  464. if not id:
  465. if not mapId:
  466. GMessage(message = _("Please, create map frame first."))
  467. return
  468. ## dlg = RasterDialog(self, id = id, settings = self.instruction)
  469. ## dlg.ShowModal()
  470. if 'mapNotebook' in self.openDialogs:
  471. self.openDialogs['mapNotebook'].notebook.ChangeSelection(1)
  472. else:
  473. if 'raster' not in self.openDialogs:
  474. dlg = RasterDialog(self, id = id, settings = self.instruction)
  475. self.openDialogs['raster'] = dlg
  476. self.openDialogs['raster'].Show()
  477. def OnAddVect(self, event):
  478. """!Add vector map"""
  479. if self.instruction.FindInstructionByType('vector'):
  480. id = self.instruction.FindInstructionByType('vector').id
  481. else: id = None
  482. if self.instruction.FindInstructionByType('map'):
  483. mapId = self.instruction.FindInstructionByType('map').id
  484. else: mapId = None
  485. if not id:
  486. if not mapId:
  487. GMessage(message = _("Please, create map frame first."))
  488. return
  489. ## dlg = MainVectorDialog(self, id = id, settings = self.instruction)
  490. ## dlg.ShowModal()
  491. if 'mapNotebook' in self.openDialogs:
  492. self.openDialogs['mapNotebook'].notebook.ChangeSelection(2)
  493. else:
  494. if 'vector' not in self.openDialogs:
  495. dlg = MainVectorDialog(self, id = id, settings = self.instruction)
  496. self.openDialogs['vector'] = dlg
  497. self.openDialogs['vector'].Show()
  498. def OnAddScalebar(self, event):
  499. """!Add scalebar"""
  500. if projInfo()['proj'] == 'll':
  501. GMessage(message = _("Scalebar is not appropriate for this projection"))
  502. return
  503. if self.instruction.FindInstructionByType('scalebar'):
  504. id = self.instruction.FindInstructionByType('scalebar').id
  505. else: id = None
  506. if 'scalebar' not in self.openDialogs:
  507. dlg = ScalebarDialog(self, id = id, settings = self.instruction)
  508. self.openDialogs['scalebar'] = dlg
  509. self.openDialogs['scalebar'].Show()
  510. def OnAddLegend(self, event, page = 0):
  511. """!Add raster or vector legend"""
  512. if self.instruction.FindInstructionByType('rasterLegend'):
  513. idR = self.instruction.FindInstructionByType('rasterLegend').id
  514. else: idR = None
  515. if self.instruction.FindInstructionByType('vectorLegend'):
  516. idV = self.instruction.FindInstructionByType('vectorLegend').id
  517. else: idV = None
  518. if 'rasterLegend' not in self.openDialogs:
  519. dlg = LegendDialog(self, id = [idR, idV], settings = self.instruction, page = page)
  520. self.openDialogs['rasterLegend'] = dlg
  521. self.openDialogs['vectorLegend'] = dlg
  522. self.openDialogs['rasterLegend'].notebook.ChangeSelection(page)
  523. self.openDialogs['rasterLegend'].Show()
  524. def OnAddMapinfo(self, event):
  525. if self.instruction.FindInstructionByType('mapinfo'):
  526. id = self.instruction.FindInstructionByType('mapinfo').id
  527. else: id = None
  528. if 'mapinfo' not in self.openDialogs:
  529. dlg = MapinfoDialog(self, id = id, settings = self.instruction)
  530. self.openDialogs['mapinfo'] = dlg
  531. self.openDialogs['mapinfo'].Show()
  532. def OnAddImage(self, event, id = None):
  533. """!Show dialog for image adding and editing"""
  534. position = None
  535. if 'image' in self.openDialogs:
  536. position = self.openDialogs['image'].GetPosition()
  537. self.openDialogs['image'].OnApply(event = None)
  538. self.openDialogs['image'].Destroy()
  539. dlg = ImageDialog(self, id = id, settings = self.instruction)
  540. self.openDialogs['image'] = dlg
  541. if position:
  542. dlg.SetPosition(position)
  543. dlg.Show()
  544. def OnAddNorthArrow(self, event, id = None):
  545. """!Show dialog for north arrow adding and editing"""
  546. if self.instruction.FindInstructionByType('northArrow'):
  547. id = self.instruction.FindInstructionByType('northArrow').id
  548. else: id = None
  549. if 'northArrow' not in self.openDialogs:
  550. dlg = NorthArrowDialog(self, id = id, settings = self.instruction)
  551. self.openDialogs['northArrow'] = dlg
  552. self.openDialogs['northArrow'].Show()
  553. def OnAddText(self, event, id = None):
  554. """!Show dialog for text adding and editing"""
  555. position = None
  556. if 'text' in self.openDialogs:
  557. position = self.openDialogs['text'].GetPosition()
  558. self.openDialogs['text'].OnApply(event = None)
  559. self.openDialogs['text'].Destroy()
  560. dlg = TextDialog(self, id = id, settings = self.instruction)
  561. self.openDialogs['text'] = dlg
  562. if position:
  563. dlg.SetPosition(position)
  564. dlg.Show()
  565. def OnAddPoint(self, event):
  566. """!Add point action selected"""
  567. self.mouse["use"] = "addPoint"
  568. self.canvas.SetCursor(self.cursors["cross"])
  569. def AddPoint(self, id = None, coordinates = None):
  570. """!Add point and open property dialog.
  571. @param id id point id (None if creating new point)
  572. @param coordinates coordinates of new point
  573. """
  574. position = None
  575. if 'point' in self.openDialogs:
  576. position = self.openDialogs['point'].GetPosition()
  577. self.openDialogs['point'].OnApply(event = None)
  578. self.openDialogs['point'].Destroy()
  579. dlg = PointDialog(self, id = id, settings = self.instruction,
  580. coordinates = coordinates)
  581. self.openDialogs['point'] = dlg
  582. if position:
  583. dlg.SetPosition(position)
  584. if coordinates:
  585. dlg.OnApply(event = None)
  586. dlg.Show()
  587. def OnAddLine(self, event):
  588. """!Add line action selected"""
  589. self.mouse["use"] = "addLine"
  590. self.canvas.SetCursor(self.cursors["cross"])
  591. def AddLine(self, id = None, coordinates = None):
  592. """!Add line and open property dialog.
  593. @param id id line id (None if creating new line)
  594. @param coordinates coordinates of new line
  595. """
  596. position = None
  597. if 'line' in self.openDialogs:
  598. position = self.openDialogs['line'].GetPosition()
  599. self.openDialogs['line'].OnApply(event = None)
  600. self.openDialogs['line'].Destroy()
  601. dlg = RectangleDialog(self, id = id, settings = self.instruction,
  602. type = 'line', coordinates = coordinates)
  603. self.openDialogs['line'] = dlg
  604. if position:
  605. dlg.SetPosition(position)
  606. if coordinates:
  607. dlg.OnApply(event = None)
  608. dlg.Show()
  609. def OnAddRectangle(self, event):
  610. """!Add rectangle action selected"""
  611. self.mouse["use"] = "addRectangle"
  612. self.canvas.SetCursor(self.cursors["cross"])
  613. def AddRectangle(self, id = None, coordinates = None):
  614. """!Add rectangle and open property dialog.
  615. @param id id rectangle id (None if creating new rectangle)
  616. @param coordinates coordinates of new rectangle
  617. """
  618. position = None
  619. if 'rectangle' in self.openDialogs:
  620. position = self.openDialogs['rectangle'].GetPosition()
  621. self.openDialogs['rectangle'].OnApply(event = None)
  622. self.openDialogs['rectangle'].Destroy()
  623. dlg = RectangleDialog(self, id = id, settings = self.instruction,
  624. type = 'rectangle', coordinates = coordinates)
  625. self.openDialogs['rectangle'] = dlg
  626. if position:
  627. dlg.SetPosition(position)
  628. if coordinates:
  629. dlg.OnApply(event = None)
  630. dlg.Show()
  631. def getModifiedTextBounds(self, x, y, textExtent, rotation):
  632. """!computes bounding box of rotated text, not very precisely"""
  633. w, h = textExtent
  634. rotation = float(rotation)/180*pi
  635. H = float(w) * sin(rotation)
  636. W = float(w) * cos(rotation)
  637. X, Y = x, y
  638. if pi/2 < rotation <= 3*pi/2:
  639. X = x + W
  640. if 0 < rotation < pi:
  641. Y = y - H
  642. if rotation == 0:
  643. return wx.Rect(x,y, *textExtent)
  644. else:
  645. return wx.Rect(X, Y, abs(W), abs(H)).Inflate(h,h)
  646. def makePSFont(self, textDict):
  647. """!creates a wx.Font object from selected postscript font. To be
  648. used for estimating bounding rectangle of text"""
  649. fontsize = textDict['fontsize'] * self.canvas.currScale
  650. fontface = textDict['font'].split('-')[0]
  651. try:
  652. fontstyle = textDict['font'].split('-')[1]
  653. except IndexError:
  654. fontstyle = ''
  655. if fontface == "Times":
  656. family = wx.FONTFAMILY_ROMAN
  657. face = "times"
  658. elif fontface == "Helvetica":
  659. family = wx.FONTFAMILY_SWISS
  660. face = 'helvetica'
  661. elif fontface == "Courier":
  662. family = wx.FONTFAMILY_TELETYPE
  663. face = 'courier'
  664. else:
  665. family = wx.FONTFAMILY_DEFAULT
  666. face = ''
  667. style = wx.FONTSTYLE_NORMAL
  668. weight = wx.FONTWEIGHT_NORMAL
  669. if 'Oblique' in fontstyle:
  670. style = wx.FONTSTYLE_SLANT
  671. if 'Italic' in fontstyle:
  672. style = wx.FONTSTYLE_ITALIC
  673. if 'Bold' in fontstyle:
  674. weight = wx.FONTWEIGHT_BOLD
  675. try:
  676. fn = wx.Font(pointSize = fontsize, family = family, style = style,
  677. weight = weight, face = face)
  678. except:
  679. fn = wx.Font(pointSize = fontsize, family = wx.FONTFAMILY_DEFAULT,
  680. style = wx.FONTSTYLE_NORMAL, weight = wx.FONTWEIGHT_NORMAL)
  681. return fn
  682. def getTextExtent(self, textDict):
  683. """!Estimates bounding rectangle of text"""
  684. #fontsize = str(fontsize if fontsize >= 4 else 4)
  685. dc = wx.ClientDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  686. fn = self.makePSFont(textDict)
  687. try:
  688. dc.SetFont(fn)
  689. w,h,lh = dc.GetMultiLineTextExtent(textDict['text'])
  690. return (w,h)
  691. except:
  692. return (0,0)
  693. def getInitMap(self):
  694. """!Create default map frame when no map is selected, needed for coordinates in map units"""
  695. instrFile = grass.tempfile()
  696. instrFileFd = open(instrFile, mode = 'w')
  697. instrFileFd.write(self.InstructionFile())
  698. instrFileFd.flush()
  699. instrFileFd.close()
  700. page = self.instruction.FindInstructionByType('page')
  701. mapInitRect = GetMapBounds(instrFile, portrait = (page['Orientation'] == 'Portrait'))
  702. grass.try_remove(instrFile)
  703. region = grass.region()
  704. units = UnitConversion(self)
  705. realWidth = units.convert(value = abs(region['w'] - region['e']), fromUnit = 'meter', toUnit = 'inch')
  706. scale = mapInitRect.Get()[2]/realWidth
  707. initMap = self.instruction.FindInstructionByType('initMap')
  708. if initMap:
  709. id = initMap.id
  710. else:
  711. id = None
  712. if not id:
  713. id = wx.NewId()
  714. initMap = InitMap(id)
  715. self.instruction.AddInstruction(initMap)
  716. self.instruction[id].SetInstruction(dict(rect = mapInitRect, scale = scale))
  717. def OnDelete(self, event):
  718. if self.canvas.dragId != -1 and self.currentPage == 0:
  719. if self.instruction[self.canvas.dragId].type == 'map':
  720. self.deleteObject(self.canvas.dragId)
  721. self.getInitMap()
  722. self.canvas.RecalculateEN()
  723. else:
  724. self.deleteObject(self.canvas.dragId)
  725. def deleteObject(self, id):
  726. """!Deletes object, his id and redraws"""
  727. #delete from canvas
  728. self.canvas.pdcObj.RemoveId(id)
  729. if id == self.canvas.dragId:
  730. self.canvas.pdcTmp.RemoveAll()
  731. self.canvas.dragId = -1
  732. self.canvas.Refresh()
  733. # delete from instructions
  734. del self.instruction[id]
  735. def DialogDataChanged(self, id):
  736. ids = id
  737. if type(id) == int:
  738. ids = [id]
  739. for id in ids:
  740. itype = self.instruction[id].type
  741. if itype in ('scalebar', 'mapinfo', 'image'):
  742. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  743. self.canvas.UpdateLabel(itype = itype, id = id)
  744. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  745. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  746. self.canvas.RedrawSelectBox(id)
  747. if itype == 'northArrow':
  748. self.canvas.UpdateLabel(itype = itype, id = id)
  749. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  750. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  751. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'bitmap', bb = drawRectangle)
  752. self.canvas.RedrawSelectBox(id)
  753. if itype in ('point', 'line', 'rectangle'):
  754. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  755. # coords only for line
  756. coords = None
  757. if itype == 'line':
  758. point1 = self.instruction[id]['where'][0]
  759. point2 = self.instruction[id]['where'][1]
  760. point1Coords = self.canvas.CanvasPaperCoordinates(rect = Rect2DPS(point1, (0, 0)), canvasToPaper = False)[:2]
  761. point2Coords = self.canvas.CanvasPaperCoordinates(rect = Rect2DPS(point2, (0, 0)), canvasToPaper = False)[:2]
  762. coords = (point1Coords, point2Coords)
  763. # fill color is not in line
  764. fcolor = None
  765. if 'fcolor' in self.instruction[id].GetInstruction():
  766. fcolor = self.instruction[id]['fcolor']
  767. # width is not in point
  768. width = None
  769. if 'width' in self.instruction[id].GetInstruction():
  770. width = self.instruction[id]['width']
  771. self.canvas.DrawGraphics(drawid = id, color = self.instruction[id]['color'], shape = itype,
  772. fcolor = fcolor, width = width, bb = drawRectangle, lineCoords = coords)
  773. self.canvas.RedrawSelectBox(id)
  774. if itype == 'text':
  775. if self.instruction[id]['rotate']:
  776. rot = float(self.instruction[id]['rotate'])
  777. else:
  778. rot = 0
  779. extent = self.getTextExtent(textDict = self.instruction[id].GetInstruction())
  780. rect = Rect2DPS(self.instruction[id]['where'], (0, 0))
  781. self.instruction[id]['coords'] = list(self.canvas.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)[:2])
  782. #computes text coordinates according to reference point, not precisely
  783. if self.instruction[id]['ref'].split()[0] == 'lower':
  784. self.instruction[id]['coords'][1] -= extent[1]
  785. elif self.instruction[id]['ref'].split()[0] == 'center':
  786. self.instruction[id]['coords'][1] -= extent[1]/2
  787. if self.instruction[id]['ref'].split()[1] == 'right':
  788. self.instruction[id]['coords'][0] -= extent[0] * cos(rot/180*pi)
  789. self.instruction[id]['coords'][1] += extent[0] * sin(rot/180*pi)
  790. elif self.instruction[id]['ref'].split()[1] == 'center':
  791. self.instruction[id]['coords'][0] -= extent[0]/2 * cos(rot/180*pi)
  792. self.instruction[id]['coords'][1] += extent[0]/2 * sin(rot/180*pi)
  793. self.instruction[id]['coords'][0] += self.instruction[id]['xoffset']
  794. self.instruction[id]['coords'][1] -= self.instruction[id]['yoffset']
  795. coords = self.instruction[id]['coords']
  796. self.instruction[id]['rect'] = bounds = self.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  797. self.canvas.DrawRotText(pdc = self.canvas.pdcObj, drawId = id,
  798. textDict = self.instruction[id].GetInstruction(),
  799. coords = coords, bounds = bounds)
  800. self.canvas.RedrawSelectBox(id)
  801. if itype in ('map', 'vector', 'raster'):
  802. if itype == 'raster':#set resolution
  803. info = grass.raster_info(self.instruction[id]['raster'])
  804. RunCommand('g.region', nsres = info['nsres'], ewres = info['ewres'])
  805. # change current raster in raster legend
  806. if 'rasterLegend' in self.openDialogs:
  807. self.openDialogs['rasterLegend'].updateDialog()
  808. id = self.instruction.FindInstructionByType('map').id
  809. #check resolution
  810. if itype == 'raster':
  811. SetResolution(dpi = self.instruction[id]['resolution'],
  812. width = self.instruction[id]['rect'].width,
  813. height = self.instruction[id]['rect'].height)
  814. rectCanvas = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'],
  815. canvasToPaper = False)
  816. self.canvas.RecalculateEN()
  817. self.canvas.UpdateMapLabel()
  818. self.canvas.Draw(pen = self.pen['map'], brush = self.brush['map'],
  819. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = rectCanvas)
  820. # redraw select box
  821. self.canvas.RedrawSelectBox(id)
  822. self.canvas.pdcTmp.RemoveId(self.canvas.idZoomBoxTmp)
  823. # redraw to get map to the bottom layer
  824. #self.canvas.Zoom(zoomFactor = 1, view = (0, 0))
  825. if itype == 'rasterLegend':
  826. if self.instruction[id]['rLegend']:
  827. self.canvas.UpdateLabel(itype = itype, id = id)
  828. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  829. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  830. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  831. self.canvas.RedrawSelectBox(id)
  832. else:
  833. self.deleteObject(id)
  834. if itype == 'vectorLegend':
  835. if not self.instruction.FindInstructionByType('vector'):
  836. self.deleteObject(id)
  837. elif self.instruction[id]['vLegend']:
  838. self.canvas.UpdateLabel(itype = itype, id = id)
  839. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  840. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  841. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  842. self.canvas.RedrawSelectBox(id)
  843. else:
  844. self.deleteObject(id)
  845. def OnPageChanged(self, event):
  846. """!Flatnotebook page has changed"""
  847. self.currentPage = self.book.GetPageIndex(self.book.GetCurrentPage())
  848. if self.currentPage == 1:
  849. self.SetStatusText(_("Press button with green triangle icon to generate preview."))
  850. else:
  851. self.SetStatusText('')
  852. def OnPageChanging(self, event):
  853. """!Flatnotebook page is changing"""
  854. if self.currentPage == 0 and self.mouse['use'] == 'addMap':
  855. event.Veto()
  856. def OnHelp(self, event):
  857. """!Show help"""
  858. if self.parent and self.parent.GetName() == 'LayerManager':
  859. log = self.parent.GetLogWindow()
  860. log.RunCmd(['g.manual',
  861. 'entry=wxGUI.psmap'])
  862. else:
  863. RunCommand('g.manual',
  864. quiet = True,
  865. entry = 'wxGUI.psmap')
  866. def OnAbout(self, event):
  867. """!Display About window"""
  868. info = wx.AboutDialogInfo()
  869. info.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  870. info.SetName(_('wxGUI Cartographic Composer'))
  871. info.SetWebSite('http://grass.osgeo.org')
  872. info.SetDescription(_('(C) 2011 by the GRASS Development Team\n\n') +
  873. '\n'.join(textwrap.wrap(_('This program is free software under the GNU General Public License'
  874. '(>=v2). Read the file COPYING that comes with GRASS for details.'), 75)))
  875. wx.AboutBox(info)
  876. def OnCloseWindow(self, event):
  877. """!Close window"""
  878. try:
  879. os.remove(self.imgName)
  880. except OSError:
  881. pass
  882. grass.set_raise_on_error(False)
  883. self.Destroy()
  884. class PsMapBufferedWindow(wx.Window):
  885. """!A buffered window class.
  886. @param parent parent window
  887. @param kwargs other wx.Window parameters
  888. """
  889. def __init__(self, parent, id = wx.ID_ANY,
  890. style = wx.NO_FULL_REPAINT_ON_RESIZE,
  891. **kwargs):
  892. wx.Window.__init__(self, parent, id = id, style = style)
  893. self.parent = parent
  894. self.FitInside()
  895. # store an off screen empty bitmap for saving to file
  896. self._buffer = None
  897. # indicates whether or not a resize event has taken place
  898. self.resize = False
  899. self.mouse = kwargs['mouse']
  900. self.cursors = kwargs['cursors']
  901. self.preview = kwargs['preview']
  902. self.pen = kwargs['pen']
  903. self.brush = kwargs['brush']
  904. if kwargs.has_key('instruction'):
  905. self.instruction = kwargs['instruction']
  906. if kwargs.has_key('openDialogs'):
  907. self.openDialogs = kwargs['openDialogs']
  908. if kwargs.has_key('pageId'):
  909. self.pageId = kwargs['pageId']
  910. if kwargs.has_key('objectId'):
  911. self.objectId = kwargs['objectId']
  912. #labels
  913. self.itemLabelsDict = { 'map': 'MAP FRAME',
  914. 'rasterLegend': 'RASTER LEGEND',
  915. 'vectorLegend': 'VECTOR LEGEND',
  916. 'mapinfo': 'MAP INFO',
  917. 'scalebar': 'SCALE BAR',
  918. 'image': 'IMAGE',
  919. 'northArrow': 'NORTH ARROW'}
  920. self.itemLabels = {}
  921. # define PseudoDC
  922. self.pdc = wx.PseudoDC()
  923. self.pdcObj = wx.PseudoDC()
  924. self.pdcPaper = wx.PseudoDC()
  925. self.pdcTmp = wx.PseudoDC()
  926. self.pdcImage = wx.PseudoDC()
  927. dc = wx.ClientDC(self)
  928. self.font = dc.GetFont()
  929. self.SetClientSize((700,510))#?
  930. self._buffer = wx.EmptyBitmap(*self.GetClientSize())
  931. self.idBoxTmp = wx.NewId()
  932. self.idZoomBoxTmp = wx.NewId()
  933. self.idResizeBoxTmp = wx.NewId()
  934. self.idLinePointsTmp = (wx.NewId(), wx.NewId()) # ids of marks for moving line vertices
  935. self.resizeBoxSize = wx.Size(8, 8)
  936. self.dragId = -1
  937. if self.preview:
  938. self.image = None
  939. self.imageId = 2000
  940. self.imgName = self.parent.imgName
  941. self.currScale = None
  942. self.Clear()
  943. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
  944. self.Bind(wx.EVT_PAINT, self.OnPaint)
  945. self.Bind(wx.EVT_SIZE, self.OnSize)
  946. self.Bind(wx.EVT_IDLE, self.OnIdle)
  947. # self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
  948. self.Bind(wx.EVT_MOUSE_EVENTS, self.MouseActions)
  949. def Clear(self):
  950. """!Clear canvas and set paper
  951. """
  952. bg = wx.LIGHT_GREY_BRUSH
  953. self.pdcPaper.BeginDrawing()
  954. self.pdcPaper.SetBackground(bg)
  955. self.pdcPaper.Clear()
  956. self.pdcPaper.EndDrawing()
  957. self.pdcObj.RemoveAll()
  958. self.pdcTmp.RemoveAll()
  959. if not self.preview:
  960. self.SetPage()
  961. def CanvasPaperCoordinates(self, rect, canvasToPaper = True):
  962. """!Converts canvas (pixel) -> paper (inch) coordinates and size and vice versa"""
  963. units = UnitConversion(self)
  964. fromU = 'pixel'
  965. toU = 'inch'
  966. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  967. pRectx, pRecty = pRect.x, pRect.y
  968. scale = 1/self.currScale
  969. if not canvasToPaper: # paper -> canvas
  970. fromU = 'inch'
  971. toU = 'pixel'
  972. scale = self.currScale
  973. pRectx = units.convert(value = - pRect.x, fromUnit = 'pixel', toUnit = 'inch' ) /scale #inch, real, negative
  974. pRecty = units.convert(value = - pRect.y, fromUnit = 'pixel', toUnit = 'inch' ) /scale
  975. Width = units.convert(value = rect.GetWidth(), fromUnit = fromU, toUnit = toU) * scale
  976. Height = units.convert(value = rect.GetHeight(), fromUnit = fromU, toUnit = toU) * scale
  977. X = units.convert(value = (rect.GetX() - pRectx), fromUnit = fromU, toUnit = toU) * scale
  978. Y = units.convert(value = (rect.GetY() - pRecty), fromUnit = fromU, toUnit = toU) * scale
  979. return Rect2D(X, Y, Width, Height)
  980. def SetPage(self):
  981. """!Sets and changes page, redraws paper"""
  982. page = self.instruction[self.pageId]
  983. if not page:
  984. page = PageSetup(id = self.pageId)
  985. self.instruction.AddInstruction(page)
  986. ppi = wx.ClientDC(self).GetPPI()
  987. cW, cH = self.GetClientSize()
  988. pW, pH = page['Width']*ppi[0], page['Height']*ppi[1]
  989. if self.currScale is None:
  990. self.currScale = min(cW/pW, cH/pH)
  991. pW = pW * self.currScale
  992. pH = pH * self.currScale
  993. x = cW/2 - pW/2
  994. y = cH/2 - pH/2
  995. self.DrawPaper(wx.Rect(x, y, pW, pH))
  996. def modifyRectangle(self, r):
  997. """! Recalculates rectangle not to have negative size"""
  998. if r.GetWidth() < 0:
  999. r.SetX(r.GetX() + r.GetWidth())
  1000. if r.GetHeight() < 0:
  1001. r.SetY(r.GetY() + r.GetHeight())
  1002. r.SetWidth(abs(r.GetWidth()))
  1003. r.SetHeight(abs(r.GetHeight()))
  1004. return r
  1005. def RecalculateEN(self):
  1006. """!Recalculate east and north for texts (eps, points) after their or map's movement"""
  1007. try:
  1008. mapId = self.instruction.FindInstructionByType('map').id
  1009. except AttributeError:
  1010. mapId = self.instruction.FindInstructionByType('initMap').id
  1011. for itemType in ('text', 'image', 'northArrow', 'point', 'line', 'rectangle'):
  1012. items = self.instruction.FindInstructionByType(itemType, list = True)
  1013. for item in items:
  1014. instr = self.instruction[item.id]
  1015. if itemType in ('line', 'rectangle'):
  1016. if itemType == 'line':
  1017. e1, n1 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['where'][0][0],
  1018. y = instr['where'][0][1], paperToMap = True)
  1019. e2, n2 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['where'][1][0],
  1020. y = instr['where'][1][1], paperToMap = True)
  1021. else:
  1022. e1, n1 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['rect'].GetLeft(),
  1023. y = instr['rect'].GetTop(), paperToMap = True)
  1024. e2, n2 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['rect'].GetRight(),
  1025. y = instr['rect'].GetBottom(), paperToMap = True)
  1026. instr['east1'] = e1
  1027. instr['north1'] = n1
  1028. instr['east2'] = e2
  1029. instr['north2'] = n2
  1030. else:
  1031. e, n = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['where'][0],
  1032. y = instr['where'][1], paperToMap = True)
  1033. instr['east'], instr['north'] = e, n
  1034. def OnPaint(self, event):
  1035. """!Draw pseudo DC to buffer
  1036. """
  1037. if not self._buffer:
  1038. return
  1039. dc = wx.BufferedPaintDC(self, self._buffer)
  1040. # use PrepareDC to set position correctly
  1041. # probably does nothing, removed from wxPython 2.9
  1042. # self.PrepareDC(dc)
  1043. dc.SetBackground(wx.LIGHT_GREY_BRUSH)
  1044. dc.Clear()
  1045. # draw paper
  1046. if not self.preview:
  1047. self.pdcPaper.DrawToDC(dc)
  1048. # draw to the DC using the calculated clipping rect
  1049. rgn = self.GetUpdateRegion()
  1050. if not self.preview:
  1051. self.pdcObj.DrawToDCClipped(dc, rgn.GetBox())
  1052. else:
  1053. self.pdcImage.DrawToDCClipped(dc, rgn.GetBox())
  1054. self.pdcTmp.DrawToDCClipped(dc, rgn.GetBox())
  1055. def MouseActions(self, event):
  1056. """!Mouse motion and button click notifier
  1057. """
  1058. # zoom with mouse wheel
  1059. if event.GetWheelRotation() != 0:
  1060. self.OnMouseWheel(event)
  1061. # left mouse button pressed
  1062. elif event.LeftDown():
  1063. self.OnLeftDown(event)
  1064. # left mouse button released
  1065. elif event.LeftUp():
  1066. self.OnLeftUp(event)
  1067. # dragging
  1068. elif event.Dragging():
  1069. self.OnDragging(event)
  1070. # double click
  1071. elif event.ButtonDClick():
  1072. self.OnButtonDClick(event)
  1073. # middle mouse button pressed
  1074. elif event.MiddleDown():
  1075. self.OnMiddleDown(event)
  1076. elif event.Moving():
  1077. self.OnMouseMoving(event)
  1078. def OnMouseWheel(self, event):
  1079. """!Mouse wheel scrolled.
  1080. Changes zoom."""
  1081. if UserSettings.Get(group = 'display',
  1082. key = 'mouseWheelZoom',
  1083. subkey = 'selection') == 2:
  1084. event.Skip()
  1085. return
  1086. zoom = event.GetWheelRotation()
  1087. oldUse = self.mouse['use']
  1088. self.mouse['begin'] = event.GetPosition()
  1089. if UserSettings.Get(group = 'display',
  1090. key = 'scrollDirection',
  1091. subkey = 'selection'):
  1092. zoom *= -1
  1093. if zoom > 0:
  1094. self.mouse['use'] = 'zoomin'
  1095. else:
  1096. self.mouse['use'] = 'zoomout'
  1097. zoomFactor, view = self.ComputeZoom(wx.Rect(0, 0, 0, 0))
  1098. self.Zoom(zoomFactor, view)
  1099. self.mouse['use'] = oldUse
  1100. def OnMouseMoving(self, event):
  1101. """!Mouse cursor moving.
  1102. Change cursor when moving over resize marker.
  1103. """
  1104. if self.preview:
  1105. return
  1106. if self.mouse['use'] in ('pointer', 'resize'):
  1107. pos = event.GetPosition()
  1108. foundResize = self.pdcTmp.FindObjects(pos[0], pos[1])
  1109. if foundResize and foundResize[0] in (self.idResizeBoxTmp,) + self.idLinePointsTmp:
  1110. self.SetCursor(self.cursors["sizenwse"])
  1111. self.parent.SetStatusText(_('Click and drag to resize object'), 0)
  1112. else:
  1113. self.parent.SetStatusText('', 0)
  1114. self.SetCursor(self.cursors["default"])
  1115. def OnLeftDown(self, event):
  1116. """!Left mouse button pressed.
  1117. Select objects, redraw, prepare for moving/resizing.
  1118. """
  1119. self.mouse['begin'] = event.GetPosition()
  1120. self.begin = self.mouse['begin']
  1121. # select
  1122. if self.mouse['use'] == 'pointer':
  1123. found = self.pdcObj.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  1124. foundResize = self.pdcTmp.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  1125. if foundResize and foundResize[0] in (self.idResizeBoxTmp,) + self.idLinePointsTmp:
  1126. self.mouse['use'] = 'resize'
  1127. # when resizing, proportions match region
  1128. if self.instruction[self.dragId].type == 'map':
  1129. self.constraint = False
  1130. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1131. if self.instruction[self.dragId]['scaleType'] in (0, 1, 2):
  1132. self.constraint = True
  1133. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1134. if self.instruction[self.dragId].type == 'line':
  1135. self.currentLinePoint = self.idLinePointsTmp.index(foundResize[0])
  1136. elif found:
  1137. self.dragId = found[0]
  1138. self.RedrawSelectBox(self.dragId)
  1139. if self.instruction[self.dragId].type not in ('map', 'rectangle'):
  1140. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1141. self.Refresh()
  1142. if self.instruction[self.dragId].type != 'line':
  1143. for id in self.idLinePointsTmp:
  1144. self.pdcTmp.RemoveId(id)
  1145. self.Refresh()
  1146. else:
  1147. self.dragId = -1
  1148. self.pdcTmp.RemoveId(self.idBoxTmp)
  1149. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1150. for id in self.idLinePointsTmp:
  1151. self.pdcTmp.RemoveId(id)
  1152. self.Refresh()
  1153. def OnLeftUp(self, event):
  1154. """!Left mouse button released.
  1155. Recalculate zooming/resizing/moving and redraw.
  1156. """
  1157. # zoom in, zoom out
  1158. if self.mouse['use'] in ('zoomin','zoomout'):
  1159. zoomR = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1160. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1161. self.Refresh()
  1162. zoomFactor, view = self.ComputeZoom(zoomR)
  1163. self.Zoom(zoomFactor, view)
  1164. # draw map frame
  1165. if self.mouse['use'] == 'addMap':
  1166. rectTmp = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1167. # too small rectangle, it's usually some mistake
  1168. if rectTmp.GetWidth() < 20 or rectTmp.GetHeight() < 20:
  1169. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1170. self.Refresh()
  1171. return
  1172. rectPaper = self.CanvasPaperCoordinates(rect = rectTmp, canvasToPaper = True)
  1173. dlg = MapDialog(parent = self.parent, id = [None, None, None], settings = self.instruction,
  1174. rect = rectPaper)
  1175. self.openDialogs['map'] = dlg
  1176. self.openDialogs['map'].Show()
  1177. self.mouse['use'] = self.parent.mouseOld
  1178. self.SetCursor(self.parent.cursorOld)
  1179. self.parent.toolbar.ToggleTool(self.parent.actionOld, True)
  1180. self.parent.toolbar.ToggleTool(self.parent.toolbar.action['id'], False)
  1181. self.parent.toolbar.action['id'] = self.parent.actionOld
  1182. return
  1183. # resize resizable objects (map, line, rectangle)
  1184. if self.mouse['use'] == 'resize':
  1185. mapObj = self.instruction.FindInstructionByType('map')
  1186. if not mapObj:
  1187. mapObj = self.instruction.FindInstructionByType('initMap')
  1188. mapId = mapObj.id
  1189. if self.dragId == mapId:
  1190. # necessary to change either map frame (scaleType 0,1,2) or region (scaletype 3)
  1191. newRectCanvas = self.pdcObj.GetIdBounds(mapId)
  1192. newRectPaper = self.CanvasPaperCoordinates(rect = newRectCanvas, canvasToPaper = True)
  1193. self.instruction[mapId]['rect'] = newRectPaper
  1194. if self.instruction[mapId]['scaleType'] in (0, 1, 2):
  1195. if self.instruction[mapId]['scaleType'] == 0:
  1196. scale, foo, rect = AutoAdjust(self, scaleType = 0,
  1197. map = self.instruction[mapId]['map'],
  1198. mapType = self.instruction[mapId]['mapType'],
  1199. rect = self.instruction[mapId]['rect'])
  1200. elif self.instruction[mapId]['scaleType'] == 1:
  1201. scale, foo, rect = AutoAdjust(self, scaleType = 1,
  1202. region = self.instruction[mapId]['region'],
  1203. rect = self.instruction[mapId]['rect'])
  1204. else:
  1205. scale, foo, rect = AutoAdjust(self, scaleType = 2,
  1206. rect = self.instruction[mapId]['rect'])
  1207. self.instruction[mapId]['rect'] = rect
  1208. self.instruction[mapId]['scale'] = scale
  1209. rectCanvas = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)
  1210. self.Draw(pen = self.pen['map'], brush = self.brush['map'],
  1211. pdc = self.pdcObj, drawid = mapId, pdctype = 'rectText', bb = rectCanvas)
  1212. elif self.instruction[mapId]['scaleType'] == 3:
  1213. ComputeSetRegion(self, mapDict = self.instruction[mapId].GetInstruction())
  1214. #check resolution
  1215. SetResolution(dpi = self.instruction[mapId]['resolution'],
  1216. width = self.instruction[mapId]['rect'].width,
  1217. height = self.instruction[mapId]['rect'].height)
  1218. self.RedrawSelectBox(mapId)
  1219. self.Zoom(zoomFactor = 1, view = (0, 0))
  1220. elif self.instruction[self.dragId].type == 'line':
  1221. points = self.instruction[self.dragId]['where']
  1222. self.instruction[self.dragId]['rect'] = Rect2DPP(points[0], points[1])
  1223. self.RecalculatePosition(ids = [self.dragId])
  1224. elif self.instruction[self.dragId].type == 'rectangle':
  1225. self.RecalculatePosition(ids = [self.dragId])
  1226. self.mouse['use'] = 'pointer'
  1227. # recalculate the position of objects after dragging
  1228. if self.mouse['use'] in ('pointer', 'resize') and self.dragId != -1:
  1229. if self.mouse['begin'] != event.GetPosition(): #for double click
  1230. self.RecalculatePosition(ids = [self.dragId])
  1231. if self.instruction[self.dragId].type in self.openDialogs:
  1232. self.openDialogs[self.instruction[self.dragId].type].updateDialog()
  1233. elif self.mouse['use'] in ('addPoint', 'addLine', 'addRectangle'):
  1234. endCoordinates = self.CanvasPaperCoordinates(rect = wx.Rect(event.GetX(), event.GetY(), 0, 0),
  1235. canvasToPaper = True)[:2]
  1236. diffX = event.GetX() - self.mouse['begin'][0]
  1237. diffY = event.GetY() - self.mouse['begin'][1]
  1238. if self.mouse['use'] == 'addPoint':
  1239. self.parent.AddPoint(coordinates = endCoordinates)
  1240. elif self.mouse['use'] in ('addLine', 'addRectangle'):
  1241. # not too small lines/rectangles
  1242. if sqrt(diffX * diffX + diffY * diffY) < 5:
  1243. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1244. self.Refresh()
  1245. return
  1246. beginCoordinates = self.CanvasPaperCoordinates(rect = wx.Rect(self.mouse['begin'][0],
  1247. self.mouse['begin'][1], 0, 0),
  1248. canvasToPaper = True)[:2]
  1249. if self.mouse['use'] == 'addLine':
  1250. self.parent.AddLine(coordinates = [beginCoordinates, endCoordinates])
  1251. else:
  1252. self.parent.AddRectangle(coordinates = [beginCoordinates, endCoordinates])
  1253. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1254. self.Refresh()
  1255. def OnButtonDClick(self, event):
  1256. """!Open object dialog for editing."""
  1257. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1258. itemCall = {'text':self.parent.OnAddText,
  1259. 'mapinfo': self.parent.OnAddMapinfo,
  1260. 'scalebar': self.parent.OnAddScalebar,
  1261. 'image': self.parent.OnAddImage,
  1262. 'northArrow' : self.parent.OnAddNorthArrow,
  1263. 'point': self.parent.AddPoint,
  1264. 'line': self.parent.AddLine,
  1265. 'rectangle': self.parent.AddRectangle,
  1266. 'rasterLegend': self.parent.OnAddLegend,
  1267. 'vectorLegend': self.parent.OnAddLegend,
  1268. 'map': self.parent.OnAddMap}
  1269. itemArg = { 'text': dict(event = None, id = self.dragId),
  1270. 'mapinfo': dict(event = None),
  1271. 'scalebar': dict(event = None),
  1272. 'image': dict(event = None, id = self.dragId),
  1273. 'northArrow': dict(event = None, id = self.dragId),
  1274. 'point': dict(id = self.dragId),
  1275. 'line': dict(id = self.dragId),
  1276. 'rectangle': dict(id = self.dragId),
  1277. 'rasterLegend': dict(event = None),
  1278. 'vectorLegend': dict(event = None, page = 1),
  1279. 'map': dict(event = None, notebook = True)}
  1280. type = self.instruction[self.dragId].type
  1281. itemCall[type](**itemArg[type])
  1282. def OnDragging(self, event):
  1283. """!Process panning/resizing/drawing/moving."""
  1284. if event.MiddleIsDown():
  1285. # panning
  1286. self.mouse['end'] = event.GetPosition()
  1287. self.Pan(begin = self.mouse['begin'], end = self.mouse['end'])
  1288. self.mouse['begin'] = event.GetPosition()
  1289. elif event.LeftIsDown():
  1290. # draw box when zooming, creating map
  1291. if self.mouse['use'] in ('zoomin', 'zoomout', 'addMap', 'addLine', 'addRectangle'):
  1292. self.mouse['end'] = event.GetPosition()
  1293. r = wx.Rect(self.mouse['begin'][0], self.mouse['begin'][1],
  1294. self.mouse['end'][0]-self.mouse['begin'][0], self.mouse['end'][1]-self.mouse['begin'][1])
  1295. r = self.modifyRectangle(r)
  1296. if self.mouse['use'] in ('addLine', 'addRectangle'):
  1297. if self.mouse['use'] == 'addLine':
  1298. pdcType = 'line'
  1299. lineCoords = (self.mouse['begin'], self.mouse['end'])
  1300. else:
  1301. pdcType = 'rect'
  1302. lineCoords = None
  1303. if r[2] < 2 or r[3] < 2:
  1304. # to avoid strange behavoiur
  1305. return
  1306. self.Draw(pen = self.pen['line'], brush = self.brush['line'],
  1307. pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
  1308. pdctype = pdcType, bb = r, lineCoords = lineCoords)
  1309. else:
  1310. self.Draw(pen = self.pen['box'], brush = self.brush['box'],
  1311. pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
  1312. pdctype = 'rect', bb = r)
  1313. # panning
  1314. if self.mouse["use"] == 'pan':
  1315. self.mouse['end'] = event.GetPosition()
  1316. self.Pan(begin = self.mouse['begin'], end = self.mouse['end'])
  1317. self.mouse['begin'] = event.GetPosition()
  1318. # move object
  1319. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1320. self.mouse['end'] = event.GetPosition()
  1321. dx, dy = self.mouse['end'][0] - self.begin[0], self.mouse['end'][1] - self.begin[1]
  1322. self.pdcObj.TranslateId(self.dragId, dx, dy)
  1323. self.pdcTmp.TranslateId(self.idBoxTmp, dx, dy)
  1324. self.pdcTmp.TranslateId(self.idResizeBoxTmp, dx, dy)
  1325. for id in self.idLinePointsTmp:
  1326. self.pdcTmp.TranslateId(id, dx, dy)
  1327. if self.instruction[self.dragId].type == 'text':
  1328. self.instruction[self.dragId]['coords'] = self.instruction[self.dragId]['coords'][0] + dx,\
  1329. self.instruction[self.dragId]['coords'][1] + dy
  1330. self.begin = event.GetPosition()
  1331. self.Refresh()
  1332. # resize object
  1333. if self.mouse['use'] == 'resize':
  1334. pos = event.GetPosition()
  1335. diffX = pos[0] - self.mouse['begin'][0]
  1336. diffY = pos[1] - self.mouse['begin'][1]
  1337. if self.instruction[self.dragId].type == 'map':
  1338. x, y = self.mapBounds.GetX(), self.mapBounds.GetY()
  1339. width, height = self.mapBounds.GetWidth(), self.mapBounds.GetHeight()
  1340. # match given region
  1341. if self.constraint:
  1342. if width > height:
  1343. newWidth = width + diffX
  1344. newHeight = height + diffX * (float(height) / width)
  1345. else:
  1346. newWidth = width + diffY * (float(width) / height)
  1347. newHeight = height + diffY
  1348. else:
  1349. newWidth = width + diffX
  1350. newHeight = height + diffY
  1351. if newWidth < 10 or newHeight < 10:
  1352. return
  1353. bounds = wx.Rect(x, y, newWidth, newHeight)
  1354. self.Draw(pen = self.pen['map'], brush = self.brush['map'], pdc = self.pdcObj, drawid = self.dragId,
  1355. pdctype = 'rectText', bb = bounds)
  1356. elif self.instruction[self.dragId].type == 'rectangle':
  1357. instr = self.instruction[self.dragId]
  1358. rect = self.CanvasPaperCoordinates(rect = instr['rect'], canvasToPaper = False)
  1359. rect.SetWidth(rect.GetWidth() + diffX)
  1360. rect.SetHeight(rect.GetHeight() + diffY)
  1361. if rect.GetWidth() < 5 or rect.GetHeight() < 5:
  1362. return
  1363. self.DrawGraphics(drawid = self.dragId, shape = 'rectangle', color = instr['color'],
  1364. fcolor = instr['fcolor'], width = instr['width'], bb = rect)
  1365. elif self.instruction[self.dragId].type == 'line':
  1366. instr = self.instruction[self.dragId]
  1367. points = instr['where']
  1368. # moving point
  1369. if self.currentLinePoint == 0:
  1370. pPaper = points[1]
  1371. else:
  1372. pPaper = points[0]
  1373. pCanvas = self.CanvasPaperCoordinates(rect = Rect2DPS(pPaper, (0, 0)),
  1374. canvasToPaper = False)[:2]
  1375. bounds = wx.RectPP(pCanvas, pos)
  1376. self.DrawGraphics(drawid = self.dragId, shape = 'line', color = instr['color'],
  1377. width = instr['width'], bb = bounds, lineCoords = (pos, pCanvas))
  1378. # update paper coordinates
  1379. points[self.currentLinePoint] = self.CanvasPaperCoordinates(rect = wx.RectPS(pos, (0, 0)),
  1380. canvasToPaper = True)[:2]
  1381. self.RedrawSelectBox(self.dragId)
  1382. def OnMiddleDown(self, event):
  1383. """!Middle mouse button pressed."""
  1384. self.mouse['begin'] = event.GetPosition()
  1385. def Pan(self, begin, end):
  1386. """!Move canvas while dragging.
  1387. @param begin x,y coordinates of first point
  1388. @param end x,y coordinates of second point
  1389. """
  1390. view = begin[0] - end[0], begin[1] - end[1]
  1391. zoomFactor = 1
  1392. self.Zoom(zoomFactor, view)
  1393. def RecalculatePosition(self, ids):
  1394. for id in ids:
  1395. itype = self.instruction[id].type
  1396. if itype in ('map', 'rectangle'):
  1397. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1398. canvasToPaper = True)
  1399. self.RecalculateEN()
  1400. elif itype in ('mapinfo' ,'rasterLegend', 'vectorLegend', 'image', 'northArrow'):
  1401. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1402. canvasToPaper = True)
  1403. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1404. canvasToPaper = True)[:2]
  1405. if itype in ('image', 'northArrow'):
  1406. self.RecalculateEN()
  1407. elif itype == 'point':
  1408. rect = self.pdcObj.GetIdBounds(id)
  1409. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = rect,
  1410. canvasToPaper = True)
  1411. rect.OffsetXY(rect.GetWidth()/2, rect.GetHeight()/2)
  1412. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = rect,
  1413. canvasToPaper = True)[:2]
  1414. self.RecalculateEN()
  1415. elif itype == 'line':
  1416. rect = self.pdcObj.GetIdBounds(id)
  1417. oldRect = self.instruction[id]['rect']
  1418. newRect = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = True)
  1419. xDiff = newRect[0] - oldRect[0]
  1420. yDiff = newRect[1] - oldRect[1]
  1421. self.instruction[id]['rect'] = newRect
  1422. point1 = wx.Point2D(xDiff, yDiff) + self.instruction[id]['where'][0]
  1423. point2 = wx.Point2D(xDiff, yDiff) + self.instruction[id]['where'][1]
  1424. self.instruction[id]['where'] = [point1, point2]
  1425. self.RecalculateEN()
  1426. elif itype == 'scalebar':
  1427. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1428. canvasToPaper = True)
  1429. self.instruction[id]['where'] = self.instruction[id]['rect'].GetCentre()
  1430. elif itype == 'text':
  1431. x, y = self.instruction[id]['coords'][0] - self.instruction[id]['xoffset'],\
  1432. self.instruction[id]['coords'][1] + self.instruction[id]['yoffset']
  1433. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1434. if self.instruction[id]['rotate'] is not None:
  1435. rot = float(self.instruction[id]['rotate'])/180*pi
  1436. else:
  1437. rot = 0
  1438. if self.instruction[id]['ref'].split()[0] == 'lower':
  1439. y += extent[1]
  1440. elif self.instruction[id]['ref'].split()[0] == 'center':
  1441. y += extent[1]/2
  1442. if self.instruction[id]['ref'].split()[1] == 'right':
  1443. x += extent[0] * cos(rot)
  1444. y -= extent[0] * sin(rot)
  1445. elif self.instruction[id]['ref'].split()[1] == 'center':
  1446. x += extent[0]/2 * cos(rot)
  1447. y -= extent[0]/2 * sin(rot)
  1448. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = Rect2D(x, y, 0, 0),
  1449. canvasToPaper = True)[:2]
  1450. self.RecalculateEN()
  1451. def ComputeZoom(self, rect):
  1452. """!Computes zoom factor and scroll view"""
  1453. zoomFactor = 1
  1454. cW, cH = self.GetClientSize()
  1455. cW = float(cW)
  1456. if rect.IsEmpty(): # clicked on canvas
  1457. zoomFactor = 1.5
  1458. if self.mouse['use'] == 'zoomout':
  1459. zoomFactor = 1./zoomFactor
  1460. x,y = self.mouse['begin']
  1461. xView = x - x/zoomFactor#x - cW/(zoomFactor * 2)
  1462. yView = y - y/zoomFactor#y - cH/(zoomFactor * 2)
  1463. else: #dragging
  1464. rW, rH = float(rect.GetWidth()), float(rect.GetHeight())
  1465. try:
  1466. zoomFactor = 1/max(rW/cW, rH/cH)
  1467. except ZeroDivisionError:
  1468. zoomFactor = 1
  1469. # when zooming to full extent, in some cases, there was zoom 1.01..., which causes problem
  1470. if abs(zoomFactor - 1) > 0.01:
  1471. zoomFactor = zoomFactor
  1472. else:
  1473. zoomFactor = 1.
  1474. if self.mouse['use'] == 'zoomout':
  1475. zoomFactor = min(rW/cW, rH/cH)
  1476. try:
  1477. if rW/rH > cW/cH:
  1478. yView = rect.GetY() - (rW*(cH/cW) - rH)/2
  1479. xView = rect.GetX()
  1480. if self.mouse['use'] == 'zoomout':
  1481. x,y = rect.GetX() + (rW-(cW/cH)*rH)/2, rect.GetY()
  1482. xView, yView = -x, -y
  1483. else:
  1484. xView = rect.GetX() - (rH*(cW/cH) - rW)/2
  1485. yView = rect.GetY()
  1486. if self.mouse['use'] == 'zoomout':
  1487. x,y = rect.GetX(), rect.GetY() + (rH-(cH/cW)*rW)/2
  1488. xView, yView = -x, -y
  1489. except ZeroDivisionError:
  1490. xView, yView = rect.GetX(), rect.GetY()
  1491. return zoomFactor, (int(xView), int(yView))
  1492. def Zoom(self, zoomFactor, view):
  1493. """! Zoom to specified region, scroll view, redraw"""
  1494. if not self.currScale:
  1495. return
  1496. self.currScale = self.currScale*zoomFactor
  1497. if self.currScale > 10 or self.currScale < 0.1:
  1498. self.currScale = self.currScale/zoomFactor
  1499. return
  1500. if not self.preview:
  1501. # redraw paper
  1502. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  1503. pRect.OffsetXY(-view[0], -view[1])
  1504. pRect = self.ScaleRect(rect = pRect, scale = zoomFactor)
  1505. self.DrawPaper(pRect)
  1506. #redraw objects
  1507. for id in self.objectId:
  1508. oRect = self.CanvasPaperCoordinates(
  1509. rect = self.instruction[id]['rect'], canvasToPaper = False)
  1510. type = self.instruction[id].type
  1511. if type == 'text':
  1512. coords = self.instruction[id]['coords']# recalculate coordinates, they are not equal to BB
  1513. self.instruction[id]['coords'] = coords = [(int(coord) - view[i]) * zoomFactor
  1514. for i, coord in enumerate(coords)]
  1515. self.DrawRotText(pdc = self.pdcObj, drawId = id, textDict = self.instruction[id],
  1516. coords = coords, bounds = oRect )
  1517. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1518. if self.instruction[id]['rotate']:
  1519. rot = float(self.instruction[id]['rotate'])
  1520. else:
  1521. rot = 0
  1522. self.instruction[id]['rect'] = bounds = self.parent.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  1523. self.pdcObj.SetIdBounds(id, bounds)
  1524. elif type == 'northArrow':
  1525. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1526. drawid = id, pdctype = 'bitmap', bb = oRect)
  1527. elif type in ('point', 'line', 'rectangle'):
  1528. instr = self.instruction[id]
  1529. color = self.instruction[id]['color']
  1530. width = fcolor = coords = None
  1531. if type in ('point', 'rectangle'):
  1532. fcolor = self.instruction[id]['fcolor']
  1533. if type in ('line', 'rectangle'):
  1534. width = self.instruction[id]['width']
  1535. if type in ('line'):
  1536. point1, point2 = instr['where'][0], instr['where'][1]
  1537. point1 = self.CanvasPaperCoordinates(rect = Rect2DPS(point1, (0, 0)),
  1538. canvasToPaper = False)[:2]
  1539. point2 = self.CanvasPaperCoordinates(rect = Rect2DPS(point2, (0, 0)),
  1540. canvasToPaper = False)[:2]
  1541. coords = (point1, point2)
  1542. self.DrawGraphics(drawid = id, shape = type, bb = oRect, lineCoords = coords,
  1543. color = color, fcolor = fcolor, width = width)
  1544. else:
  1545. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1546. drawid = id, pdctype = 'rectText', bb = oRect)
  1547. #redraw tmp objects
  1548. if self.dragId != -1:
  1549. self.RedrawSelectBox(self.dragId)
  1550. #redraw preview
  1551. else: # preview mode
  1552. imageRect = self.pdcImage.GetIdBounds(self.imageId)
  1553. imageRect.OffsetXY(-view[0], -view[1])
  1554. imageRect = self.ScaleRect(rect = imageRect, scale = zoomFactor)
  1555. self.DrawImage(imageRect)
  1556. def ZoomAll(self):
  1557. """! Zoom to full extent"""
  1558. if not self.preview:
  1559. bounds = self.pdcPaper.GetIdBounds(self.pageId)
  1560. else:
  1561. bounds = self.pdcImage.GetIdBounds(self.imageId)
  1562. zoomP = bounds.Inflate(bounds.width/20, bounds.height/20)
  1563. zoomFactor, view = self.ComputeZoom(zoomP)
  1564. self.Zoom(zoomFactor, view)
  1565. def Draw(self, pen, brush, pdc, drawid = None, pdctype = 'rect', bb = wx.Rect(0,0,0,0), lineCoords = None):
  1566. """! Draw object with given pen and brush.
  1567. @param pdc PseudoDC
  1568. @param pdctype 'bitmap'/'rectText'/'rect'/'point'/'line'
  1569. @param bb bounding box
  1570. @param lineCoords coordinates of line start, end points (wx.Point, wx.Point)
  1571. """
  1572. if drawid is None:
  1573. drawid = wx.NewId()
  1574. bb = bb.Get()
  1575. pdc.BeginDrawing()
  1576. pdc.RemoveId(drawid)
  1577. pdc.SetId(drawid)
  1578. pdc.SetPen(pen)
  1579. pdc.SetBrush(brush)
  1580. if pdctype == 'bitmap':
  1581. if havePILImage:
  1582. file = self.instruction[drawid]['epsfile']
  1583. rotation = self.instruction[drawid]['rotate']
  1584. self.DrawBitmap(pdc = pdc, filePath = file, rotation = rotation, bbox = bb)
  1585. else: # draw only rectangle with label
  1586. pdctype = 'rectText'
  1587. if pdctype in ('rect', 'rectText'):
  1588. pdc.DrawRectangle(*bb)
  1589. if pdctype == 'rectText':
  1590. dc = wx.ClientDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  1591. font = self.font
  1592. size = 10
  1593. font.SetPointSize(size)
  1594. font.SetStyle(wx.ITALIC)
  1595. dc.SetFont(font)
  1596. pdc.SetFont(font)
  1597. text = '\n'.join(self.itemLabels[drawid])
  1598. w,h,lh = dc.GetMultiLineTextExtent(text)
  1599. textExtent = (w,h)
  1600. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1601. r = map(int, bb)
  1602. while not wx.Rect(*r).ContainsRect(textRect) and size >= 8:
  1603. size -= 2
  1604. font.SetPointSize(size)
  1605. dc.SetFont(font)
  1606. pdc.SetFont(font)
  1607. textExtent = dc.GetTextExtent(text)
  1608. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1609. pdc.SetTextForeground(wx.Colour(100,100,100,200))
  1610. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1611. pdc.DrawLabel(text = text, rect = textRect)
  1612. elif pdctype == 'point':
  1613. pdc.DrawCircle(x = bb[0] + bb[2] / 2,
  1614. y = bb[1] + bb[3] / 2,
  1615. radius = bb[2] / 2)
  1616. elif pdctype == 'line':
  1617. pdc.DrawLinePoint(lineCoords[0], lineCoords[1])
  1618. pdc.SetIdBounds(drawid, bb)
  1619. pdc.EndDrawing()
  1620. self.Refresh()
  1621. return drawid
  1622. def DrawGraphics(self, drawid, shape, color, bb, width = None, fcolor = None, lineCoords = None):
  1623. """!Draw point/line/rectangle with given color and width
  1624. @param drawid id of drawn object
  1625. @param shape drawn shape: 'point'/'line'/'rectangle'
  1626. @param color pen outline color ('RRR:GGG:BBB')
  1627. @param fcolor brush fill color, if meaningful ('RRR:GGG:BBB')
  1628. @param width pen width
  1629. @param bb bounding box
  1630. @param lineCoords line coordinates (for line only)
  1631. """
  1632. pdctype = {'point' : 'point',
  1633. 'line' : 'line',
  1634. 'rectangle' : 'rect'}
  1635. if color == 'none':
  1636. pen = wx.TRANSPARENT_PEN
  1637. else:
  1638. if width is not None:
  1639. units = UnitConversion(self)
  1640. width = int(units.convert(value = width, fromUnit = 'point', toUnit = 'pixel') * self.currScale)
  1641. else:
  1642. width = 2
  1643. pen = wx.Pen(colour = convertRGB(color), width = width)
  1644. pen.SetCap(wx.CAP_BUTT) # this is how ps.map draws
  1645. brush = wx.TRANSPARENT_BRUSH
  1646. if fcolor and fcolor != 'none':
  1647. brush = wx.Brush(colour = convertRGB(fcolor))
  1648. self.Draw(pen = pen, brush = brush, pdc = self.pdcObj, pdctype = pdctype[shape],
  1649. drawid = drawid, bb = bb, lineCoords = lineCoords)
  1650. def DrawBitmap(self, pdc, filePath, rotation, bbox):
  1651. """!Draw bitmap using PIL"""
  1652. pImg = PILImage.open(filePath)
  1653. if rotation:
  1654. # get rid of black background
  1655. pImg = pImg.convert("RGBA")
  1656. rot = pImg.rotate(rotation, expand = 1)
  1657. new = PILImage.new('RGBA', rot.size, (255,) * 4)
  1658. pImg = PILImage.composite(rot, new, rot)
  1659. pImg = pImg.resize((int(bbox[2]), int(bbox[3])), resample = PILImage.BICUBIC)
  1660. img = PilImageToWxImage(pImg)
  1661. bitmap = img.ConvertToBitmap()
  1662. mask = wx.Mask(bitmap, wx.WHITE)
  1663. bitmap.SetMask(mask)
  1664. pdc.DrawBitmap(bitmap, bbox[0], bbox[1], useMask = True)
  1665. def DrawRotText(self, pdc, drawId, textDict, coords, bounds):
  1666. if textDict['rotate']:
  1667. rot = float(textDict['rotate'])
  1668. else:
  1669. rot = 0
  1670. fontsize = textDict['fontsize'] * self.currScale
  1671. if textDict['background'] != 'none':
  1672. background = textDict['background']
  1673. else:
  1674. background = None
  1675. pdc.RemoveId(drawId)
  1676. pdc.SetId(drawId)
  1677. pdc.BeginDrawing()
  1678. # border is not redrawn when zoom changes, why?
  1679. ## if textDict['border'] != 'none' and not rot:
  1680. ## units = UnitConversion(self)
  1681. ## borderWidth = units.convert(value = textDict['width'],
  1682. ## fromUnit = 'point', toUnit = 'pixel' ) * self.currScale
  1683. ## pdc.SetPen(wx.Pen(colour = convertRGB(textDict['border']), width = borderWidth))
  1684. ## pdc.DrawRectangle(*bounds)
  1685. if background:
  1686. pdc.SetTextBackground(convertRGB(background))
  1687. pdc.SetBackgroundMode(wx.SOLID)
  1688. else:
  1689. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1690. fn = self.parent.makePSFont(textDict)
  1691. pdc.SetFont(fn)
  1692. pdc.SetTextForeground(convertRGB(textDict['color']))
  1693. pdc.DrawRotatedText(textDict['text'], coords[0], coords[1], rot)
  1694. pdc.SetIdBounds(drawId, wx.Rect(*bounds))
  1695. self.Refresh()
  1696. pdc.EndDrawing()
  1697. def DrawImage(self, rect):
  1698. """!Draw preview image to pseudoDC"""
  1699. self.pdcImage.ClearId(self.imageId)
  1700. self.pdcImage.SetId(self.imageId)
  1701. img = self.image
  1702. if img.GetWidth() != rect.width or img.GetHeight() != rect.height:
  1703. img = img.Scale(rect.width, rect.height)
  1704. bitmap = img.ConvertToBitmap()
  1705. self.pdcImage.BeginDrawing()
  1706. self.pdcImage.DrawBitmap(bitmap, rect.x, rect.y)
  1707. self.pdcImage.SetIdBounds(self.imageId, rect)
  1708. self.pdcImage.EndDrawing()
  1709. self.Refresh()
  1710. def DrawPaper(self, rect):
  1711. """!Draw paper and margins"""
  1712. page = self.instruction[self.pageId]
  1713. scale = page['Width'] / rect.GetWidth()
  1714. w = (page['Width'] - page['Right'] - page['Left']) / scale
  1715. h = (page['Height'] - page['Top'] - page['Bottom']) / scale
  1716. x = page['Left'] / scale + rect.GetX()
  1717. y = page['Top'] / scale + rect.GetY()
  1718. self.pdcPaper.BeginDrawing()
  1719. self.pdcPaper.RemoveId(self.pageId)
  1720. self.pdcPaper.SetId(self.pageId)
  1721. self.pdcPaper.SetPen(self.pen['paper'])
  1722. self.pdcPaper.SetBrush(self.brush['paper'])
  1723. self.pdcPaper.DrawRectangleRect(rect)
  1724. self.pdcPaper.SetPen(self.pen['margins'])
  1725. self.pdcPaper.SetBrush(self.brush['margins'])
  1726. self.pdcPaper.DrawRectangle(x, y, w, h)
  1727. self.pdcPaper.SetIdBounds(self.pageId, rect)
  1728. self.pdcPaper.EndDrawing()
  1729. self.Refresh()
  1730. def ImageRect(self):
  1731. """!Returns image centered in canvas, computes scale"""
  1732. img = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  1733. cW, cH = self.GetClientSize()
  1734. iW, iH = img.GetWidth(), img.GetHeight()
  1735. self.currScale = min(float(cW)/iW, float(cH)/iH)
  1736. iW = iW * self.currScale
  1737. iH = iH * self.currScale
  1738. x = cW/2 - iW/2
  1739. y = cH/2 - iH/2
  1740. imageRect = wx.Rect(x, y, iW, iH)
  1741. return imageRect
  1742. def RedrawSelectBox(self, id):
  1743. """!Redraws select box when selected object changes its size"""
  1744. if self.dragId == id:
  1745. rect = self.pdcObj.GetIdBounds(id)
  1746. if self.instruction[id].type != 'line':
  1747. rect = rect.Inflate(3,3)
  1748. # draw select box around object
  1749. self.Draw(pen = self.pen['select'], brush = self.brush['select'], pdc = self.pdcTmp,
  1750. drawid = self.idBoxTmp, pdctype = 'rect', bb = rect)
  1751. # draw small marks signalizing resizing
  1752. if self.instruction[id].type in ('map', 'rectangle'):
  1753. controlP = self.pdcObj.GetIdBounds(id).GetBottomRight()
  1754. rect = wx.RectPS(controlP, self.resizeBoxSize)
  1755. self.Draw(pen = self.pen['resize'], brush = self.brush['resize'], pdc = self.pdcTmp,
  1756. drawid = self.idResizeBoxTmp, pdctype = 'rect', bb = rect)
  1757. elif self.instruction[id].type == 'line':
  1758. p1Paper = self.instruction[id]['where'][0]
  1759. p2Paper = self.instruction[id]['where'][1]
  1760. p1Canvas = self.CanvasPaperCoordinates(rect = Rect2DPS(p1Paper, (0, 0)), canvasToPaper = False)[:2]
  1761. p2Canvas = self.CanvasPaperCoordinates(rect = Rect2DPS(p2Paper, (0, 0)), canvasToPaper = False)[:2]
  1762. rect = []
  1763. box = wx.RectS(self.resizeBoxSize)
  1764. rect.append(box.CenterIn(wx.RectPS(p1Canvas, wx.Size())))
  1765. rect.append(box.CenterIn(wx.RectPS(p2Canvas, wx.Size())))
  1766. for i, point in enumerate((p1Canvas, p2Canvas)):
  1767. self.Draw(pen = self.pen['resize'], brush = self.brush['resize'], pdc = self.pdcTmp,
  1768. drawid = self.idLinePointsTmp[i], pdctype = 'rect', bb = rect[i])
  1769. def UpdateMapLabel(self):
  1770. """!Updates map frame label"""
  1771. vector = self.instruction.FindInstructionByType('vector')
  1772. if vector:
  1773. vectorId = vector.id
  1774. else:
  1775. vectorId = None
  1776. raster = self.instruction.FindInstructionByType('raster')
  1777. if raster:
  1778. rasterId = raster.id
  1779. else:
  1780. rasterId = None
  1781. rasterName = 'None'
  1782. if rasterId:
  1783. rasterName = self.instruction[rasterId]['raster'].split('@')[0]
  1784. mapId = self.instruction.FindInstructionByType('map').id
  1785. self.itemLabels[mapId] = []
  1786. self.itemLabels[mapId].append(self.itemLabelsDict['map'])
  1787. self.itemLabels[mapId].append("raster: " + rasterName)
  1788. if vectorId:
  1789. for map in self.instruction[vectorId]['list']:
  1790. self.itemLabels[mapId].append('vector: ' + map[0].split('@')[0])
  1791. def UpdateLabel(self, itype, id):
  1792. self.itemLabels[id] = []
  1793. self.itemLabels[id].append(self.itemLabelsDict[itype])
  1794. if itype == 'image':
  1795. file = os.path.basename(self.instruction[id]['epsfile'])
  1796. self.itemLabels[id].append(file)
  1797. def OnSize(self, event):
  1798. """!Init image size to match window size
  1799. """
  1800. # not zoom all when notebook page is changed
  1801. if self.preview and self.parent.currentPage == 1 or not self.preview and self.parent.currentPage == 0:
  1802. self.ZoomAll()
  1803. self.OnIdle(None)
  1804. event.Skip()
  1805. def OnIdle(self, event):
  1806. """!Only re-render a image during idle time instead of
  1807. multiple times during resizing.
  1808. """
  1809. width, height = self.GetClientSize()
  1810. # Make new off screen bitmap: this bitmap will always have the
  1811. # current drawing in it, so it can be used to save the image
  1812. # to a file, or whatever.
  1813. self._buffer = wx.EmptyBitmap(width, height)
  1814. # re-render image on idle
  1815. self.resize = True
  1816. def ScaleRect(self, rect, scale):
  1817. """! Scale rectangle"""
  1818. return wx.Rect(rect.GetLeft()*scale, rect.GetTop()*scale,
  1819. rect.GetSize()[0]*scale, rect.GetSize()[1]*scale)
  1820. # hack for Windows, loading EPS works only on Unix
  1821. # these functions are taken from EpsImagePlugin.py
  1822. def loadPSForWindows(self):
  1823. # Load EPS via Ghostscript
  1824. if not self.tile:
  1825. return
  1826. self.im = GhostscriptForWindows(self.tile, self.size, self.fp)
  1827. self.mode = self.im.mode
  1828. self.size = self.im.size
  1829. self.tile = []
  1830. def GhostscriptForWindows(tile, size, fp):
  1831. """Render an image using Ghostscript (Windows only)"""
  1832. # Unpack decoder tile
  1833. decoder, tile, offset, data = tile[0]
  1834. length, bbox = data
  1835. import tempfile, os
  1836. file = tempfile.mkstemp()[1]
  1837. # Build ghostscript command - for Windows
  1838. command = ["gswin32c",
  1839. "-q", # quite mode
  1840. "-g%dx%d" % size, # set output geometry (pixels)
  1841. "-dNOPAUSE -dSAFER", # don't pause between pages, safe mode
  1842. "-sDEVICE=ppmraw", # ppm driver
  1843. "-sOutputFile=%s" % file # output file
  1844. ]
  1845. command = string.join(command)
  1846. # push data through ghostscript
  1847. try:
  1848. gs = os.popen(command, "w")
  1849. # adjust for image origin
  1850. if bbox[0] != 0 or bbox[1] != 0:
  1851. gs.write("%d %d translate\n" % (-bbox[0], -bbox[1]))
  1852. fp.seek(offset)
  1853. while length > 0:
  1854. s = fp.read(8192)
  1855. if not s:
  1856. break
  1857. length = length - len(s)
  1858. gs.write(s)
  1859. status = gs.close()
  1860. if status:
  1861. raise IOError("gs failed (status %d)" % status)
  1862. im = PILImage.core.open_ppm(file)
  1863. finally:
  1864. try: os.unlink(file)
  1865. except: pass
  1866. return im