frame.py 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203
  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 as 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 as 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. def __init__(self, parent, id = wx.ID_ANY,
  903. style = wx.NO_FULL_REPAINT_ON_RESIZE,
  904. **kwargs):
  905. """
  906. :param parent: parent window
  907. :param kwargs: other wx.Window parameters
  908. """
  909. wx.Window.__init__(self, parent, id = id, style = style)
  910. self.parent = parent
  911. self.FitInside()
  912. # store an off screen empty bitmap for saving to file
  913. self._buffer = None
  914. # indicates whether or not a resize event has taken place
  915. self.resize = False
  916. self.mouse = kwargs['mouse']
  917. self.cursors = kwargs['cursors']
  918. self.preview = kwargs['preview']
  919. self.pen = kwargs['pen']
  920. self.brush = kwargs['brush']
  921. if kwargs.has_key('instruction'):
  922. self.instruction = kwargs['instruction']
  923. if kwargs.has_key('openDialogs'):
  924. self.openDialogs = kwargs['openDialogs']
  925. if kwargs.has_key('pageId'):
  926. self.pageId = kwargs['pageId']
  927. if kwargs.has_key('objectId'):
  928. self.objectId = kwargs['objectId']
  929. #labels
  930. self.itemLabelsDict = { 'map': _("MAP FRAME"),
  931. 'rasterLegend': _("RASTER LEGEND"),
  932. 'vectorLegend': _("VECTOR LEGEND"),
  933. 'mapinfo': _("MAP INFO"),
  934. 'scalebar': _("SCALE BAR"),
  935. 'image': _("IMAGE"),
  936. 'northArrow': _("NORTH ARROW")}
  937. self.itemLabels = {}
  938. # define PseudoDC
  939. self.pdc = wx.PseudoDC()
  940. self.pdcObj = wx.PseudoDC()
  941. self.pdcPaper = wx.PseudoDC()
  942. self.pdcTmp = wx.PseudoDC()
  943. self.pdcImage = wx.PseudoDC()
  944. self.SetClientSize((700,510))#?
  945. self._buffer = wx.EmptyBitmap(*self.GetClientSize())
  946. self.idBoxTmp = wx.NewId()
  947. self.idZoomBoxTmp = wx.NewId()
  948. self.idResizeBoxTmp = wx.NewId()
  949. self.idLinePointsTmp = (wx.NewId(), wx.NewId()) # ids of marks for moving line vertices
  950. self.resizeBoxSize = wx.Size(8, 8)
  951. self.showResizeHelp = False # helper for correctly working statusbar
  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. self.showResizeHelp = True
  1129. else:
  1130. if self.showResizeHelp:
  1131. self.parent.SetStatusText('', 0)
  1132. self.SetCursor(self.cursors["default"])
  1133. self.showResizeHelp = False
  1134. def OnLeftDown(self, event):
  1135. """Left mouse button pressed.
  1136. Select objects, redraw, prepare for moving/resizing.
  1137. """
  1138. self.mouse['begin'] = event.GetPosition()
  1139. self.begin = self.mouse['begin']
  1140. # select
  1141. if self.mouse['use'] == 'pointer':
  1142. found = self.pdcObj.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  1143. foundResize = self.pdcTmp.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  1144. if foundResize and foundResize[0] in (self.idResizeBoxTmp,) + self.idLinePointsTmp:
  1145. self.mouse['use'] = 'resize'
  1146. # when resizing, proportions match region
  1147. if self.instruction[self.dragId].type == 'map':
  1148. self.constraint = False
  1149. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1150. if self.instruction[self.dragId]['scaleType'] in (0, 1, 2):
  1151. self.constraint = True
  1152. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1153. if self.instruction[self.dragId].type == 'line':
  1154. self.currentLinePoint = self.idLinePointsTmp.index(foundResize[0])
  1155. elif found:
  1156. self.dragId = found[0]
  1157. self.RedrawSelectBox(self.dragId)
  1158. if self.instruction[self.dragId].type not in ('map', 'rectangle'):
  1159. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1160. self.Refresh()
  1161. if self.instruction[self.dragId].type != 'line':
  1162. for id in self.idLinePointsTmp:
  1163. self.pdcTmp.RemoveId(id)
  1164. self.Refresh()
  1165. else:
  1166. self.dragId = -1
  1167. self.pdcTmp.RemoveId(self.idBoxTmp)
  1168. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1169. for id in self.idLinePointsTmp:
  1170. self.pdcTmp.RemoveId(id)
  1171. self.Refresh()
  1172. def OnLeftUp(self, event):
  1173. """Left mouse button released.
  1174. Recalculate zooming/resizing/moving and redraw.
  1175. """
  1176. # zoom in, zoom out
  1177. if self.mouse['use'] in ('zoomin','zoomout'):
  1178. zoomR = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1179. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1180. self.Refresh()
  1181. zoomFactor, view = self.ComputeZoom(zoomR)
  1182. self.Zoom(zoomFactor, view)
  1183. # draw map frame
  1184. if self.mouse['use'] == 'addMap':
  1185. rectTmp = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1186. # too small rectangle, it's usually some mistake
  1187. if rectTmp.GetWidth() < 20 or rectTmp.GetHeight() < 20:
  1188. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1189. self.Refresh()
  1190. return
  1191. rectPaper = self.CanvasPaperCoordinates(rect = rectTmp, canvasToPaper = True)
  1192. dlg = MapDialog(parent = self.parent, id = [None, None, None], settings = self.instruction,
  1193. rect = rectPaper)
  1194. self.openDialogs['map'] = dlg
  1195. self.openDialogs['map'].Show()
  1196. self.parent.toolbar.SelectDefault()
  1197. return
  1198. # resize resizable objects (map, line, rectangle)
  1199. if self.mouse['use'] == 'resize':
  1200. mapObj = self.instruction.FindInstructionByType('map')
  1201. if not mapObj:
  1202. mapObj = self.instruction.FindInstructionByType('initMap')
  1203. mapId = mapObj.id
  1204. if self.dragId == mapId:
  1205. # necessary to change either map frame (scaleType 0,1,2) or region (scaletype 3)
  1206. newRectCanvas = self.pdcObj.GetIdBounds(mapId)
  1207. newRectPaper = self.CanvasPaperCoordinates(rect = newRectCanvas, canvasToPaper = True)
  1208. self.instruction[mapId]['rect'] = newRectPaper
  1209. if self.instruction[mapId]['scaleType'] in (0, 1, 2):
  1210. if self.instruction[mapId]['scaleType'] == 0:
  1211. scale, foo, rect = AutoAdjust(self, scaleType = 0,
  1212. map = self.instruction[mapId]['map'],
  1213. mapType = self.instruction[mapId]['mapType'],
  1214. rect = self.instruction[mapId]['rect'])
  1215. elif self.instruction[mapId]['scaleType'] == 1:
  1216. scale, foo, rect = AutoAdjust(self, scaleType = 1,
  1217. region = self.instruction[mapId]['region'],
  1218. rect = self.instruction[mapId]['rect'])
  1219. else:
  1220. scale, foo, rect = AutoAdjust(self, scaleType = 2,
  1221. rect = self.instruction[mapId]['rect'])
  1222. self.instruction[mapId]['rect'] = rect
  1223. self.instruction[mapId]['scale'] = scale
  1224. rectCanvas = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)
  1225. self.Draw(pen = self.pen['map'], brush = self.brush['map'],
  1226. pdc = self.pdcObj, drawid = mapId, pdctype = 'rectText', bb = rectCanvas)
  1227. elif self.instruction[mapId]['scaleType'] == 3:
  1228. ComputeSetRegion(self, mapDict = self.instruction[mapId].GetInstruction())
  1229. #check resolution
  1230. SetResolution(dpi = self.instruction[mapId]['resolution'],
  1231. width = self.instruction[mapId]['rect'].width,
  1232. height = self.instruction[mapId]['rect'].height)
  1233. self.RedrawSelectBox(mapId)
  1234. self.Zoom(zoomFactor = 1, view = (0, 0))
  1235. elif self.instruction[self.dragId].type == 'line':
  1236. points = self.instruction[self.dragId]['where']
  1237. self.instruction[self.dragId]['rect'] = Rect2DPP(points[0], points[1])
  1238. self.RecalculatePosition(ids = [self.dragId])
  1239. elif self.instruction[self.dragId].type == 'rectangle':
  1240. self.RecalculatePosition(ids = [self.dragId])
  1241. self.mouse['use'] = 'pointer'
  1242. # recalculate the position of objects after dragging
  1243. if self.mouse['use'] in ('pointer', 'resize') and self.dragId != -1:
  1244. if self.mouse['begin'] != event.GetPosition(): #for double click
  1245. self.RecalculatePosition(ids = [self.dragId])
  1246. if self.instruction[self.dragId].type in self.openDialogs:
  1247. self.openDialogs[self.instruction[self.dragId].type].updateDialog()
  1248. elif self.mouse['use'] in ('addPoint', 'addLine', 'addRectangle'):
  1249. endCoordinates = self.CanvasPaperCoordinates(rect = wx.Rect(event.GetX(), event.GetY(), 0, 0),
  1250. canvasToPaper = True)[:2]
  1251. diffX = event.GetX() - self.mouse['begin'][0]
  1252. diffY = event.GetY() - self.mouse['begin'][1]
  1253. if self.mouse['use'] == 'addPoint':
  1254. self.parent.AddPoint(coordinates = endCoordinates)
  1255. elif self.mouse['use'] in ('addLine', 'addRectangle'):
  1256. # not too small lines/rectangles
  1257. if sqrt(diffX * diffX + diffY * diffY) < 5:
  1258. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1259. self.Refresh()
  1260. return
  1261. beginCoordinates = self.CanvasPaperCoordinates(rect = wx.Rect(self.mouse['begin'][0],
  1262. self.mouse['begin'][1], 0, 0),
  1263. canvasToPaper = True)[:2]
  1264. if self.mouse['use'] == 'addLine':
  1265. self.parent.AddLine(coordinates = [beginCoordinates, endCoordinates])
  1266. else:
  1267. self.parent.AddRectangle(coordinates = [beginCoordinates, endCoordinates])
  1268. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1269. self.Refresh()
  1270. def OnButtonDClick(self, event):
  1271. """Open object dialog for editing."""
  1272. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1273. itemCall = {'text':self.parent.OnAddText,
  1274. 'mapinfo': self.parent.OnAddMapinfo,
  1275. 'scalebar': self.parent.OnAddScalebar,
  1276. 'image': self.parent.OnAddImage,
  1277. 'northArrow' : self.parent.OnAddNorthArrow,
  1278. 'point': self.parent.AddPoint,
  1279. 'line': self.parent.AddLine,
  1280. 'rectangle': self.parent.AddRectangle,
  1281. 'rasterLegend': self.parent.OnAddLegend,
  1282. 'vectorLegend': self.parent.OnAddLegend,
  1283. 'map': self.parent.OnAddMap}
  1284. itemArg = { 'text': dict(event = None, id = self.dragId),
  1285. 'mapinfo': dict(event = None),
  1286. 'scalebar': dict(event = None),
  1287. 'image': dict(event = None, id = self.dragId),
  1288. 'northArrow': dict(event = None, id = self.dragId),
  1289. 'point': dict(id = self.dragId),
  1290. 'line': dict(id = self.dragId),
  1291. 'rectangle': dict(id = self.dragId),
  1292. 'rasterLegend': dict(event = None),
  1293. 'vectorLegend': dict(event = None, page = 1),
  1294. 'map': dict(event = None, notebook = True)}
  1295. type = self.instruction[self.dragId].type
  1296. itemCall[type](**itemArg[type])
  1297. def OnDragging(self, event):
  1298. """Process panning/resizing/drawing/moving."""
  1299. if event.MiddleIsDown():
  1300. # panning
  1301. self.mouse['end'] = event.GetPosition()
  1302. self.Pan(begin = self.mouse['begin'], end = self.mouse['end'])
  1303. self.mouse['begin'] = event.GetPosition()
  1304. elif event.LeftIsDown():
  1305. # draw box when zooming, creating map
  1306. if self.mouse['use'] in ('zoomin', 'zoomout', 'addMap', 'addLine', 'addRectangle'):
  1307. self.mouse['end'] = event.GetPosition()
  1308. r = wx.Rect(self.mouse['begin'][0], self.mouse['begin'][1],
  1309. self.mouse['end'][0]-self.mouse['begin'][0], self.mouse['end'][1]-self.mouse['begin'][1])
  1310. r = self.modifyRectangle(r)
  1311. if self.mouse['use'] in ('addLine', 'addRectangle'):
  1312. if self.mouse['use'] == 'addLine':
  1313. pdcType = 'line'
  1314. lineCoords = (self.mouse['begin'], self.mouse['end'])
  1315. else:
  1316. pdcType = 'rect'
  1317. lineCoords = None
  1318. if r[2] < 2 or r[3] < 2:
  1319. # to avoid strange behavoiur
  1320. return
  1321. self.Draw(pen = self.pen['line'], brush = self.brush['line'],
  1322. pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
  1323. pdctype = pdcType, bb = r, lineCoords = lineCoords)
  1324. else:
  1325. self.Draw(pen = self.pen['box'], brush = self.brush['box'],
  1326. pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
  1327. pdctype = 'rect', bb = r)
  1328. # panning
  1329. if self.mouse["use"] == 'pan':
  1330. self.mouse['end'] = event.GetPosition()
  1331. self.Pan(begin = self.mouse['begin'], end = self.mouse['end'])
  1332. self.mouse['begin'] = event.GetPosition()
  1333. # move object
  1334. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1335. self.mouse['end'] = event.GetPosition()
  1336. dx, dy = self.mouse['end'][0] - self.begin[0], self.mouse['end'][1] - self.begin[1]
  1337. self.pdcObj.TranslateId(self.dragId, dx, dy)
  1338. self.pdcTmp.TranslateId(self.idBoxTmp, dx, dy)
  1339. self.pdcTmp.TranslateId(self.idResizeBoxTmp, dx, dy)
  1340. for id in self.idLinePointsTmp:
  1341. self.pdcTmp.TranslateId(id, dx, dy)
  1342. if self.instruction[self.dragId].type == 'text':
  1343. self.instruction[self.dragId]['coords'] = self.instruction[self.dragId]['coords'][0] + dx,\
  1344. self.instruction[self.dragId]['coords'][1] + dy
  1345. self.begin = event.GetPosition()
  1346. self.Refresh()
  1347. # resize object
  1348. if self.mouse['use'] == 'resize':
  1349. pos = event.GetPosition()
  1350. diffX = pos[0] - self.mouse['begin'][0]
  1351. diffY = pos[1] - self.mouse['begin'][1]
  1352. if self.instruction[self.dragId].type == 'map':
  1353. x, y = self.mapBounds.GetX(), self.mapBounds.GetY()
  1354. width, height = self.mapBounds.GetWidth(), self.mapBounds.GetHeight()
  1355. # match given region
  1356. if self.constraint:
  1357. if width > height:
  1358. newWidth = width + diffX
  1359. newHeight = height + diffX * (float(height) / width)
  1360. else:
  1361. newWidth = width + diffY * (float(width) / height)
  1362. newHeight = height + diffY
  1363. else:
  1364. newWidth = width + diffX
  1365. newHeight = height + diffY
  1366. if newWidth < 10 or newHeight < 10:
  1367. return
  1368. bounds = wx.Rect(x, y, newWidth, newHeight)
  1369. self.Draw(pen = self.pen['map'], brush = self.brush['map'], pdc = self.pdcObj, drawid = self.dragId,
  1370. pdctype = 'rectText', bb = bounds)
  1371. elif self.instruction[self.dragId].type == 'rectangle':
  1372. instr = self.instruction[self.dragId]
  1373. rect = self.CanvasPaperCoordinates(rect = instr['rect'], canvasToPaper = False)
  1374. rect.SetWidth(rect.GetWidth() + diffX)
  1375. rect.SetHeight(rect.GetHeight() + diffY)
  1376. if rect.GetWidth() < 5 or rect.GetHeight() < 5:
  1377. return
  1378. self.DrawGraphics(drawid = self.dragId, shape = 'rectangle', color = instr['color'],
  1379. fcolor = instr['fcolor'], width = instr['width'], bb = rect)
  1380. elif self.instruction[self.dragId].type == 'line':
  1381. instr = self.instruction[self.dragId]
  1382. points = instr['where']
  1383. # moving point
  1384. if self.currentLinePoint == 0:
  1385. pPaper = points[1]
  1386. else:
  1387. pPaper = points[0]
  1388. pCanvas = self.CanvasPaperCoordinates(rect = Rect2DPS(pPaper, (0, 0)),
  1389. canvasToPaper = False)[:2]
  1390. bounds = wx.RectPP(pCanvas, pos)
  1391. self.DrawGraphics(drawid = self.dragId, shape = 'line', color = instr['color'],
  1392. width = instr['width'], bb = bounds, lineCoords = (pos, pCanvas))
  1393. # update paper coordinates
  1394. points[self.currentLinePoint] = self.CanvasPaperCoordinates(rect = wx.RectPS(pos, (0, 0)),
  1395. canvasToPaper = True)[:2]
  1396. self.RedrawSelectBox(self.dragId)
  1397. def OnMiddleDown(self, event):
  1398. """Middle mouse button pressed."""
  1399. self.mouse['begin'] = event.GetPosition()
  1400. def Pan(self, begin, end):
  1401. """Move canvas while dragging.
  1402. :param begin: x,y coordinates of first point
  1403. :param end: x,y coordinates of second point
  1404. """
  1405. view = begin[0] - end[0], begin[1] - end[1]
  1406. zoomFactor = 1
  1407. self.Zoom(zoomFactor, view)
  1408. def RecalculatePosition(self, ids):
  1409. for id in ids:
  1410. itype = self.instruction[id].type
  1411. if itype in ('map', 'rectangle'):
  1412. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1413. canvasToPaper = True)
  1414. self.RecalculateEN()
  1415. elif itype in ('mapinfo' ,'rasterLegend', 'vectorLegend', 'image', 'northArrow'):
  1416. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1417. canvasToPaper = True)
  1418. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1419. canvasToPaper = True)[:2]
  1420. if itype in ('image', 'northArrow'):
  1421. self.RecalculateEN()
  1422. elif itype == 'point':
  1423. rect = self.pdcObj.GetIdBounds(id)
  1424. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = rect,
  1425. canvasToPaper = True)
  1426. rect.OffsetXY(rect.GetWidth()/2, rect.GetHeight()/2)
  1427. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = rect,
  1428. canvasToPaper = True)[:2]
  1429. self.RecalculateEN()
  1430. elif itype == 'line':
  1431. rect = self.pdcObj.GetIdBounds(id)
  1432. oldRect = self.instruction[id]['rect']
  1433. newRect = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = True)
  1434. xDiff = newRect[0] - oldRect[0]
  1435. yDiff = newRect[1] - oldRect[1]
  1436. self.instruction[id]['rect'] = newRect
  1437. point1 = wx.Point2D(xDiff, yDiff) + self.instruction[id]['where'][0]
  1438. point2 = wx.Point2D(xDiff, yDiff) + self.instruction[id]['where'][1]
  1439. self.instruction[id]['where'] = [point1, point2]
  1440. self.RecalculateEN()
  1441. elif itype == 'scalebar':
  1442. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1443. canvasToPaper = True)
  1444. self.instruction[id]['where'] = self.instruction[id]['rect'].GetCentre()
  1445. elif itype == 'text':
  1446. x, y = self.instruction[id]['coords'][0] - self.instruction[id]['xoffset'],\
  1447. self.instruction[id]['coords'][1] + self.instruction[id]['yoffset']
  1448. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1449. if self.instruction[id]['rotate'] is not None:
  1450. rot = float(self.instruction[id]['rotate'])/180*pi
  1451. else:
  1452. rot = 0
  1453. if self.instruction[id]['ref'].split()[0] == 'lower':
  1454. y += extent[1]
  1455. elif self.instruction[id]['ref'].split()[0] == 'center':
  1456. y += extent[1]/2
  1457. if self.instruction[id]['ref'].split()[1] == 'right':
  1458. x += extent[0] * cos(rot)
  1459. y -= extent[0] * sin(rot)
  1460. elif self.instruction[id]['ref'].split()[1] == 'center':
  1461. x += extent[0]/2 * cos(rot)
  1462. y -= extent[0]/2 * sin(rot)
  1463. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = Rect2D(x, y, 0, 0),
  1464. canvasToPaper = True)[:2]
  1465. self.RecalculateEN()
  1466. def ComputeZoom(self, rect):
  1467. """Computes zoom factor and scroll view"""
  1468. zoomFactor = 1
  1469. cW, cH = self.GetClientSize()
  1470. cW = float(cW)
  1471. if rect.IsEmpty(): # clicked on canvas
  1472. zoomFactor = 1.5
  1473. if self.mouse['use'] == 'zoomout':
  1474. zoomFactor = 1./zoomFactor
  1475. x,y = self.mouse['begin']
  1476. xView = x - x/zoomFactor#x - cW/(zoomFactor * 2)
  1477. yView = y - y/zoomFactor#y - cH/(zoomFactor * 2)
  1478. else: #dragging
  1479. rW, rH = float(rect.GetWidth()), float(rect.GetHeight())
  1480. try:
  1481. zoomFactor = 1/max(rW/cW, rH/cH)
  1482. except ZeroDivisionError:
  1483. zoomFactor = 1
  1484. # when zooming to full extent, in some cases, there was zoom 1.01..., which causes problem
  1485. if abs(zoomFactor - 1) > 0.01:
  1486. zoomFactor = zoomFactor
  1487. else:
  1488. zoomFactor = 1.
  1489. if self.mouse['use'] == 'zoomout':
  1490. zoomFactor = min(rW/cW, rH/cH)
  1491. try:
  1492. if rW/rH > cW/cH:
  1493. yView = rect.GetY() - (rW*(cH/cW) - rH)/2
  1494. xView = rect.GetX()
  1495. if self.mouse['use'] == 'zoomout':
  1496. x,y = rect.GetX() + (rW-(cW/cH)*rH)/2, rect.GetY()
  1497. xView, yView = -x, -y
  1498. else:
  1499. xView = rect.GetX() - (rH*(cW/cH) - rW)/2
  1500. yView = rect.GetY()
  1501. if self.mouse['use'] == 'zoomout':
  1502. x,y = rect.GetX(), rect.GetY() + (rH-(cH/cW)*rW)/2
  1503. xView, yView = -x, -y
  1504. except ZeroDivisionError:
  1505. xView, yView = rect.GetX(), rect.GetY()
  1506. return zoomFactor, (int(xView), int(yView))
  1507. def Zoom(self, zoomFactor, view):
  1508. """Zoom to specified region, scroll view, redraw"""
  1509. if not self.currScale:
  1510. return
  1511. self.currScale = self.currScale*zoomFactor
  1512. if self.currScale > 10 or self.currScale < 0.1:
  1513. self.currScale = self.currScale/zoomFactor
  1514. return
  1515. if not self.preview:
  1516. # redraw paper
  1517. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  1518. pRect.OffsetXY(-view[0], -view[1])
  1519. pRect = self.ScaleRect(rect = pRect, scale = zoomFactor)
  1520. self.DrawPaper(pRect)
  1521. #redraw objects
  1522. for id in self.objectId:
  1523. type = self.instruction[id].type
  1524. if type == 'labels': # why it's here? it should not
  1525. continue
  1526. oRect = self.CanvasPaperCoordinates(
  1527. rect = self.instruction[id]['rect'], canvasToPaper = False)
  1528. if type == 'text':
  1529. coords = self.instruction[id]['coords']# recalculate coordinates, they are not equal to BB
  1530. self.instruction[id]['coords'] = coords = [(int(coord) - view[i]) * zoomFactor
  1531. for i, coord in enumerate(coords)]
  1532. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1533. if self.instruction[id]['rotate']:
  1534. rot = float(self.instruction[id]['rotate'])
  1535. else:
  1536. rot = 0
  1537. self.instruction[id]['rect'] = bounds = self.parent.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  1538. self.DrawRotText(pdc = self.pdcObj, drawId = id, textDict = self.instruction[id],
  1539. coords = coords, bounds = bounds )
  1540. self.pdcObj.SetIdBounds(id, bounds)
  1541. elif type == 'northArrow':
  1542. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1543. drawid = id, pdctype = 'bitmap', bb = oRect)
  1544. elif type in ('point', 'line', 'rectangle'):
  1545. instr = self.instruction[id]
  1546. color = self.instruction[id]['color']
  1547. width = fcolor = coords = None
  1548. if type in ('point', 'rectangle'):
  1549. fcolor = self.instruction[id]['fcolor']
  1550. if type in ('line', 'rectangle'):
  1551. width = self.instruction[id]['width']
  1552. if type in ('line'):
  1553. point1, point2 = instr['where'][0], instr['where'][1]
  1554. point1 = self.CanvasPaperCoordinates(rect = Rect2DPS(point1, (0, 0)),
  1555. canvasToPaper = False)[:2]
  1556. point2 = self.CanvasPaperCoordinates(rect = Rect2DPS(point2, (0, 0)),
  1557. canvasToPaper = False)[:2]
  1558. coords = (point1, point2)
  1559. self.DrawGraphics(drawid = id, shape = type, bb = oRect, lineCoords = coords,
  1560. color = color, fcolor = fcolor, width = width)
  1561. else:
  1562. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1563. drawid = id, pdctype = 'rectText', bb = oRect)
  1564. #redraw tmp objects
  1565. if self.dragId != -1:
  1566. self.RedrawSelectBox(self.dragId)
  1567. #redraw preview
  1568. else: # preview mode
  1569. imageRect = self.pdcImage.GetIdBounds(self.imageId)
  1570. imageRect.OffsetXY(-view[0], -view[1])
  1571. imageRect = self.ScaleRect(rect = imageRect, scale = zoomFactor)
  1572. self.DrawImage(imageRect)
  1573. def ZoomAll(self):
  1574. """Zoom to full extent"""
  1575. if not self.preview:
  1576. bounds = self.pdcPaper.GetIdBounds(self.pageId)
  1577. else:
  1578. bounds = self.pdcImage.GetIdBounds(self.imageId)
  1579. zoomP = bounds.Inflate(bounds.width/20, bounds.height/20)
  1580. zoomFactor, view = self.ComputeZoom(zoomP)
  1581. self.Zoom(zoomFactor, view)
  1582. def Draw(self, pen, brush, pdc, drawid = None, pdctype = 'rect', bb = wx.Rect(0,0,0,0), lineCoords = None):
  1583. """Draw object with given pen and brush.
  1584. :param pdc: PseudoDC
  1585. :param pdctype: 'bitmap'/'rectText'/'rect'/'point'/'line'
  1586. :param bb: bounding box
  1587. :param lineCoords: coordinates of line start, end points (wx.Point, wx.Point)
  1588. """
  1589. if drawid is None:
  1590. drawid = wx.NewId()
  1591. bb = bb.Get()
  1592. pdc.BeginDrawing()
  1593. pdc.RemoveId(drawid)
  1594. pdc.SetId(drawid)
  1595. pdc.SetPen(pen)
  1596. pdc.SetBrush(brush)
  1597. if pdctype == 'bitmap':
  1598. if havePILImage:
  1599. file = self.instruction[drawid]['epsfile']
  1600. rotation = self.instruction[drawid]['rotate']
  1601. self.DrawBitmap(pdc = pdc, filePath = file, rotation = rotation, bbox = bb)
  1602. else: # draw only rectangle with label
  1603. pdctype = 'rectText'
  1604. if pdctype in ('rect', 'rectText'):
  1605. pdc.DrawRectangle(*bb)
  1606. if pdctype == 'rectText':
  1607. dc = wx.ClientDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  1608. font = dc.GetFont()
  1609. size = 10
  1610. font.SetPointSize(size)
  1611. font.SetStyle(wx.ITALIC)
  1612. dc.SetFont(font)
  1613. pdc.SetFont(font)
  1614. text = '\n'.join(self.itemLabels[drawid])
  1615. w,h,lh = dc.GetMultiLineTextExtent(text)
  1616. textExtent = (w,h)
  1617. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1618. r = map(int, bb)
  1619. while not wx.Rect(*r).ContainsRect(textRect) and size >= 8:
  1620. size -= 2
  1621. font.SetPointSize(size)
  1622. dc.SetFont(font)
  1623. pdc.SetFont(font)
  1624. textExtent = dc.GetTextExtent(text)
  1625. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1626. pdc.SetTextForeground(wx.Colour(100,100,100,200))
  1627. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1628. pdc.DrawLabel(text = text, rect = textRect)
  1629. elif pdctype == 'point':
  1630. pdc.DrawCircle(x = bb[0] + bb[2] / 2,
  1631. y = bb[1] + bb[3] / 2,
  1632. radius = bb[2] / 2)
  1633. elif pdctype == 'line':
  1634. pdc.DrawLinePoint(lineCoords[0], lineCoords[1])
  1635. pdc.SetIdBounds(drawid, bb)
  1636. pdc.EndDrawing()
  1637. self.Refresh()
  1638. return drawid
  1639. def DrawGraphics(self, drawid, shape, color, bb, width = None, fcolor = None, lineCoords = None):
  1640. """Draw point/line/rectangle with given color and width
  1641. :param drawid: id of drawn object
  1642. :param shape: drawn shape 'point'/'line'/'rectangle'
  1643. :param color: pen outline color ('RRR:GGG:BBB')
  1644. :param fcolor: brush fill color, if meaningful ('RRR:GGG:BBB')
  1645. :param width: pen width
  1646. :param bb: bounding box
  1647. :param lineCoords: line coordinates (for line only)
  1648. """
  1649. pdctype = {'point' : 'point',
  1650. 'line' : 'line',
  1651. 'rectangle' : 'rect'}
  1652. if color == 'none':
  1653. pen = wx.TRANSPARENT_PEN
  1654. else:
  1655. if width is not None:
  1656. units = UnitConversion(self)
  1657. width = int(units.convert(value = width, fromUnit = 'point', toUnit = 'pixel') * self.currScale)
  1658. else:
  1659. width = 2
  1660. pen = wx.Pen(colour = convertRGB(color), width = width)
  1661. pen.SetCap(wx.CAP_BUTT) # this is how ps.map draws
  1662. brush = wx.TRANSPARENT_BRUSH
  1663. if fcolor and fcolor != 'none':
  1664. brush = wx.Brush(colour = convertRGB(fcolor))
  1665. self.Draw(pen = pen, brush = brush, pdc = self.pdcObj, pdctype = pdctype[shape],
  1666. drawid = drawid, bb = bb, lineCoords = lineCoords)
  1667. def DrawBitmap(self, pdc, filePath, rotation, bbox):
  1668. """Draw bitmap using PIL"""
  1669. pImg = PILImage.open(filePath)
  1670. if sys.platform == 'win32' and \
  1671. 'eps' in os.path.splitext(filePath)[1].lower():
  1672. import types
  1673. pImg.load = types.MethodType(loadPSForWindows, pImg)
  1674. if rotation:
  1675. # get rid of black background
  1676. pImg = pImg.convert("RGBA")
  1677. rot = pImg.rotate(rotation, expand = 1)
  1678. new = PILImage.new('RGBA', rot.size, (255,) * 4)
  1679. pImg = PILImage.composite(rot, new, rot)
  1680. pImg = pImg.resize((int(bbox[2]), int(bbox[3])), resample = PILImage.BICUBIC)
  1681. img = PilImageToWxImage(pImg)
  1682. bitmap = img.ConvertToBitmap()
  1683. mask = wx.Mask(bitmap, wx.WHITE)
  1684. bitmap.SetMask(mask)
  1685. pdc.DrawBitmap(bitmap, bbox[0], bbox[1], useMask = True)
  1686. def DrawRotText(self, pdc, drawId, textDict, coords, bounds):
  1687. if textDict['rotate']:
  1688. rot = float(textDict['rotate'])
  1689. else:
  1690. rot = 0
  1691. if textDict['background'] != 'none':
  1692. background = textDict['background']
  1693. else:
  1694. background = None
  1695. pdc.RemoveId(drawId)
  1696. pdc.SetId(drawId)
  1697. pdc.BeginDrawing()
  1698. # border is not redrawn when zoom changes, why?
  1699. ## if textDict['border'] != 'none' and not rot:
  1700. ## units = UnitConversion(self)
  1701. ## borderWidth = units.convert(value = textDict['width'],
  1702. ## fromUnit = 'point', toUnit = 'pixel' ) * self.currScale
  1703. ## pdc.SetPen(wx.Pen(colour = convertRGB(textDict['border']), width = borderWidth))
  1704. ## pdc.DrawRectangle(*bounds)
  1705. if background:
  1706. pdc.SetTextBackground(convertRGB(background))
  1707. pdc.SetBackgroundMode(wx.SOLID)
  1708. else:
  1709. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1710. fn = self.parent.makePSFont(textDict)
  1711. pdc.SetFont(fn)
  1712. pdc.SetTextForeground(convertRGB(textDict['color']))
  1713. if rot == 0:
  1714. pdc.DrawLabel(text=textDict['text'], rect=bounds)
  1715. else:
  1716. pdc.DrawRotatedText(textDict['text'], coords[0], coords[1], rot)
  1717. pdc.SetIdBounds(drawId, wx.Rect(*bounds))
  1718. self.Refresh()
  1719. pdc.EndDrawing()
  1720. def DrawImage(self, rect):
  1721. """Draw preview image to pseudoDC"""
  1722. self.pdcImage.ClearId(self.imageId)
  1723. self.pdcImage.SetId(self.imageId)
  1724. img = self.image
  1725. if img.GetWidth() != rect.width or img.GetHeight() != rect.height:
  1726. img = img.Scale(rect.width, rect.height)
  1727. bitmap = img.ConvertToBitmap()
  1728. self.pdcImage.BeginDrawing()
  1729. self.pdcImage.DrawBitmap(bitmap, rect.x, rect.y)
  1730. self.pdcImage.SetIdBounds(self.imageId, rect)
  1731. self.pdcImage.EndDrawing()
  1732. self.Refresh()
  1733. def DrawPaper(self, rect):
  1734. """Draw paper and margins"""
  1735. page = self.instruction[self.pageId]
  1736. scale = page['Width'] / rect.GetWidth()
  1737. w = (page['Width'] - page['Right'] - page['Left']) / scale
  1738. h = (page['Height'] - page['Top'] - page['Bottom']) / scale
  1739. x = page['Left'] / scale + rect.GetX()
  1740. y = page['Top'] / scale + rect.GetY()
  1741. self.pdcPaper.BeginDrawing()
  1742. self.pdcPaper.RemoveId(self.pageId)
  1743. self.pdcPaper.SetId(self.pageId)
  1744. self.pdcPaper.SetPen(self.pen['paper'])
  1745. self.pdcPaper.SetBrush(self.brush['paper'])
  1746. self.pdcPaper.DrawRectangleRect(rect)
  1747. self.pdcPaper.SetPen(self.pen['margins'])
  1748. self.pdcPaper.SetBrush(self.brush['margins'])
  1749. self.pdcPaper.DrawRectangle(x, y, w, h)
  1750. self.pdcPaper.SetIdBounds(self.pageId, rect)
  1751. self.pdcPaper.EndDrawing()
  1752. self.Refresh()
  1753. def ImageRect(self):
  1754. """Returns image centered in canvas, computes scale"""
  1755. img = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  1756. cW, cH = self.GetClientSize()
  1757. iW, iH = img.GetWidth(), img.GetHeight()
  1758. self.currScale = min(float(cW)/iW, float(cH)/iH)
  1759. iW = iW * self.currScale
  1760. iH = iH * self.currScale
  1761. x = cW/2 - iW/2
  1762. y = cH/2 - iH/2
  1763. imageRect = wx.Rect(x, y, iW, iH)
  1764. return imageRect
  1765. def RedrawSelectBox(self, id):
  1766. """Redraws select box when selected object changes its size"""
  1767. if self.dragId == id:
  1768. rect = self.pdcObj.GetIdBounds(id)
  1769. if self.instruction[id].type != 'line':
  1770. rect = rect.Inflate(3,3)
  1771. # draw select box around object
  1772. self.Draw(pen = self.pen['select'], brush = self.brush['select'], pdc = self.pdcTmp,
  1773. drawid = self.idBoxTmp, pdctype = 'rect', bb = rect)
  1774. # draw small marks signalizing resizing
  1775. if self.instruction[id].type in ('map', 'rectangle'):
  1776. controlP = self.pdcObj.GetIdBounds(id).GetBottomRight()
  1777. rect = wx.RectPS(controlP, self.resizeBoxSize)
  1778. self.Draw(pen = self.pen['resize'], brush = self.brush['resize'], pdc = self.pdcTmp,
  1779. drawid = self.idResizeBoxTmp, pdctype = 'rect', bb = rect)
  1780. elif self.instruction[id].type == 'line':
  1781. p1Paper = self.instruction[id]['where'][0]
  1782. p2Paper = self.instruction[id]['where'][1]
  1783. p1Canvas = self.CanvasPaperCoordinates(rect = Rect2DPS(p1Paper, (0, 0)), canvasToPaper = False)[:2]
  1784. p2Canvas = self.CanvasPaperCoordinates(rect = Rect2DPS(p2Paper, (0, 0)), canvasToPaper = False)[:2]
  1785. rect = []
  1786. box = wx.RectS(self.resizeBoxSize)
  1787. rect.append(box.CenterIn(wx.RectPS(p1Canvas, wx.Size())))
  1788. rect.append(box.CenterIn(wx.RectPS(p2Canvas, wx.Size())))
  1789. for i, point in enumerate((p1Canvas, p2Canvas)):
  1790. self.Draw(pen = self.pen['resize'], brush = self.brush['resize'], pdc = self.pdcTmp,
  1791. drawid = self.idLinePointsTmp[i], pdctype = 'rect', bb = rect[i])
  1792. def UpdateMapLabel(self):
  1793. """Updates map frame label"""
  1794. vector = self.instruction.FindInstructionByType('vector')
  1795. if vector:
  1796. vectorId = vector.id
  1797. else:
  1798. vectorId = None
  1799. raster = self.instruction.FindInstructionByType('raster')
  1800. if raster:
  1801. rasterId = raster.id
  1802. else:
  1803. rasterId = None
  1804. rasterName = 'None'
  1805. if rasterId:
  1806. rasterName = self.instruction[rasterId]['raster'].split('@')[0]
  1807. mapId = self.instruction.FindInstructionByType('map').id
  1808. self.itemLabels[mapId] = []
  1809. self.itemLabels[mapId].append(self.itemLabelsDict['map'])
  1810. self.itemLabels[mapId].append("raster: " + rasterName)
  1811. if vectorId:
  1812. for map in self.instruction[vectorId]['list']:
  1813. self.itemLabels[mapId].append('vector: ' + map[0].split('@')[0])
  1814. labels = self.instruction.FindInstructionByType('labels')
  1815. if labels:
  1816. labelFiles = self.instruction[labels.id]['labels']
  1817. if not labelFiles:
  1818. return
  1819. labelFiles = [lFile.split('@')[0] for lFile in labelFiles]
  1820. self.itemLabels[mapId].append(_("labels: ") + ', '.join(labelFiles))
  1821. def UpdateLabel(self, itype, id):
  1822. self.itemLabels[id] = []
  1823. self.itemLabels[id].append(self.itemLabelsDict[itype])
  1824. if itype == 'image':
  1825. file = os.path.basename(self.instruction[id]['epsfile'])
  1826. self.itemLabels[id].append(file)
  1827. def OnSize(self, event):
  1828. """Init image size to match window size
  1829. """
  1830. # not zoom all when notebook page is changed
  1831. if self.preview and self.parent.currentPage == 1 or not self.preview and self.parent.currentPage == 0:
  1832. self.ZoomAll()
  1833. self.OnIdle(None)
  1834. event.Skip()
  1835. def OnIdle(self, event):
  1836. """Only re-render a image during idle time instead of
  1837. multiple times during resizing.
  1838. """
  1839. width, height = self.GetClientSize()
  1840. # Make new off screen bitmap: this bitmap will always have the
  1841. # current drawing in it, so it can be used to save the image
  1842. # to a file, or whatever.
  1843. self._buffer = wx.EmptyBitmap(width, height)
  1844. # re-render image on idle
  1845. self.resize = True
  1846. def ScaleRect(self, rect, scale):
  1847. """Scale rectangle"""
  1848. return wx.Rect(rect.GetLeft()*scale, rect.GetTop()*scale,
  1849. rect.GetSize()[0]*scale, rect.GetSize()[1]*scale)