frame.py 93 KB

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