frame.py 95 KB

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