frame.py 95 KB

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