frame.py 74 KB

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