frame.py 95 KB

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