frame.py 93 KB

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