frame.py 93 KB

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