frame.py 93 KB

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