frame.py 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803
  1. """!
  2. @package psmap.frame
  3. @brief GUI for ps.map
  4. Classes:
  5. - frame::PsMapFrame
  6. - frame::PsMapBufferedWindow
  7. (C) 2011 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
  18. try:
  19. import Image as PILImage
  20. havePILImage = True
  21. except ImportError:
  22. havePILImage = False
  23. import wx
  24. try:
  25. import wx.lib.agw.flatnotebook as fnb
  26. except ImportError:
  27. import wx.lib.flatnotebook as fnb
  28. import grass.script as grass
  29. from core import globalvar
  30. from gui_core.menu import Menu
  31. from gui_core.goutput import CmdThread, EVT_CMD_DONE
  32. from psmap.toolbars import PsMapToolbar
  33. from icon import Icons, MetaIcon, iconSet
  34. from core.gcmd import RunCommand, GError, GMessage
  35. from gui_core.forms import GUI
  36. from psmap.menudata import PsMapData
  37. from psmap.dialogs import *
  38. class PsMapFrame(wx.Frame):
  39. def __init__(self, parent = None, id = wx.ID_ANY,
  40. title = _("GRASS GIS Cartographic Composer"), **kwargs):
  41. """!Main window of ps.map GUI
  42. @param parent parent window
  43. @param id window id
  44. @param title window title
  45. @param kwargs wx.Frames' arguments
  46. """
  47. self.parent = parent
  48. wx.Frame.__init__(self, parent = parent, id = id, title = title, name = "PsMap", **kwargs)
  49. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  50. #menubar
  51. self.menubar = Menu(parent = self, data = PsMapData())
  52. self.SetMenuBar(self.menubar)
  53. #toolbar
  54. self.toolbar = PsMapToolbar(parent = self)
  55. self.SetToolBar(self.toolbar)
  56. self.actionOld = self.toolbar.action['id']
  57. self.iconsize = (16, 16)
  58. #satusbar
  59. self.statusbar = self.CreateStatusBar(number = 1)
  60. # mouse attributes -- position on the screen, begin and end of
  61. # dragging, and type of drawing
  62. self.mouse = {
  63. 'begin': [0, 0], # screen coordinates
  64. 'end' : [0, 0],
  65. 'use' : "pointer",
  66. }
  67. # available cursors
  68. self.cursors = {
  69. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  70. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  71. "hand" : wx.StockCursor(wx.CURSOR_HAND),
  72. "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
  73. }
  74. # pen and brush
  75. self.pen = {
  76. 'paper': wx.Pen(colour = "BLACK", width = 1),
  77. 'margins': wx.Pen(colour = "GREY", width = 1),
  78. 'map': wx.Pen(colour = wx.Color(86, 122, 17), width = 2),
  79. 'rasterLegend': wx.Pen(colour = wx.Color(219, 216, 4), width = 2),
  80. 'vectorLegend': wx.Pen(colour = wx.Color(219, 216, 4), width = 2),
  81. 'mapinfo': wx.Pen(colour = wx.Color(5, 184, 249), width = 2),
  82. 'scalebar': wx.Pen(colour = wx.Color(150, 150, 150), width = 2),
  83. 'image': wx.Pen(colour = wx.Color(255, 150, 50), width = 2),
  84. 'northArrow': wx.Pen(colour = wx.Color(200, 200, 200), width = 2),
  85. 'box': wx.Pen(colour = 'RED', width = 2, style = wx.SHORT_DASH),
  86. 'select': wx.Pen(colour = 'BLACK', width = 1, style = wx.SHORT_DASH),
  87. 'resize': wx.Pen(colour = 'BLACK', width = 1)
  88. }
  89. self.brush = {
  90. 'paper': wx.WHITE_BRUSH,
  91. 'margins': wx.TRANSPARENT_BRUSH,
  92. 'map': wx.Brush(wx.Color(151, 214, 90)),
  93. 'rasterLegend': wx.Brush(wx.Color(250, 247, 112)),
  94. 'vectorLegend': wx.Brush(wx.Color(250, 247, 112)),
  95. 'mapinfo': wx.Brush(wx.Color(127, 222, 252)),
  96. 'scalebar': wx.Brush(wx.Color(200, 200, 200)),
  97. 'image': wx.Brush(wx.Color(255, 200, 50)),
  98. 'northArrow': wx.Brush(wx.Color(255, 255, 255)),
  99. 'box': wx.TRANSPARENT_BRUSH,
  100. 'select':wx.TRANSPARENT_BRUSH,
  101. 'resize': wx.BLACK_BRUSH
  102. }
  103. # list of objects to draw
  104. self.objectId = []
  105. # instructions
  106. self.instruction = Instruction(parent = self, objectsToDraw = self.objectId)
  107. # open dialogs
  108. self.openDialogs = dict()
  109. self.pageId = wx.NewId()
  110. #current page of flatnotebook
  111. self.currentPage = 0
  112. #canvas for draft mode
  113. self.canvas = PsMapBufferedWindow(parent = self, mouse = self.mouse, pen = self.pen,
  114. brush = self.brush, cursors = self.cursors,
  115. instruction = self.instruction, openDialogs = self.openDialogs,
  116. pageId = self.pageId, objectId = self.objectId,
  117. preview = False)
  118. self.canvas.SetCursor(self.cursors["default"])
  119. self.getInitMap()
  120. # image path
  121. env = grass.gisenv()
  122. self.imgName = os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'], '.tmp', 'tmpImage.png')
  123. #canvas for preview
  124. self.previewCanvas = PsMapBufferedWindow(parent = self, mouse = self.mouse, cursors = self.cursors,
  125. pen = self.pen, brush = self.brush, preview = True)
  126. # set WIND_OVERRIDE
  127. grass.use_temp_region()
  128. # create queues
  129. self.requestQ = Queue.Queue()
  130. self.resultQ = Queue.Queue()
  131. # thread
  132. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  133. self._layout()
  134. self.SetMinSize(wx.Size(750, 600))
  135. self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
  136. self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
  137. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  138. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  139. if not havePILImage:
  140. wx.CallAfter(self._showErrMsg)
  141. def _showErrMsg(self):
  142. """!Show error message (missing preview)
  143. """
  144. GError(parent = self,
  145. message = _("Python Imaging Library is not available.\n"
  146. "'Preview' functionality won't work."),
  147. showTraceback = False)
  148. def _layout(self):
  149. """!Do layout
  150. """
  151. mainSizer = wx.BoxSizer(wx.VERTICAL)
  152. if globalvar.hasAgw:
  153. self.book = fnb.FlatNotebook(parent = self, id = wx.ID_ANY,
  154. agwStyle = fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
  155. fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
  156. else:
  157. self.book = fnb.FlatNotebook(parent = self, id = wx.ID_ANY,
  158. style = fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
  159. fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
  160. #self.book = fnb.FlatNotebook(self, wx.ID_ANY, style = fnb.FNB_BOTTOM)
  161. self.book.AddPage(self.canvas, "Draft mode")
  162. self.book.AddPage(self.previewCanvas, "Preview")
  163. self.book.SetSelection(0)
  164. mainSizer.Add(self.book,1, wx.EXPAND)
  165. self.SetSizer(mainSizer)
  166. mainSizer.Fit(self)
  167. def InstructionFile(self):
  168. """!Creates mapping instructions"""
  169. return str(self.instruction)
  170. def OnPSFile(self, event):
  171. """!Generate PostScript"""
  172. filename = self.getFile(wildcard = "PostScript (*.ps)|*.ps|Encapsulated PostScript (*.eps)|*.eps")
  173. if filename:
  174. self.PSFile(filename)
  175. def OnPsMapDialog(self, event):
  176. """!Launch ps.map dialog
  177. """
  178. GUI(parent = self).ParseCommand(cmd = ['ps.map'])
  179. def OnPDFFile(self, event):
  180. """!Generate PDF from PS with ps2pdf if available"""
  181. try:
  182. p = grass.Popen(["ps2pdf"], stderr = grass.PIPE)
  183. p.stderr.close()
  184. except OSError:
  185. GMessage(parent = self,
  186. message = _("Program ps2pdf is not available. Please install it first to create PDF."))
  187. return
  188. filename = self.getFile(wildcard = "PDF (*.pdf)|*.pdf")
  189. if filename:
  190. self.PSFile(filename, pdf = True)
  191. def OnPreview(self, event):
  192. """!Run ps.map and show result"""
  193. self.PSFile()
  194. def PSFile(self, filename = None, pdf = False):
  195. """!Create temporary instructions file and run ps.map with output = filename"""
  196. instrFile = grass.tempfile()
  197. instrFileFd = open(instrFile, mode = 'w')
  198. instrFileFd.write(self.InstructionFile())
  199. instrFileFd.flush()
  200. instrFileFd.close()
  201. temp = False
  202. regOld = grass.region()
  203. if pdf:
  204. pdfname = filename
  205. else:
  206. pdfname = None
  207. #preview or pdf
  208. if not filename or (filename and pdf):
  209. temp = True
  210. filename = grass.tempfile()
  211. if not pdf: # lower resolution for preview
  212. if self.instruction.FindInstructionByType('map'):
  213. mapId = self.instruction.FindInstructionByType('map').id
  214. SetResolution(dpi = 100, width = self.instruction[mapId]['rect'][2],
  215. height = self.instruction[mapId]['rect'][3])
  216. cmd = ['ps.map', '--overwrite']
  217. if os.path.splitext(filename)[1] == '.eps':
  218. cmd.append('-e')
  219. if self.instruction[self.pageId]['Orientation'] == 'Landscape':
  220. cmd.append('-r')
  221. cmd.append('input=%s' % instrFile)
  222. cmd.append('output=%s' % filename)
  223. if pdf:
  224. self.SetStatusText(_('Generating PDF...'), 0)
  225. elif not temp:
  226. self.SetStatusText(_('Generating PostScript...'), 0)
  227. else:
  228. self.SetStatusText(_('Generating preview...'), 0)
  229. self.cmdThread.RunCmd(cmd, userData = {'instrFile' : instrFile, 'filename' : filename,
  230. 'pdfname' : pdfname, 'temp' : temp, 'regionOld' : regOld})
  231. def OnCmdDone(self, event):
  232. """!ps.map process finished"""
  233. if event.returncode != 0:
  234. GMessage(parent = self,
  235. message = _("Ps.map exited with return code %s") % event.returncode)
  236. grass.try_remove(event.userData['instrFile'])
  237. if event.userData['temp']:
  238. grass.try_remove(event.userData['filename'])
  239. return
  240. if event.userData['pdfname']:
  241. try:
  242. proc = grass.Popen(['ps2pdf', '-dPDFSETTINGS=/prepress', '-r1200',
  243. event.userData['filename'], event.userData['pdfname']])
  244. ret = proc.wait()
  245. if ret > 0:
  246. GMessage(parent = self,
  247. message = _("ps2pdf exited with return code %s") % ret)
  248. except OSError, e:
  249. GError(parent = self,
  250. message = _("Program ps2pdf is not available. Please install it to create PDF.\n\n %s") % e)
  251. # show preview only when user doesn't want to create ps or pdf
  252. if havePILImage and event.userData['temp'] and not event.userData['pdfname']:
  253. RunCommand('g.region', cols = event.userData['regionOld']['cols'], rows = event.userData['regionOld']['rows'])
  254. ## wx.BusyInfo does not display the message
  255. ## busy = wx.BusyInfo(message = "Generating preview, wait please", parent = self)
  256. try:
  257. im = PILImage.open(event.userData['filename'])
  258. if self.instruction[self.pageId]['Orientation'] == 'Landscape':
  259. im = im.rotate(270)
  260. im.save(self.imgName, format = 'png')
  261. except IOError, e:
  262. GError(parent = self,
  263. message = _("Unable to generate preview. %s") % e)
  264. rect = self.previewCanvas.ImageRect()
  265. self.previewCanvas.image = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  266. self.previewCanvas.DrawImage(rect = rect)
  267. ## busy.Destroy()
  268. self.SetStatusText(_('Preview generated'), 0)
  269. self.book.SetSelection(1)
  270. self.currentPage = 1
  271. grass.try_remove(event.userData['instrFile'])
  272. if event.userData['temp']:
  273. grass.try_remove(event.userData['filename'])
  274. def getFile(self, wildcard):
  275. suffix = []
  276. for filter in wildcard.split('|')[1::2]:
  277. s = filter.strip('*').split('.')[1]
  278. if s:
  279. s = '.' + s
  280. suffix.append(s)
  281. raster = self.instruction.FindInstructionByType('raster')
  282. if raster:
  283. rasterId = raster.id
  284. else:
  285. rasterId = None
  286. if rasterId and self.instruction[rasterId]['raster']:
  287. mapName = self.instruction[rasterId]['raster'].split('@')[0] + suffix[0]
  288. else:
  289. mapName = ''
  290. filename = ''
  291. dlg = wx.FileDialog(self, message = _("Save file as"), defaultDir = "",
  292. defaultFile = mapName, wildcard = wildcard,
  293. style = wx.CHANGE_DIR | wx.SAVE | wx.OVERWRITE_PROMPT)
  294. if dlg.ShowModal() == wx.ID_OK:
  295. filename = dlg.GetPath()
  296. suffix = suffix[dlg.GetFilterIndex()]
  297. if not os.path.splitext(filename)[1]:
  298. filename = filename + suffix
  299. elif os.path.splitext(filename)[1] != suffix and suffix != '':
  300. filename = os.path.splitext(filename)[0] + suffix
  301. dlg.Destroy()
  302. return filename
  303. def OnInstructionFile(self, event):
  304. filename = self.getFile(wildcard = "*.psmap|*.psmap|Text file(*.txt)|*.txt|All files(*.*)|*.*")
  305. if filename:
  306. instrFile = open(filename, "w")
  307. instrFile.write(self.InstructionFile())
  308. instrFile.close()
  309. def OnLoadFile(self, event):
  310. """!Load file and read instructions"""
  311. #find file
  312. filename = ''
  313. dlg = wx.FileDialog(self, message = "Find instructions file", defaultDir = "",
  314. defaultFile = '', wildcard = "All files (*.*)|*.*",
  315. style = wx.CHANGE_DIR|wx.OPEN)
  316. if dlg.ShowModal() == wx.ID_OK:
  317. filename = dlg.GetPath()
  318. dlg.Destroy()
  319. if not filename:
  320. return
  321. # load instructions
  322. readObjectId = []
  323. readInstruction = Instruction(parent = self, objectsToDraw = readObjectId)
  324. ok = readInstruction.Read(filename)
  325. if not ok:
  326. GMessage(_("Failed to read file %s.") % filename)
  327. else:
  328. self.instruction = self.canvas.instruction = readInstruction
  329. self.objectId = self.canvas.objectId = readObjectId
  330. self.pageId = self.canvas.pageId = self.instruction.FindInstructionByType('page').id
  331. self.canvas.UpdateMapLabel()
  332. self.canvas.dragId = -1
  333. self.canvas.Clear()
  334. self.canvas.SetPage()
  335. #self.canvas.ZoomAll()
  336. self.DialogDataChanged(self.objectId)
  337. def OnPageSetup(self, event = None):
  338. """!Specify paper size, margins and orientation"""
  339. id = self.instruction.FindInstructionByType('page').id
  340. dlg = PageSetupDialog(self, id = id, settings = self.instruction)
  341. dlg.CenterOnScreen()
  342. val = dlg.ShowModal()
  343. if val == wx.ID_OK:
  344. self.canvas.SetPage()
  345. self.getInitMap()
  346. self.canvas.RecalculatePosition(ids = self.objectId)
  347. dlg.Destroy()
  348. def OnPointer(self, event):
  349. self.toolbar.OnTool(event)
  350. self.mouse["use"] = "pointer"
  351. self.canvas.SetCursor(self.cursors["default"])
  352. self.previewCanvas.SetCursor(self.cursors["default"])
  353. def OnPan(self, event):
  354. self.toolbar.OnTool(event)
  355. self.mouse["use"] = "pan"
  356. self.canvas.SetCursor(self.cursors["hand"])
  357. self.previewCanvas.SetCursor(self.cursors["hand"])
  358. def OnZoomIn(self, event):
  359. self.toolbar.OnTool(event)
  360. self.mouse["use"] = "zoomin"
  361. self.canvas.SetCursor(self.cursors["cross"])
  362. self.previewCanvas.SetCursor(self.cursors["cross"])
  363. def OnZoomOut(self, event):
  364. self.toolbar.OnTool(event)
  365. self.mouse["use"] = "zoomout"
  366. self.canvas.SetCursor(self.cursors["cross"])
  367. self.previewCanvas.SetCursor(self.cursors["cross"])
  368. def OnZoomAll(self, event):
  369. self.mouseOld = self.mouse['use']
  370. if self.currentPage == 0:
  371. self.cursorOld = self.canvas.GetCursor()
  372. else:
  373. self.cursorOld = self.previewCanvas.GetCursor()
  374. self.previewCanvas.GetCursor()
  375. self.mouse["use"] = "zoomin"
  376. if self.currentPage == 0:
  377. self.canvas.ZoomAll()
  378. else:
  379. self.previewCanvas.ZoomAll()
  380. self.mouse["use"] = self.mouseOld
  381. if self.currentPage == 0:
  382. self.canvas.SetCursor(self.cursorOld)
  383. else:
  384. self.previewCanvas.SetCursor(self.cursorOld)
  385. def OnAddMap(self, event, notebook = False):
  386. """!Add or edit map frame"""
  387. if event is not None:
  388. if event.GetId() != self.toolbar.action['id']:
  389. self.actionOld = self.toolbar.action['id']
  390. self.mouseOld = self.mouse['use']
  391. self.cursorOld = self.canvas.GetCursor()
  392. self.toolbar.OnTool(event)
  393. if self.instruction.FindInstructionByType('map'):
  394. mapId = self.instruction.FindInstructionByType('map').id
  395. else: mapId = None
  396. id = [mapId, None, None]
  397. if notebook:
  398. if self.instruction.FindInstructionByType('vector'):
  399. vectorId = self.instruction.FindInstructionByType('vector').id
  400. else: vectorId = None
  401. if self.instruction.FindInstructionByType('raster'):
  402. rasterId = self.instruction.FindInstructionByType('raster').id
  403. else: rasterId = None
  404. id[1] = rasterId
  405. id[2] = vectorId
  406. if mapId: # map exists
  407. self.toolbar.ToggleTool(self.actionOld, True)
  408. self.toolbar.ToggleTool(self.toolbar.action['id'], False)
  409. self.toolbar.action['id'] = self.actionOld
  410. try:
  411. self.canvas.SetCursor(self.cursorOld)
  412. except AttributeError:
  413. pass
  414. ## dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  415. ## notebook = notebook)
  416. ## dlg.ShowModal()
  417. if notebook:
  418. #check map, raster, vector and save, destroy them
  419. if 'map' in self.openDialogs:
  420. self.openDialogs['map'].OnOK(event = None)
  421. if 'raster' in self.openDialogs:
  422. self.openDialogs['raster'].OnOK(event = None)
  423. if 'vector' in self.openDialogs:
  424. self.openDialogs['vector'].OnOK(event = None)
  425. if 'mapNotebook' not in self.openDialogs:
  426. dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  427. notebook = notebook)
  428. self.openDialogs['mapNotebook'] = dlg
  429. self.openDialogs['mapNotebook'].Show()
  430. else:
  431. if 'mapNotebook' in self.openDialogs:
  432. self.openDialogs['mapNotebook'].notebook.ChangeSelection(0)
  433. else:
  434. if 'map' not in self.openDialogs:
  435. dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  436. notebook = notebook)
  437. self.openDialogs['map'] = dlg
  438. self.openDialogs['map'].Show()
  439. else: # sofar no map
  440. self.mouse["use"] = "addMap"
  441. self.canvas.SetCursor(self.cursors["cross"])
  442. if self.currentPage == 1:
  443. self.book.SetSelection(0)
  444. self.currentPage = 0
  445. def OnAddRaster(self, event):
  446. """!Add raster map"""
  447. if self.instruction.FindInstructionByType('raster'):
  448. id = self.instruction.FindInstructionByType('raster').id
  449. else: id = None
  450. if self.instruction.FindInstructionByType('map'):
  451. mapId = self.instruction.FindInstructionByType('map').id
  452. else: mapId = None
  453. if not id:
  454. if not mapId:
  455. GMessage(message = _("Please, create map frame first."))
  456. return
  457. ## dlg = RasterDialog(self, id = id, settings = self.instruction)
  458. ## dlg.ShowModal()
  459. if 'mapNotebook' in self.openDialogs:
  460. self.openDialogs['mapNotebook'].notebook.ChangeSelection(1)
  461. else:
  462. if 'raster' not in self.openDialogs:
  463. dlg = RasterDialog(self, id = id, settings = self.instruction)
  464. self.openDialogs['raster'] = dlg
  465. self.openDialogs['raster'].Show()
  466. def OnAddVect(self, event):
  467. """!Add vector map"""
  468. if self.instruction.FindInstructionByType('vector'):
  469. id = self.instruction.FindInstructionByType('vector').id
  470. else: id = None
  471. if self.instruction.FindInstructionByType('map'):
  472. mapId = self.instruction.FindInstructionByType('map').id
  473. else: mapId = None
  474. if not id:
  475. if not mapId:
  476. GMessage(message = _("Please, create map frame first."))
  477. return
  478. ## dlg = MainVectorDialog(self, id = id, settings = self.instruction)
  479. ## dlg.ShowModal()
  480. if 'mapNotebook' in self.openDialogs:
  481. self.openDialogs['mapNotebook'].notebook.ChangeSelection(2)
  482. else:
  483. if 'vector' not in self.openDialogs:
  484. dlg = MainVectorDialog(self, id = id, settings = self.instruction)
  485. self.openDialogs['vector'] = dlg
  486. self.openDialogs['vector'].Show()
  487. def OnDecoration(self, event):
  488. """!Decorations overlay menu
  489. """
  490. decmenu = wx.Menu()
  491. # legend
  492. AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, Icons['psMap']["addLegend"].GetLabel())
  493. AddLegend.SetBitmap(Icons['psMap']["addLegend"].GetBitmap(self.iconsize))
  494. decmenu.AppendItem(AddLegend)
  495. self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
  496. # mapinfo
  497. AddMapinfo = wx.MenuItem(decmenu, wx.ID_ANY, Icons['psMap']["addMapinfo"].GetLabel())
  498. AddMapinfo.SetBitmap(Icons['psMap']["addMapinfo"].GetBitmap(self.iconsize))
  499. decmenu.AppendItem(AddMapinfo)
  500. self.Bind(wx.EVT_MENU, self.OnAddMapinfo, AddMapinfo)
  501. # scalebar
  502. AddScalebar = wx.MenuItem(decmenu, wx.ID_ANY, Icons['psMap']["addScalebar"].GetLabel())
  503. AddScalebar.SetBitmap(Icons['psMap']["addScalebar"].GetBitmap(self.iconsize))
  504. decmenu.AppendItem(AddScalebar)
  505. self.Bind(wx.EVT_MENU, self.OnAddScalebar, AddScalebar)
  506. # text
  507. AddText = wx.MenuItem(decmenu, wx.ID_ANY, Icons['psMap']["addText"].GetLabel())
  508. AddText.SetBitmap(Icons['psMap']["addText"].GetBitmap(self.iconsize))
  509. decmenu.AppendItem(AddText)
  510. self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
  511. # eps image
  512. AddImage = wx.MenuItem(decmenu, wx.ID_ANY, Icons['psMap']["addImage"].GetLabel())
  513. AddImage.SetBitmap(Icons['psMap']["addImage"].GetBitmap(self.iconsize))
  514. decmenu.AppendItem(AddImage)
  515. self.Bind(wx.EVT_MENU, self.OnAddImage, AddImage)
  516. # north arrow image
  517. AddNorthArrow = wx.MenuItem(decmenu, wx.ID_ANY, _("North arrow"))
  518. AddNorthArrow.SetBitmap(wx.ArtProvider.GetBitmap(id = wx.ART_MISSING_IMAGE,
  519. client = wx.ART_MENU, size = self.iconsize))
  520. decmenu.AppendItem(AddNorthArrow)
  521. self.Bind(wx.EVT_MENU, self.OnAddNorthArrow, AddNorthArrow)
  522. # Popup the menu. If an item is selected then its handler
  523. # will be called before PopupMenu returns.
  524. self.PopupMenu(decmenu)
  525. decmenu.Destroy()
  526. def OnAddScalebar(self, event):
  527. """!Add scalebar"""
  528. if projInfo()['proj'] == 'll':
  529. GMessage(message = _("Scalebar is not appropriate for this projection"))
  530. return
  531. if self.instruction.FindInstructionByType('scalebar'):
  532. id = self.instruction.FindInstructionByType('scalebar').id
  533. else: id = None
  534. if 'scalebar' not in self.openDialogs:
  535. dlg = ScalebarDialog(self, id = id, settings = self.instruction)
  536. self.openDialogs['scalebar'] = dlg
  537. self.openDialogs['scalebar'].Show()
  538. def OnAddLegend(self, event, page = 0):
  539. """!Add raster or vector legend"""
  540. if self.instruction.FindInstructionByType('rasterLegend'):
  541. idR = self.instruction.FindInstructionByType('rasterLegend').id
  542. else: idR = None
  543. if self.instruction.FindInstructionByType('vectorLegend'):
  544. idV = self.instruction.FindInstructionByType('vectorLegend').id
  545. else: idV = None
  546. if 'rasterLegend' not in self.openDialogs:
  547. dlg = LegendDialog(self, id = [idR, idV], settings = self.instruction, page = page)
  548. self.openDialogs['rasterLegend'] = dlg
  549. self.openDialogs['vectorLegend'] = dlg
  550. self.openDialogs['rasterLegend'].notebook.ChangeSelection(page)
  551. self.openDialogs['rasterLegend'].Show()
  552. def OnAddMapinfo(self, event):
  553. if self.instruction.FindInstructionByType('mapinfo'):
  554. id = self.instruction.FindInstructionByType('mapinfo').id
  555. else: id = None
  556. if 'mapinfo' not in self.openDialogs:
  557. dlg = MapinfoDialog(self, id = id, settings = self.instruction)
  558. self.openDialogs['mapinfo'] = dlg
  559. self.openDialogs['mapinfo'].Show()
  560. def OnAddImage(self, event, id = None):
  561. """!Show dialog for image adding and editing"""
  562. position = None
  563. if 'image' in self.openDialogs:
  564. position = self.openDialogs['image'].GetPosition()
  565. self.openDialogs['image'].OnApply(event = None)
  566. self.openDialogs['image'].Destroy()
  567. dlg = ImageDialog(self, id = id, settings = self.instruction)
  568. self.openDialogs['image'] = dlg
  569. if position:
  570. dlg.SetPosition(position)
  571. dlg.Show()
  572. def OnAddNorthArrow(self, event, id = None):
  573. """!Show dialog for north arrow adding and editing"""
  574. if self.instruction.FindInstructionByType('northArrow'):
  575. id = self.instruction.FindInstructionByType('northArrow').id
  576. else: id = None
  577. if 'northArrow' not in self.openDialogs:
  578. dlg = NorthArrowDialog(self, id = id, settings = self.instruction)
  579. self.openDialogs['northArrow'] = dlg
  580. self.openDialogs['northArrow'].Show()
  581. def OnAddText(self, event, id = None):
  582. """!Show dialog for text adding and editing"""
  583. position = None
  584. if 'text' in self.openDialogs:
  585. position = self.openDialogs['text'].GetPosition()
  586. self.openDialogs['text'].OnApply(event = None)
  587. self.openDialogs['text'].Destroy()
  588. dlg = TextDialog(self, id = id, settings = self.instruction)
  589. self.openDialogs['text'] = dlg
  590. if position:
  591. dlg.SetPosition(position)
  592. dlg.Show()
  593. def getModifiedTextBounds(self, x, y, textExtent, rotation):
  594. """!computes bounding box of rotated text, not very precisely"""
  595. w, h = textExtent
  596. rotation = float(rotation)/180*pi
  597. H = float(w) * sin(rotation)
  598. W = float(w) * cos(rotation)
  599. X, Y = x, y
  600. if pi/2 < rotation <= 3*pi/2:
  601. X = x + W
  602. if 0 < rotation < pi:
  603. Y = y - H
  604. if rotation == 0:
  605. return wx.Rect(x,y, *textExtent)
  606. else:
  607. return wx.Rect(X, Y, abs(W), abs(H)).Inflate(h,h)
  608. def makePSFont(self, textDict):
  609. """!creates a wx.Font object from selected postscript font. To be
  610. used for estimating bounding rectangle of text"""
  611. fontsize = textDict['fontsize'] * self.canvas.currScale
  612. fontface = textDict['font'].split('-')[0]
  613. try:
  614. fontstyle = textDict['font'].split('-')[1]
  615. except IndexError:
  616. fontstyle = ''
  617. if fontface == "Times":
  618. family = wx.FONTFAMILY_ROMAN
  619. face = "times"
  620. elif fontface == "Helvetica":
  621. family = wx.FONTFAMILY_SWISS
  622. face = 'helvetica'
  623. elif fontface == "Courier":
  624. family = wx.FONTFAMILY_TELETYPE
  625. face = 'courier'
  626. else:
  627. family = wx.FONTFAMILY_DEFAULT
  628. face = ''
  629. style = wx.FONTSTYLE_NORMAL
  630. weight = wx.FONTWEIGHT_NORMAL
  631. if 'Oblique' in fontstyle:
  632. style = wx.FONTSTYLE_SLANT
  633. if 'Italic' in fontstyle:
  634. style = wx.FONTSTYLE_ITALIC
  635. if 'Bold' in fontstyle:
  636. weight = wx.FONTWEIGHT_BOLD
  637. try:
  638. fn = wx.Font(pointSize = fontsize, family = family, style = style,
  639. weight = weight, face = face)
  640. except:
  641. fn = wx.Font(pointSize = fontsize, family = wx.FONTFAMILY_DEFAULT,
  642. style = wx.FONTSTYLE_NORMAL, weight = wx.FONTWEIGHT_NORMAL)
  643. return fn
  644. def getTextExtent(self, textDict):
  645. """!Estimates bounding rectangle of text"""
  646. #fontsize = str(fontsize if fontsize >= 4 else 4)
  647. dc = wx.PaintDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  648. fn = self.makePSFont(textDict)
  649. try:
  650. dc.SetFont(fn)
  651. w,h,lh = dc.GetMultiLineTextExtent(textDict['text'])
  652. return (w,h)
  653. except:
  654. return (0,0)
  655. def getInitMap(self):
  656. """!Create default map frame when no map is selected, needed for coordinates in map units"""
  657. instrFile = grass.tempfile()
  658. instrFileFd = open(instrFile, mode = 'w')
  659. instrFileFd.write(self.InstructionFile())
  660. instrFileFd.flush()
  661. instrFileFd.close()
  662. page = self.instruction.FindInstructionByType('page')
  663. mapInitRect = GetMapBounds(instrFile, portrait = (page['Orientation'] == 'Portrait'))
  664. grass.try_remove(instrFile)
  665. region = grass.region()
  666. units = UnitConversion(self)
  667. realWidth = units.convert(value = abs(region['w'] - region['e']), fromUnit = 'meter', toUnit = 'inch')
  668. scale = mapInitRect.Get()[2]/realWidth
  669. initMap = self.instruction.FindInstructionByType('initMap')
  670. if initMap:
  671. id = initMap.id
  672. else:
  673. id = None
  674. if not id:
  675. id = wx.NewId()
  676. initMap = InitMap(id)
  677. self.instruction.AddInstruction(initMap)
  678. self.instruction[id].SetInstruction(dict(rect = mapInitRect, scale = scale))
  679. def OnDelete(self, event):
  680. if self.canvas.dragId != -1 and self.currentPage == 0:
  681. if self.instruction[self.canvas.dragId].type == 'map':
  682. self.deleteObject(self.canvas.dragId)
  683. self.getInitMap()
  684. self.canvas.RecalculateEN()
  685. else:
  686. self.deleteObject(self.canvas.dragId)
  687. def deleteObject(self, id):
  688. """!Deletes object, his id and redraws"""
  689. #delete from canvas
  690. self.canvas.pdcObj.RemoveId(id)
  691. if id == self.canvas.dragId:
  692. self.canvas.pdcTmp.RemoveAll()
  693. self.canvas.dragId = -1
  694. self.canvas.Refresh()
  695. # delete from instructions
  696. del self.instruction[id]
  697. def DialogDataChanged(self, id):
  698. ids = id
  699. if type(id) == int:
  700. ids = [id]
  701. for id in ids:
  702. itype = self.instruction[id].type
  703. if itype in ('scalebar', 'mapinfo', 'image'):
  704. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  705. self.canvas.UpdateLabel(itype = itype, id = id)
  706. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  707. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  708. self.canvas.RedrawSelectBox(id)
  709. if itype == 'northArrow':
  710. self.canvas.UpdateLabel(itype = itype, id = id)
  711. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  712. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  713. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'bitmap', bb = drawRectangle)
  714. self.canvas.RedrawSelectBox(id)
  715. if itype == 'text':
  716. if self.instruction[id]['rotate']:
  717. rot = float(self.instruction[id]['rotate'])
  718. else:
  719. rot = 0
  720. extent = self.getTextExtent(textDict = self.instruction[id].GetInstruction())
  721. rect = wx.Rect2D(self.instruction[id]['where'][0], self.instruction[id]['where'][1], 0, 0)
  722. self.instruction[id]['coords'] = list(self.canvas.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)[:2])
  723. #computes text coordinates according to reference point, not precisely
  724. if self.instruction[id]['ref'].split()[0] == 'lower':
  725. self.instruction[id]['coords'][1] -= extent[1]
  726. elif self.instruction[id]['ref'].split()[0] == 'center':
  727. self.instruction[id]['coords'][1] -= extent[1]/2
  728. if self.instruction[id]['ref'].split()[1] == 'right':
  729. self.instruction[id]['coords'][0] -= extent[0] * cos(rot/180*pi)
  730. self.instruction[id]['coords'][1] += extent[0] * sin(rot/180*pi)
  731. elif self.instruction[id]['ref'].split()[1] == 'center':
  732. self.instruction[id]['coords'][0] -= extent[0]/2 * cos(rot/180*pi)
  733. self.instruction[id]['coords'][1] += extent[0]/2 * sin(rot/180*pi)
  734. self.instruction[id]['coords'][0] += self.instruction[id]['xoffset']
  735. self.instruction[id]['coords'][1] -= self.instruction[id]['yoffset']
  736. coords = self.instruction[id]['coords']
  737. self.instruction[id]['rect'] = bounds = self.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  738. self.canvas.DrawRotText(pdc = self.canvas.pdcObj, drawId = id,
  739. textDict = self.instruction[id].GetInstruction(),
  740. coords = coords, bounds = bounds)
  741. self.canvas.RedrawSelectBox(id)
  742. if itype in ('map', 'vector', 'raster'):
  743. if itype == 'raster':#set resolution
  744. info = grass.raster_info(self.instruction[id]['raster'])
  745. RunCommand('g.region', nsres = info['nsres'], ewres = info['ewres'])
  746. # change current raster in raster legend
  747. if 'rasterLegend' in self.openDialogs:
  748. self.openDialogs['rasterLegend'].updateDialog()
  749. id = self.instruction.FindInstructionByType('map').id
  750. #check resolution
  751. if itype == 'raster':
  752. SetResolution(dpi = self.instruction[id]['resolution'],
  753. width = self.instruction[id]['rect'].width,
  754. height = self.instruction[id]['rect'].height)
  755. rectCanvas = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'],
  756. canvasToPaper = False)
  757. self.canvas.RecalculateEN()
  758. self.canvas.UpdateMapLabel()
  759. self.canvas.Draw(pen = self.pen['map'], brush = self.brush['map'],
  760. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = rectCanvas)
  761. # redraw select box
  762. self.canvas.RedrawSelectBox(id)
  763. self.canvas.pdcTmp.RemoveId(self.canvas.idZoomBoxTmp)
  764. # redraw to get map to the bottom layer
  765. #self.canvas.Zoom(zoomFactor = 1, view = (0, 0))
  766. if itype == 'rasterLegend':
  767. if self.instruction[id]['rLegend']:
  768. self.canvas.UpdateLabel(itype = itype, id = id)
  769. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  770. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  771. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  772. self.canvas.RedrawSelectBox(id)
  773. else:
  774. self.deleteObject(id)
  775. if itype == 'vectorLegend':
  776. if not self.instruction.FindInstructionByType('vector'):
  777. self.deleteObject(id)
  778. elif self.instruction[id]['vLegend']:
  779. self.canvas.UpdateLabel(itype = itype, id = id)
  780. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  781. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  782. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  783. self.canvas.RedrawSelectBox(id)
  784. else:
  785. self.deleteObject(id)
  786. def OnPageChanged(self, event):
  787. """!Flatnotebook page has changed"""
  788. self.currentPage = self.book.GetPageIndex(self.book.GetCurrentPage())
  789. def OnPageChanging(self, event):
  790. """!Flatnotebook page is changing"""
  791. if self.currentPage == 0 and self.mouse['use'] == 'addMap':
  792. event.Veto()
  793. def OnHelp(self, event):
  794. """!Show help"""
  795. if self.parent and self.parent.GetName() == 'LayerManager':
  796. log = self.parent.GetLogWindow()
  797. log.RunCmd(['g.manual',
  798. 'entry=wxGUI.PsMap'])
  799. else:
  800. RunCommand('g.manual',
  801. quiet = True,
  802. entry = 'wxGUI.PsMap')
  803. def OnAbout(self, event):
  804. """!Display About window"""
  805. info = wx.AboutDialogInfo()
  806. info.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  807. info.SetName(_('wxGUI Cartographic Composer'))
  808. info.SetWebSite('http://grass.osgeo.org')
  809. info.SetDescription(_('(C) 2011 by the GRASS Development Team\n\n') +
  810. '\n'.join(textwrap.wrap(_('This program is free software under the GNU General Public License'
  811. '(>=v2). Read the file COPYING that comes with GRASS for details.'), 75)))
  812. wx.AboutBox(info)
  813. def OnCloseWindow(self, event):
  814. """!Close window"""
  815. try:
  816. os.remove(self.imgName)
  817. except OSError:
  818. pass
  819. grass.set_raise_on_error(False)
  820. self.Destroy()
  821. class PsMapBufferedWindow(wx.Window):
  822. """!A buffered window class.
  823. @param parent parent window
  824. @param kwargs other wx.Window parameters
  825. """
  826. def __init__(self, parent, id = wx.ID_ANY,
  827. style = wx.NO_FULL_REPAINT_ON_RESIZE,
  828. **kwargs):
  829. wx.Window.__init__(self, parent, id = id, style = style)
  830. self.parent = parent
  831. self.FitInside()
  832. # store an off screen empty bitmap for saving to file
  833. self._buffer = None
  834. # indicates whether or not a resize event has taken place
  835. self.resize = False
  836. self.mouse = kwargs['mouse']
  837. self.cursors = kwargs['cursors']
  838. self.preview = kwargs['preview']
  839. self.pen = kwargs['pen']
  840. self.brush = kwargs['brush']
  841. if kwargs.has_key('instruction'):
  842. self.instruction = kwargs['instruction']
  843. if kwargs.has_key('openDialogs'):
  844. self.openDialogs = kwargs['openDialogs']
  845. if kwargs.has_key('pageId'):
  846. self.pageId = kwargs['pageId']
  847. if kwargs.has_key('objectId'):
  848. self.objectId = kwargs['objectId']
  849. #labels
  850. self.itemLabelsDict = { 'map': 'MAP FRAME',
  851. 'rasterLegend': 'RASTER LEGEND',
  852. 'vectorLegend': 'VECTOR LEGEND',
  853. 'mapinfo': 'MAP INFO',
  854. 'scalebar': 'SCALE BAR',
  855. 'image': 'IMAGE',
  856. 'northArrow': 'NORTH ARROW'}
  857. self.itemLabels = {}
  858. # define PseudoDC
  859. self.pdc = wx.PseudoDC()
  860. self.pdcObj = wx.PseudoDC()
  861. self.pdcPaper = wx.PseudoDC()
  862. self.pdcTmp = wx.PseudoDC()
  863. self.pdcImage = wx.PseudoDC()
  864. dc = wx.PaintDC(self)
  865. self.font = dc.GetFont()
  866. self.SetClientSize((700,510))#?
  867. self._buffer = wx.EmptyBitmap(*self.GetClientSize())
  868. self.idBoxTmp = wx.NewId()
  869. self.idZoomBoxTmp = wx.NewId()
  870. self.idResizeBoxTmp = wx.NewId()
  871. self.dragId = -1
  872. if self.preview:
  873. self.image = None
  874. self.imageId = 2000
  875. self.imgName = self.parent.imgName
  876. self.currScale = None
  877. self.Clear()
  878. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
  879. self.Bind(wx.EVT_PAINT, self.OnPaint)
  880. self.Bind(wx.EVT_SIZE, self.OnSize)
  881. self.Bind(wx.EVT_IDLE, self.OnIdle)
  882. self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
  883. def Clear(self):
  884. """!Clear canvas and set paper
  885. """
  886. bg = wx.LIGHT_GREY_BRUSH
  887. self.pdcPaper.BeginDrawing()
  888. self.pdcPaper.SetBackground(bg)
  889. self.pdcPaper.Clear()
  890. self.pdcPaper.EndDrawing()
  891. self.pdcObj.RemoveAll()
  892. self.pdcTmp.RemoveAll()
  893. if not self.preview:
  894. self.SetPage()
  895. def CanvasPaperCoordinates(self, rect, canvasToPaper = True):
  896. """!Converts canvas (pixel) -> paper (inch) coordinates and size and vice versa"""
  897. units = UnitConversion(self)
  898. fromU = 'pixel'
  899. toU = 'inch'
  900. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  901. pRectx, pRecty = pRect.x, pRect.y
  902. scale = 1/self.currScale
  903. if not canvasToPaper: # paper -> canvas
  904. fromU = 'inch'
  905. toU = 'pixel'
  906. scale = self.currScale
  907. pRectx = units.convert(value = - pRect.x, fromUnit = 'pixel', toUnit = 'inch' ) /scale #inch, real, negative
  908. pRecty = units.convert(value = - pRect.y, fromUnit = 'pixel', toUnit = 'inch' ) /scale
  909. Width = units.convert(value = rect.width, fromUnit = fromU, toUnit = toU) * scale
  910. Height = units.convert(value = rect.height, fromUnit = fromU, toUnit = toU) * scale
  911. X = units.convert(value = (rect.x - pRectx), fromUnit = fromU, toUnit = toU) * scale
  912. Y = units.convert(value = (rect.y - pRecty), fromUnit = fromU, toUnit = toU) * scale
  913. return wx.Rect2D(X, Y, Width, Height)
  914. def SetPage(self):
  915. """!Sets and changes page, redraws paper"""
  916. page = self.instruction[self.pageId]
  917. if not page:
  918. page = PageSetup(id = self.pageId)
  919. self.instruction.AddInstruction(page)
  920. ppi = wx.PaintDC(self).GetPPI()
  921. cW, cH = self.GetClientSize()
  922. pW, pH = page['Width']*ppi[0], page['Height']*ppi[1]
  923. if self.currScale is None:
  924. self.currScale = min(cW/pW, cH/pH)
  925. pW = pW * self.currScale
  926. pH = pH * self.currScale
  927. x = cW/2 - pW/2
  928. y = cH/2 - pH/2
  929. self.DrawPaper(wx.Rect(x, y, pW, pH))
  930. def modifyRectangle(self, r):
  931. """! Recalculates rectangle not to have negative size"""
  932. if r.GetWidth() < 0:
  933. r.SetX(r.GetX() + r.GetWidth())
  934. if r.GetHeight() < 0:
  935. r.SetY(r.GetY() + r.GetHeight())
  936. r.SetWidth(abs(r.GetWidth()))
  937. r.SetHeight(abs(r.GetHeight()))
  938. return r
  939. def RecalculateEN(self):
  940. """!Recalculate east and north for texts (eps, points) after their or map's movement"""
  941. try:
  942. mapId = self.instruction.FindInstructionByType('map').id
  943. except AttributeError:
  944. mapId = self.instruction.FindInstructionByType('initMap').id
  945. for itemType in ('text', 'image', 'northArrow'):
  946. items = self.instruction.FindInstructionByType(itemType, list = True)
  947. for item in items:
  948. e, n = PaperMapCoordinates(map = self.instruction[mapId], x = self.instruction[item.id]['where'][0],
  949. y = self.instruction[item.id]['where'][1], paperToMap = True)
  950. self.instruction[item.id]['east'], self.instruction[item.id]['north'] = e, n
  951. def OnPaint(self, event):
  952. """!Draw pseudo DC to buffer
  953. """
  954. if not self._buffer:
  955. return
  956. dc = wx.BufferedPaintDC(self, self._buffer)
  957. # use PrepareDC to set position correctly
  958. self.PrepareDC(dc)
  959. dc.SetBackground(wx.LIGHT_GREY_BRUSH)
  960. dc.Clear()
  961. # draw paper
  962. if not self.preview:
  963. self.pdcPaper.DrawToDC(dc)
  964. # draw to the DC using the calculated clipping rect
  965. rgn = self.GetUpdateRegion()
  966. if not self.preview:
  967. self.pdcObj.DrawToDCClipped(dc, rgn.GetBox())
  968. else:
  969. self.pdcImage.DrawToDCClipped(dc, rgn.GetBox())
  970. self.pdcTmp.DrawToDCClipped(dc, rgn.GetBox())
  971. def OnMouse(self, event):
  972. if event.GetWheelRotation():
  973. zoom = event.GetWheelRotation()
  974. use = self.mouse['use']
  975. self.mouse['begin'] = event.GetPosition()
  976. if zoom > 0:
  977. self.mouse['use'] = 'zoomin'
  978. else:
  979. self.mouse['use'] = 'zoomout'
  980. zoomFactor, view = self.ComputeZoom(wx.Rect(0,0,0,0))
  981. self.Zoom(zoomFactor, view)
  982. self.mouse['use'] = use
  983. if event.Moving():
  984. if self.mouse['use'] in ('pointer', 'resize'):
  985. pos = event.GetPosition()
  986. foundResize = self.pdcTmp.FindObjects(pos[0], pos[1])
  987. if foundResize and foundResize[0] == self.idResizeBoxTmp:
  988. self.SetCursor(self.cursors["sizenwse"])
  989. self.parent.SetStatusText(_('Click and drag to resize object'), 0)
  990. else:
  991. self.parent.SetStatusText('', 0)
  992. self.SetCursor(self.cursors["default"])
  993. elif event.LeftDown():
  994. self.mouse['begin'] = event.GetPosition()
  995. self.begin = self.mouse['begin']
  996. if self.mouse['use'] in ('pan', 'zoomin', 'zoomout', 'addMap'):
  997. pass
  998. #select
  999. if self.mouse['use'] == 'pointer':
  1000. found = self.pdcObj.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  1001. foundResize = self.pdcTmp.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  1002. if foundResize and foundResize[0] == self.idResizeBoxTmp:
  1003. self.mouse['use'] = 'resize'
  1004. # when resizing, proportions match region
  1005. if self.instruction[self.dragId].type == 'map':
  1006. self.constraint = False
  1007. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1008. if self.instruction[self.dragId]['scaleType'] in (0, 1, 2):
  1009. self.constraint = True
  1010. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1011. elif found:
  1012. self.dragId = found[0]
  1013. self.RedrawSelectBox(self.dragId)
  1014. if self.instruction[self.dragId].type != 'map':
  1015. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1016. self.Refresh()
  1017. else:
  1018. self.dragId = -1
  1019. self.pdcTmp.RemoveId(self.idBoxTmp)
  1020. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1021. self.Refresh()
  1022. elif event.Dragging() and event.LeftIsDown():
  1023. #draw box when zooming, creating map
  1024. if self.mouse['use'] in ('zoomin', 'zoomout', 'addMap'):
  1025. self.mouse['end'] = event.GetPosition()
  1026. r = wx.Rect(self.mouse['begin'][0], self.mouse['begin'][1],
  1027. self.mouse['end'][0]-self.mouse['begin'][0], self.mouse['end'][1]-self.mouse['begin'][1])
  1028. r = self.modifyRectangle(r)
  1029. self.Draw(pen = self.pen['box'], brush = self.brush['box'], pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
  1030. pdctype = 'rect', bb = r)
  1031. # panning
  1032. if self.mouse["use"] == 'pan':
  1033. self.mouse['end'] = event.GetPosition()
  1034. view = self.mouse['begin'][0] - self.mouse['end'][0], self.mouse['begin'][1] - self.mouse['end'][1]
  1035. zoomFactor = 1
  1036. self.Zoom(zoomFactor, view)
  1037. self.mouse['begin'] = event.GetPosition()
  1038. #move object
  1039. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1040. self.mouse['end'] = event.GetPosition()
  1041. dx, dy = self.mouse['end'][0] - self.begin[0], self.mouse['end'][1] - self.begin[1]
  1042. self.pdcObj.TranslateId(self.dragId, dx, dy)
  1043. self.pdcTmp.TranslateId(self.idBoxTmp, dx, dy)
  1044. self.pdcTmp.TranslateId(self.idResizeBoxTmp, dx, dy)
  1045. if self.instruction[self.dragId].type == 'text':
  1046. self.instruction[self.dragId]['coords'] = self.instruction[self.dragId]['coords'][0] + dx,\
  1047. self.instruction[self.dragId]['coords'][1] + dy
  1048. self.begin = event.GetPosition()
  1049. self.Refresh()
  1050. # resize object
  1051. if self.mouse['use'] == 'resize':
  1052. type = self.instruction[self.dragId].type
  1053. pos = event.GetPosition()
  1054. x, y = self.mapBounds.GetX(), self.mapBounds.GetY()
  1055. width, height = self.mapBounds.GetWidth(), self.mapBounds.GetHeight()
  1056. diffX = pos[0] - self.mouse['begin'][0]
  1057. diffY = pos[1] - self.mouse['begin'][1]
  1058. # match given region
  1059. if self.constraint:
  1060. if width > height:
  1061. newWidth = width + diffX
  1062. newHeight = height + diffX * (float(height) / width)
  1063. else:
  1064. newWidth = width + diffY * (float(width) / height)
  1065. newHeight = height + diffY
  1066. else:
  1067. newWidth = width + diffX
  1068. newHeight = height + diffY
  1069. if newWidth < 10 or newHeight < 10:
  1070. return
  1071. bounds = wx.Rect(x, y, newWidth, newHeight)
  1072. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj, drawid = self.dragId,
  1073. pdctype = 'rectText', bb = bounds)
  1074. self.RedrawSelectBox(self.dragId)
  1075. elif event.LeftUp():
  1076. # zoom in, zoom out
  1077. if self.mouse['use'] in ('zoomin','zoomout'):
  1078. zoomR = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1079. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1080. self.Refresh()
  1081. zoomFactor, view = self.ComputeZoom(zoomR)
  1082. self.Zoom(zoomFactor, view)
  1083. # draw map frame
  1084. if self.mouse['use'] == 'addMap':
  1085. rectTmp = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1086. # too small rectangle, it's usually some mistake
  1087. if rectTmp.GetWidth() < 20 or rectTmp.GetHeight() < 20:
  1088. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1089. self.Refresh()
  1090. return
  1091. rectPaper = self.CanvasPaperCoordinates(rect = rectTmp, canvasToPaper = True)
  1092. dlg = MapDialog(parent = self.parent, id = [None, None, None], settings = self.instruction,
  1093. rect = rectPaper)
  1094. self.openDialogs['map'] = dlg
  1095. self.openDialogs['map'].Show()
  1096. self.mouse['use'] = self.parent.mouseOld
  1097. self.SetCursor(self.parent.cursorOld)
  1098. self.parent.toolbar.ToggleTool(self.parent.actionOld, True)
  1099. self.parent.toolbar.ToggleTool(self.parent.toolbar.action['id'], False)
  1100. self.parent.toolbar.action['id'] = self.parent.actionOld
  1101. # resize resizable objects (only map sofar)
  1102. if self.mouse['use'] == 'resize':
  1103. mapId = self.instruction.FindInstructionByType('map').id
  1104. if self.dragId == mapId:
  1105. # necessary to change either map frame (scaleType 0,1,2) or region (scaletype 3)
  1106. newRectCanvas = self.pdcObj.GetIdBounds(mapId)
  1107. newRectPaper = self.CanvasPaperCoordinates(rect = newRectCanvas, canvasToPaper = True)
  1108. self.instruction[mapId]['rect'] = newRectPaper
  1109. if self.instruction[mapId]['scaleType'] in (0, 1, 2):
  1110. if self.instruction[mapId]['scaleType'] == 0:
  1111. scale, foo, rect = AutoAdjust(self, scaleType = 0,
  1112. map = self.instruction[mapId]['map'],
  1113. mapType = self.instruction[mapId]['mapType'],
  1114. rect = self.instruction[mapId]['rect'])
  1115. elif self.instruction[mapId]['scaleType'] == 1:
  1116. scale, foo, rect = AutoAdjust(self, scaleType = 1,
  1117. region = self.instruction[mapId]['region'],
  1118. rect = self.instruction[mapId]['rect'])
  1119. else:
  1120. scale, foo, rect = AutoAdjust(self, scaleType = 2,
  1121. rect = self.instruction[mapId]['rect'])
  1122. self.instruction[mapId]['rect'] = rect
  1123. self.instruction[mapId]['scale'] = scale
  1124. rectCanvas = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)
  1125. self.Draw(pen = self.pen['map'], brush = self.brush['map'],
  1126. pdc = self.pdcObj, drawid = mapId, pdctype = 'rectText', bb = rectCanvas)
  1127. elif self.instruction[mapId]['scaleType'] == 3:
  1128. ComputeSetRegion(self, mapDict = self.instruction[mapId].GetInstruction())
  1129. #check resolution
  1130. SetResolution(dpi = self.instruction[mapId]['resolution'],
  1131. width = self.instruction[mapId]['rect'].width,
  1132. height = self.instruction[mapId]['rect'].height)
  1133. self.RedrawSelectBox(mapId)
  1134. self.Zoom(zoomFactor = 1, view = (0, 0))
  1135. self.mouse['use'] = 'pointer'
  1136. # recalculate the position of objects after dragging
  1137. if self.mouse['use'] in ('pointer', 'resize') and self.dragId != -1:
  1138. if self.mouse['begin'] != event.GetPosition(): #for double click
  1139. self.RecalculatePosition(ids = [self.dragId])
  1140. if self.instruction[self.dragId].type in self.openDialogs:
  1141. self.openDialogs[self.instruction[self.dragId].type].updateDialog()
  1142. # double click launches dialogs
  1143. elif event.LeftDClick():
  1144. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1145. itemCall = { 'text':self.parent.OnAddText, 'mapinfo': self.parent.OnAddMapinfo,
  1146. 'scalebar': self.parent.OnAddScalebar, 'image': self.parent.OnAddImage,
  1147. 'northArrow' : self.parent.OnAddNorthArrow,
  1148. 'rasterLegend': self.parent.OnAddLegend, 'vectorLegend': self.parent.OnAddLegend,
  1149. 'map': self.parent.OnAddMap}
  1150. itemArg = { 'text': dict(event = None, id = self.dragId), 'mapinfo': dict(event = None),
  1151. 'scalebar': dict(event = None), 'image': dict(event = None, id = self.dragId),
  1152. 'northArrow': dict(event = None, id = self.dragId),
  1153. 'rasterLegend': dict(event = None), 'vectorLegend': dict(event = None, page = 1),
  1154. 'map': dict(event = None, notebook = True)}
  1155. type = self.instruction[self.dragId].type
  1156. itemCall[type](**itemArg[type])
  1157. def RecalculatePosition(self, ids):
  1158. for id in ids:
  1159. itype = self.instruction[id].type
  1160. if itype == 'map':
  1161. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1162. canvasToPaper = True)
  1163. self.RecalculateEN()
  1164. elif itype in ('mapinfo' ,'rasterLegend', 'vectorLegend', 'image', 'northArrow'):
  1165. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1166. canvasToPaper = True)
  1167. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1168. canvasToPaper = True)[:2]
  1169. if itype in ('image', 'northArrow'):
  1170. self.RecalculateEN()
  1171. elif itype == 'scalebar':
  1172. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1173. canvasToPaper = True)
  1174. self.instruction[id]['where'] = self.instruction[id]['rect'].GetCentre()
  1175. elif itype == 'text':
  1176. x, y = self.instruction[id]['coords'][0] - self.instruction[id]['xoffset'],\
  1177. self.instruction[id]['coords'][1] + self.instruction[id]['yoffset']
  1178. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1179. if self.instruction[id]['rotate'] is not None:
  1180. rot = float(self.instruction[id]['rotate'])/180*pi
  1181. else:
  1182. rot = 0
  1183. if self.instruction[id]['ref'].split()[0] == 'lower':
  1184. y += extent[1]
  1185. elif self.instruction[id]['ref'].split()[0] == 'center':
  1186. y += extent[1]/2
  1187. if self.instruction[id]['ref'].split()[1] == 'right':
  1188. x += extent[0] * cos(rot)
  1189. y -= extent[0] * sin(rot)
  1190. elif self.instruction[id]['ref'].split()[1] == 'center':
  1191. x += extent[0]/2 * cos(rot)
  1192. y -= extent[0]/2 * sin(rot)
  1193. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = wx.Rect2D(x, y, 0, 0),
  1194. canvasToPaper = True)[:2]
  1195. self.RecalculateEN()
  1196. def ComputeZoom(self, rect):
  1197. """!Computes zoom factor and scroll view"""
  1198. zoomFactor = 1
  1199. cW, cH = self.GetClientSize()
  1200. cW = float(cW)
  1201. if rect.IsEmpty(): # clicked on canvas
  1202. zoomFactor = 1.5
  1203. if self.mouse['use'] == 'zoomout':
  1204. zoomFactor = 1./zoomFactor
  1205. x,y = self.mouse['begin']
  1206. xView = x - x/zoomFactor#x - cW/(zoomFactor * 2)
  1207. yView = y - y/zoomFactor#y - cH/(zoomFactor * 2)
  1208. else: #dragging
  1209. rW, rH = float(rect.GetWidth()), float(rect.GetHeight())
  1210. zoomFactor = 1/max(rW/cW, rH/cH)
  1211. # when zooming to full extent, in some cases, there was zoom 1.01..., which causes problem
  1212. if abs(zoomFactor - 1) > 0.01:
  1213. zoomFactor = zoomFactor
  1214. else:
  1215. zoomFactor = 1.
  1216. if self.mouse['use'] == 'zoomout':
  1217. zoomFactor = min(rW/cW, rH/cH)
  1218. if rW/rH > cW/cH:
  1219. yView = rect.GetY() - (rW*(cH/cW) - rH)/2
  1220. xView = rect.GetX()
  1221. if self.mouse['use'] == 'zoomout':
  1222. x,y = rect.GetX() + (rW-(cW/cH)*rH)/2, rect.GetY()
  1223. xView, yView = -x, -y
  1224. else:
  1225. xView = rect.GetX() - (rH*(cW/cH) - rW)/2
  1226. yView = rect.GetY()
  1227. if self.mouse['use'] == 'zoomout':
  1228. x,y = rect.GetX(), rect.GetY() + (rH-(cH/cW)*rW)/2
  1229. xView, yView = -x, -y
  1230. return zoomFactor, (int(xView), int(yView))
  1231. def Zoom(self, zoomFactor, view):
  1232. """! Zoom to specified region, scroll view, redraw"""
  1233. if not self.currScale:
  1234. return
  1235. self.currScale = self.currScale*zoomFactor
  1236. if self.currScale > 10 or self.currScale < 0.1:
  1237. self.currScale = self.currScale/zoomFactor
  1238. return
  1239. if not self.preview:
  1240. # redraw paper
  1241. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  1242. pRect.OffsetXY(-view[0], -view[1])
  1243. pRect = self.ScaleRect(rect = pRect, scale = zoomFactor)
  1244. self.DrawPaper(pRect)
  1245. #redraw objects
  1246. for id in self.objectId:
  1247. oRect = self.CanvasPaperCoordinates(
  1248. rect = self.instruction[id]['rect'], canvasToPaper = False)
  1249. type = self.instruction[id].type
  1250. if type == 'text':
  1251. coords = self.instruction[id]['coords']# recalculate coordinates, they are not equal to BB
  1252. self.instruction[id]['coords'] = coords = [(int(coord) - view[i]) * zoomFactor
  1253. for i, coord in enumerate(coords)]
  1254. self.DrawRotText(pdc = self.pdcObj, drawId = id, textDict = self.instruction[id],
  1255. coords = coords, bounds = oRect )
  1256. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1257. if self.instruction[id]['rotate']:
  1258. rot = float(self.instruction[id]['rotate'])
  1259. else:
  1260. rot = 0
  1261. self.instruction[id]['rect'] = bounds = self.parent.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  1262. self.pdcObj.SetIdBounds(id, bounds)
  1263. elif type == 'northArrow':
  1264. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1265. drawid = id, pdctype = 'bitmap', bb = oRect)
  1266. else:
  1267. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1268. drawid = id, pdctype = 'rectText', bb = oRect)
  1269. #redraw tmp objects
  1270. if self.dragId != -1:
  1271. self.RedrawSelectBox(self.dragId)
  1272. #redraw preview
  1273. else: # preview mode
  1274. imageRect = self.pdcImage.GetIdBounds(self.imageId)
  1275. imageRect.OffsetXY(-view[0], -view[1])
  1276. imageRect = self.ScaleRect(rect = imageRect, scale = zoomFactor)
  1277. self.DrawImage(imageRect)
  1278. def ZoomAll(self):
  1279. """! Zoom to full extent"""
  1280. if not self.preview:
  1281. bounds = self.pdcPaper.GetIdBounds(self.pageId)
  1282. else:
  1283. bounds = self.pdcImage.GetIdBounds(self.imageId)
  1284. zoomP = bounds.Inflate(bounds.width/20, bounds.height/20)
  1285. zoomFactor, view = self.ComputeZoom(zoomP)
  1286. self.Zoom(zoomFactor, view)
  1287. def Draw(self, pen, brush, pdc, drawid = None, pdctype = 'rect', bb = wx.Rect(0,0,0,0)):
  1288. """! Draw object"""
  1289. if drawid is None:
  1290. drawid = wx.NewId()
  1291. bb = bb.Get()
  1292. pdc.BeginDrawing()
  1293. pdc.RemoveId(drawid)
  1294. pdc.SetId(drawid)
  1295. pdc.SetPen(pen)
  1296. pdc.SetBrush(brush)
  1297. if pdctype == 'bitmap':
  1298. if havePILImage:
  1299. file = self.instruction[drawid]['epsfile']
  1300. rotation = self.instruction[drawid]['rotate']
  1301. self.DrawBitmap(pdc = pdc, filePath = file, rotation = rotation, bbox = bb)
  1302. else: # draw only rectangle with label
  1303. pdctype = 'rectText'
  1304. if pdctype in ('rect', 'rectText'):
  1305. pdc.DrawRectangle(*bb)
  1306. if pdctype == 'rectText':
  1307. dc = wx.PaintDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  1308. font = self.font
  1309. size = 10
  1310. font.SetPointSize(size)
  1311. font.SetStyle(wx.ITALIC)
  1312. dc.SetFont(font)
  1313. pdc.SetFont(font)
  1314. text = '\n'.join(self.itemLabels[drawid])
  1315. w,h,lh = dc.GetMultiLineTextExtent(text)
  1316. textExtent = (w,h)
  1317. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1318. r = map(int, bb)
  1319. while not wx.Rect(*r).ContainsRect(textRect) and size >= 8:
  1320. size -= 2
  1321. font.SetPointSize(size)
  1322. dc.SetFont(font)
  1323. pdc.SetFont(font)
  1324. textExtent = dc.GetTextExtent(text)
  1325. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1326. pdc.SetTextForeground(wx.Color(100,100,100,200))
  1327. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1328. pdc.DrawText(text = text, x = textRect.x, y = textRect.y)
  1329. pdc.SetIdBounds(drawid, bb)
  1330. pdc.EndDrawing()
  1331. self.Refresh()
  1332. return drawid
  1333. def DrawBitmap(self, pdc, filePath, rotation, bbox):
  1334. """!Draw bitmap using PIL"""
  1335. pImg = PILImage.open(filePath)
  1336. if rotation:
  1337. # get rid of black background
  1338. pImg = pImg.convert("RGBA")
  1339. rot = pImg.rotate(rotation, expand = 1)
  1340. new = PILImage.new('RGBA', rot.size, (255,) * 4)
  1341. pImg = PILImage.composite(rot, new, rot)
  1342. pImg = pImg.resize((int(bbox[2]), int(bbox[3])), resample = PILImage.BICUBIC)
  1343. img = PilImageToWxImage(pImg)
  1344. bitmap = img.ConvertToBitmap()
  1345. mask = wx.Mask(bitmap, wx.WHITE)
  1346. bitmap.SetMask(mask)
  1347. pdc.DrawBitmap(bitmap, bbox[0], bbox[1], useMask = True)
  1348. def DrawRotText(self, pdc, drawId, textDict, coords, bounds):
  1349. if textDict['rotate']:
  1350. rot = float(textDict['rotate'])
  1351. else:
  1352. rot = 0
  1353. fontsize = textDict['fontsize'] * self.currScale
  1354. if textDict['background'] != 'none':
  1355. background = textDict['background']
  1356. else:
  1357. background = None
  1358. pdc.RemoveId(drawId)
  1359. pdc.SetId(drawId)
  1360. pdc.BeginDrawing()
  1361. # border is not redrawn when zoom changes, why?
  1362. ## if textDict['border'] != 'none' and not rot:
  1363. ## units = UnitConversion(self)
  1364. ## borderWidth = units.convert(value = textDict['width'],
  1365. ## fromUnit = 'point', toUnit = 'pixel' ) * self.currScale
  1366. ## pdc.SetPen(wx.Pen(colour = convertRGB(textDict['border']), width = borderWidth))
  1367. ## pdc.DrawRectangle(*bounds)
  1368. if background:
  1369. pdc.SetTextBackground(convertRGB(background))
  1370. pdc.SetBackgroundMode(wx.SOLID)
  1371. else:
  1372. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1373. fn = self.parent.makePSFont(textDict)
  1374. pdc.SetFont(fn)
  1375. pdc.SetTextForeground(convertRGB(textDict['color']))
  1376. pdc.DrawRotatedText(textDict['text'], coords[0], coords[1], rot)
  1377. pdc.SetIdBounds(drawId, wx.Rect(*bounds))
  1378. self.Refresh()
  1379. pdc.EndDrawing()
  1380. def DrawImage(self, rect):
  1381. """!Draw preview image to pseudoDC"""
  1382. self.pdcImage.ClearId(self.imageId)
  1383. self.pdcImage.SetId(self.imageId)
  1384. img = self.image
  1385. if img.GetWidth() != rect.width or img.GetHeight() != rect.height:
  1386. img = img.Scale(rect.width, rect.height)
  1387. bitmap = img.ConvertToBitmap()
  1388. self.pdcImage.BeginDrawing()
  1389. self.pdcImage.DrawBitmap(bitmap, rect.x, rect.y)
  1390. self.pdcImage.SetIdBounds(self.imageId, rect)
  1391. self.pdcImage.EndDrawing()
  1392. self.Refresh()
  1393. def DrawPaper(self, rect):
  1394. """!Draw paper and margins"""
  1395. page = self.instruction[self.pageId]
  1396. scale = page['Width'] / rect.GetWidth()
  1397. w = (page['Width'] - page['Right'] - page['Left']) / scale
  1398. h = (page['Height'] - page['Top'] - page['Bottom']) / scale
  1399. x = page['Left'] / scale + rect.GetX()
  1400. y = page['Top'] / scale + rect.GetY()
  1401. self.pdcPaper.BeginDrawing()
  1402. self.pdcPaper.RemoveId(self.pageId)
  1403. self.pdcPaper.SetId(self.pageId)
  1404. self.pdcPaper.SetPen(self.pen['paper'])
  1405. self.pdcPaper.SetBrush(self.brush['paper'])
  1406. self.pdcPaper.DrawRectangleRect(rect)
  1407. self.pdcPaper.SetPen(self.pen['margins'])
  1408. self.pdcPaper.SetBrush(self.brush['margins'])
  1409. self.pdcPaper.DrawRectangle(x, y, w, h)
  1410. self.pdcPaper.SetIdBounds(self.pageId, rect)
  1411. self.pdcPaper.EndDrawing()
  1412. self.Refresh()
  1413. def ImageRect(self):
  1414. """!Returns image centered in canvas, computes scale"""
  1415. img = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  1416. cW, cH = self.GetClientSize()
  1417. iW, iH = img.GetWidth(), img.GetHeight()
  1418. self.currScale = min(float(cW)/iW, float(cH)/iH)
  1419. iW = iW * self.currScale
  1420. iH = iH * self.currScale
  1421. x = cW/2 - iW/2
  1422. y = cH/2 - iH/2
  1423. imageRect = wx.Rect(x, y, iW, iH)
  1424. return imageRect
  1425. def RedrawSelectBox(self, id):
  1426. """!Redraws select box when selected object changes its size"""
  1427. if self.dragId == id:
  1428. rect = [self.pdcObj.GetIdBounds(id).Inflate(3,3)]
  1429. type = ['select']
  1430. ids = [self.idBoxTmp]
  1431. if self.instruction[id].type == 'map':
  1432. controlP = self.pdcObj.GetIdBounds(id).GetBottomRight()
  1433. rect.append(wx.Rect(controlP.x, controlP.y, 10,10))
  1434. type.append('resize')
  1435. ids.append(self.idResizeBoxTmp)
  1436. for id, type, rect in zip(ids, type, rect):
  1437. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcTmp,
  1438. drawid = id, pdctype = 'rect', bb = rect)
  1439. def UpdateMapLabel(self):
  1440. """!Updates map frame label"""
  1441. vector = self.instruction.FindInstructionByType('vector')
  1442. if vector:
  1443. vectorId = vector.id
  1444. else:
  1445. vectorId = None
  1446. raster = self.instruction.FindInstructionByType('raster')
  1447. if raster:
  1448. rasterId = raster.id
  1449. else:
  1450. rasterId = None
  1451. rasterName = 'None'
  1452. if rasterId:
  1453. rasterName = self.instruction[rasterId]['raster'].split('@')[0]
  1454. mapId = self.instruction.FindInstructionByType('map').id
  1455. self.itemLabels[mapId] = []
  1456. self.itemLabels[mapId].append(self.itemLabelsDict['map'])
  1457. self.itemLabels[mapId].append("raster: " + rasterName)
  1458. if vectorId:
  1459. for map in self.instruction[vectorId]['list']:
  1460. self.itemLabels[mapId].append('vector: ' + map[0].split('@')[0])
  1461. def UpdateLabel(self, itype, id):
  1462. self.itemLabels[id] = []
  1463. self.itemLabels[id].append(self.itemLabelsDict[itype])
  1464. if itype == 'image':
  1465. file = os.path.basename(self.instruction[id]['epsfile'])
  1466. self.itemLabels[id].append(file)
  1467. def OnSize(self, event):
  1468. """!Init image size to match window size
  1469. """
  1470. # not zoom all when notebook page is changed
  1471. if self.preview and self.parent.currentPage == 1 or not self.preview and self.parent.currentPage == 0:
  1472. self.ZoomAll()
  1473. self.OnIdle(None)
  1474. event.Skip()
  1475. def OnIdle(self, event):
  1476. """!Only re-render a image during idle time instead of
  1477. multiple times during resizing.
  1478. """
  1479. width, height = self.GetClientSize()
  1480. # Make new off screen bitmap: this bitmap will always have the
  1481. # current drawing in it, so it can be used to save the image
  1482. # to a file, or whatever.
  1483. self._buffer = wx.EmptyBitmap(width, height)
  1484. # re-render image on idle
  1485. self.resize = True
  1486. def ScaleRect(self, rect, scale):
  1487. """! Scale rectangle"""
  1488. return wx.Rect(rect.GetLeft()*scale, rect.GetTop()*scale,
  1489. rect.GetSize()[0]*scale, rect.GetSize()[1]*scale)
  1490. def main():
  1491. import gettext
  1492. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1493. app = wx.PySimpleApp()
  1494. wx.InitAllImageHandlers()
  1495. frame = PsMapFrame()
  1496. frame.Show()
  1497. app.MainLoop()
  1498. if __name__ == "__main__":
  1499. main()