frame.py 99 KB

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