frame.py 94 KB

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