frame.py 94 KB

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