frame.py 93 KB

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