frame.py 96 KB

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