FlatCAMGeoEditor.py 174 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666
  1. # ######################################################### ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ######################################################### ##
  8. # ########################################################### #
  9. # File Modified: Marius Adrian Stanciu (c) #
  10. # Date: 3/10/2019 #
  11. # ######################################################### ##
  12. from PyQt5 import QtGui, QtCore, QtWidgets
  13. from PyQt5.QtCore import Qt, QSettings
  14. from camlib import *
  15. from FlatCAMTool import FlatCAMTool
  16. from flatcamGUI.ObjectUI import LengthEntry, RadioSet
  17. from shapely.geometry import LineString, LinearRing, MultiLineString
  18. # from shapely.geometry import mapping
  19. from shapely.ops import cascaded_union, unary_union
  20. import shapely.affinity as affinity
  21. from numpy import arctan2, Inf, array, sqrt, sign, dot
  22. from numpy.linalg import norm as numpy_norm
  23. from rtree import index as rtindex
  24. from flatcamGUI.GUIElements import OptionalInputSection, FCCheckBox, FCEntry, FCComboBox, FCTextAreaRich, \
  25. FCTable, FCDoubleSpinner, FCButton, EvalEntry2, FCInputDialog
  26. from flatcamParsers.ParseFont import *
  27. # from vispy.io import read_png
  28. import gettext
  29. import FlatCAMTranslation as fcTranslate
  30. import builtins
  31. fcTranslate.apply_language('strings')
  32. if '_' not in builtins.__dict__:
  33. _ = gettext.gettext
  34. class BufferSelectionTool(FlatCAMTool):
  35. """
  36. Simple input for buffer distance.
  37. """
  38. toolName = "Buffer Selection"
  39. def __init__(self, app, draw_app):
  40. FlatCAMTool.__init__(self, app)
  41. self.draw_app = draw_app
  42. # Title
  43. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  44. title_label.setStyleSheet("""
  45. QLabel
  46. {
  47. font-size: 16px;
  48. font-weight: bold;
  49. }
  50. """)
  51. self.layout.addWidget(title_label)
  52. # this way I can hide/show the frame
  53. self.buffer_tool_frame = QtWidgets.QFrame()
  54. self.buffer_tool_frame.setContentsMargins(0, 0, 0, 0)
  55. self.layout.addWidget(self.buffer_tool_frame)
  56. self.buffer_tools_box = QtWidgets.QVBoxLayout()
  57. self.buffer_tools_box.setContentsMargins(0, 0, 0, 0)
  58. self.buffer_tool_frame.setLayout(self.buffer_tools_box)
  59. # Form Layout
  60. form_layout = QtWidgets.QFormLayout()
  61. self.buffer_tools_box.addLayout(form_layout)
  62. # Buffer distance
  63. self.buffer_distance_entry = FCDoubleSpinner()
  64. self.buffer_distance_entry.set_precision(4)
  65. self.buffer_distance_entry.set_range(0.0000, 999999.9999)
  66. form_layout.addRow(_("Buffer distance:"), self.buffer_distance_entry)
  67. self.buffer_corner_lbl = QtWidgets.QLabel(_("Buffer corner:"))
  68. self.buffer_corner_lbl.setToolTip(
  69. _("There are 3 types of corners:\n"
  70. " - 'Round': the corner is rounded for exterior buffer.\n"
  71. " - 'Square:' the corner is met in a sharp angle for exterior buffer.\n"
  72. " - 'Beveled:' the corner is a line that directly connects the features meeting in the corner")
  73. )
  74. self.buffer_corner_cb = FCComboBox()
  75. self.buffer_corner_cb.addItem(_("Round"))
  76. self.buffer_corner_cb.addItem(_("Square"))
  77. self.buffer_corner_cb.addItem(_("Beveled"))
  78. form_layout.addRow(self.buffer_corner_lbl, self.buffer_corner_cb)
  79. # Buttons
  80. hlay = QtWidgets.QHBoxLayout()
  81. self.buffer_tools_box.addLayout(hlay)
  82. self.buffer_int_button = QtWidgets.QPushButton(_("Buffer Interior"))
  83. hlay.addWidget(self.buffer_int_button)
  84. self.buffer_ext_button = QtWidgets.QPushButton(_("Buffer Exterior"))
  85. hlay.addWidget(self.buffer_ext_button)
  86. hlay1 = QtWidgets.QHBoxLayout()
  87. self.buffer_tools_box.addLayout(hlay1)
  88. self.buffer_button = QtWidgets.QPushButton(_("Full Buffer"))
  89. hlay1.addWidget(self.buffer_button)
  90. self.layout.addStretch()
  91. # Signals
  92. self.buffer_button.clicked.connect(self.on_buffer)
  93. self.buffer_int_button.clicked.connect(self.on_buffer_int)
  94. self.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  95. # Init GUI
  96. self.buffer_distance_entry.set_value(0.01)
  97. def run(self):
  98. self.app.report_usage("Geo Editor ToolBuffer()")
  99. FlatCAMTool.run(self)
  100. # if the splitter us hidden, display it
  101. if self.app.ui.splitter.sizes()[0] == 0:
  102. self.app.ui.splitter.setSizes([1, 1])
  103. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  104. def on_buffer(self):
  105. try:
  106. buffer_distance = float(self.buffer_distance_entry.get_value())
  107. except ValueError:
  108. # try to convert comma to decimal point. if it's still not working error message and return
  109. try:
  110. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  111. self.buffer_distance_entry.set_value(buffer_distance)
  112. except ValueError:
  113. self.app.inform.emit('[WARNING_NOTCL] %s' %
  114. _("Buffer distance value is missing or wrong format. Add it and retry."))
  115. return
  116. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  117. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  118. join_style = self.buffer_corner_cb.currentIndex() + 1
  119. self.draw_app.buffer(buffer_distance, join_style)
  120. def on_buffer_int(self):
  121. try:
  122. buffer_distance = float(self.buffer_distance_entry.get_value())
  123. except ValueError:
  124. # try to convert comma to decimal point. if it's still not working error message and return
  125. try:
  126. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  127. self.buffer_distance_entry.set_value(buffer_distance)
  128. except ValueError:
  129. self.app.inform.emit('[WARNING_NOTCL] %s' %
  130. _("Buffer distance value is missing or wrong format. Add it and retry."))
  131. return
  132. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  133. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  134. join_style = self.buffer_corner_cb.currentIndex() + 1
  135. self.draw_app.buffer_int(buffer_distance, join_style)
  136. def on_buffer_ext(self):
  137. try:
  138. buffer_distance = float(self.buffer_distance_entry.get_value())
  139. except ValueError:
  140. # try to convert comma to decimal point. if it's still not working error message and return
  141. try:
  142. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  143. self.buffer_distance_entry.set_value(buffer_distance)
  144. except ValueError:
  145. self.app.inform.emit('[WARNING_NOTCL] %s' %
  146. _("Buffer distance value is missing or wrong format. Add it and retry."))
  147. return
  148. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  149. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  150. join_style = self.buffer_corner_cb.currentIndex() + 1
  151. self.draw_app.buffer_ext(buffer_distance, join_style)
  152. def hide_tool(self):
  153. self.buffer_tool_frame.hide()
  154. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  155. class TextInputTool(FlatCAMTool):
  156. """
  157. Simple input for buffer distance.
  158. """
  159. toolName = "Text Input Tool"
  160. def __init__(self, app):
  161. FlatCAMTool.__init__(self, app)
  162. self.app = app
  163. self.text_path = []
  164. self.f_parse = ParseFont(self)
  165. self.f_parse.get_fonts_by_types()
  166. # this way I can hide/show the frame
  167. self.text_tool_frame = QtWidgets.QFrame()
  168. self.text_tool_frame.setContentsMargins(0, 0, 0, 0)
  169. self.layout.addWidget(self.text_tool_frame)
  170. self.text_tools_box = QtWidgets.QVBoxLayout()
  171. self.text_tools_box.setContentsMargins(0, 0, 0, 0)
  172. self.text_tool_frame.setLayout(self.text_tools_box)
  173. # Title
  174. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  175. title_label.setStyleSheet("""
  176. QLabel
  177. {
  178. font-size: 16px;
  179. font-weight: bold;
  180. }
  181. """)
  182. self.text_tools_box.addWidget(title_label)
  183. # Form Layout
  184. self.form_layout = QtWidgets.QFormLayout()
  185. self.text_tools_box.addLayout(self.form_layout)
  186. # Font type
  187. if sys.platform == "win32":
  188. f_current = QtGui.QFont("Arial")
  189. elif sys.platform == "linux":
  190. f_current = QtGui.QFont("FreeMono")
  191. else:
  192. f_current = QtGui.QFont("Helvetica Neue")
  193. self.font_name = f_current.family()
  194. self.font_type_cb = QtWidgets.QFontComboBox(self)
  195. self.font_type_cb.setCurrentFont(f_current)
  196. self.form_layout.addRow("Font:", self.font_type_cb)
  197. # Flag variables to show if font is bold, italic, both or none (regular)
  198. self.font_bold = False
  199. self.font_italic = False
  200. # # Create dictionaries with the filenames of the fonts
  201. # # Key: Fontname
  202. # # Value: Font File Name.ttf
  203. #
  204. # # regular fonts
  205. # self.ff_names_regular ={}
  206. # # bold fonts
  207. # self.ff_names_bold = {}
  208. # # italic fonts
  209. # self.ff_names_italic = {}
  210. # # bold and italic fonts
  211. # self.ff_names_bi = {}
  212. #
  213. # if sys.platform == 'win32':
  214. # from winreg import ConnectRegistry, OpenKey, EnumValue, HKEY_LOCAL_MACHINE
  215. # registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
  216. # font_key = OpenKey(registry, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts")
  217. # try:
  218. # i = 0
  219. # while 1:
  220. # name_font, value, type = EnumValue(font_key, i)
  221. # k = name_font.replace(" (TrueType)", '')
  222. # if 'Bold' in k and 'Italic' in k:
  223. # k = k.replace(" Bold Italic", '')
  224. # self.ff_names_bi.update({k: value})
  225. # elif 'Bold' in k:
  226. # k = k.replace(" Bold", '')
  227. # self.ff_names_bold.update({k: value})
  228. # elif 'Italic' in k:
  229. # k = k.replace(" Italic", '')
  230. # self.ff_names_italic.update({k: value})
  231. # else:
  232. # self.ff_names_regular.update({k: value})
  233. # i += 1
  234. # except WindowsError:
  235. # pass
  236. # Font size
  237. self.font_size_cb = FCComboBox()
  238. self.font_size_cb.setEditable(True)
  239. self.font_size_cb.setMinimumContentsLength(3)
  240. self.font_size_cb.setMaximumWidth(70)
  241. font_sizes = ['6', '7', '8', '9', '10', '11', '12', '13', '14',
  242. '15', '16', '18', '20', '22', '24', '26', '28',
  243. '32', '36', '40', '44', '48', '54', '60', '66',
  244. '72', '80', '88', '96']
  245. for i in font_sizes:
  246. self.font_size_cb.addItem(i)
  247. self.font_size_cb.setCurrentIndex(4)
  248. hlay = QtWidgets.QHBoxLayout()
  249. hlay.addWidget(self.font_size_cb)
  250. hlay.addStretch()
  251. self.font_bold_tb = QtWidgets.QToolButton()
  252. self.font_bold_tb.setCheckable(True)
  253. self.font_bold_tb.setIcon(QtGui.QIcon('share/bold32.png'))
  254. hlay.addWidget(self.font_bold_tb)
  255. self.font_italic_tb = QtWidgets.QToolButton()
  256. self.font_italic_tb.setCheckable(True)
  257. self.font_italic_tb.setIcon(QtGui.QIcon('share/italic32.png'))
  258. hlay.addWidget(self.font_italic_tb)
  259. self.form_layout.addRow("Size:", hlay)
  260. # Text input
  261. self.text_input_entry = FCTextAreaRich()
  262. self.text_input_entry.setTabStopWidth(12)
  263. self.text_input_entry.setMinimumHeight(200)
  264. # self.text_input_entry.setMaximumHeight(150)
  265. self.text_input_entry.setCurrentFont(f_current)
  266. self.text_input_entry.setFontPointSize(10)
  267. self.form_layout.addRow("Text:", self.text_input_entry)
  268. # Buttons
  269. hlay1 = QtWidgets.QHBoxLayout()
  270. self.form_layout.addRow("", hlay1)
  271. hlay1.addStretch()
  272. self.apply_button = QtWidgets.QPushButton("Apply")
  273. hlay1.addWidget(self.apply_button)
  274. # self.layout.addStretch()
  275. # Signals
  276. self.apply_button.clicked.connect(self.on_apply_button)
  277. self.font_type_cb.currentFontChanged.connect(self.font_family)
  278. self.font_size_cb.activated.connect(self.font_size)
  279. self.font_bold_tb.clicked.connect(self.on_bold_button)
  280. self.font_italic_tb.clicked.connect(self.on_italic_button)
  281. def run(self):
  282. self.app.report_usage("Geo Editor TextInputTool()")
  283. FlatCAMTool.run(self)
  284. # if the splitter us hidden, display it
  285. if self.app.ui.splitter.sizes()[0] == 0:
  286. self.app.ui.splitter.setSizes([1, 1])
  287. self.app.ui.notebook.setTabText(2, _("Text Tool"))
  288. def on_apply_button(self):
  289. font_to_geo_type = ""
  290. if self.font_bold is True:
  291. font_to_geo_type = 'bold'
  292. elif self.font_italic is True:
  293. font_to_geo_type = 'italic'
  294. elif self.font_bold is True and self.font_italic is True:
  295. font_to_geo_type = 'bi'
  296. elif self.font_bold is False and self.font_italic is False:
  297. font_to_geo_type = 'regular'
  298. string_to_geo = self.text_input_entry.get_value()
  299. font_to_geo_size = self.font_size_cb.get_value()
  300. self.text_path = self.f_parse.font_to_geometry(
  301. char_string=string_to_geo,
  302. font_name=self.font_name,
  303. font_size=font_to_geo_size,
  304. font_type=font_to_geo_type,
  305. units=self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper())
  306. def font_family(self, font):
  307. self.text_input_entry.selectAll()
  308. font.setPointSize(float(self.font_size_cb.get_value()))
  309. self.text_input_entry.setCurrentFont(font)
  310. self.font_name = self.font_type_cb.currentFont().family()
  311. def font_size(self):
  312. self.text_input_entry.selectAll()
  313. self.text_input_entry.setFontPointSize(float(self.font_size_cb.get_value()))
  314. def on_bold_button(self):
  315. if self.font_bold_tb.isChecked():
  316. self.text_input_entry.selectAll()
  317. self.text_input_entry.setFontWeight(QtGui.QFont.Bold)
  318. self.font_bold = True
  319. else:
  320. self.text_input_entry.selectAll()
  321. self.text_input_entry.setFontWeight(QtGui.QFont.Normal)
  322. self.font_bold = False
  323. def on_italic_button(self):
  324. if self.font_italic_tb.isChecked():
  325. self.text_input_entry.selectAll()
  326. self.text_input_entry.setFontItalic(True)
  327. self.font_italic = True
  328. else:
  329. self.text_input_entry.selectAll()
  330. self.text_input_entry.setFontItalic(False)
  331. self.font_italic = False
  332. def hide_tool(self):
  333. self.text_tool_frame.hide()
  334. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  335. self.app.ui.splitter.setSizes([0, 1])
  336. self.app.ui.notebook.setTabText(2, _("Tool"))
  337. class PaintOptionsTool(FlatCAMTool):
  338. """
  339. Inputs to specify how to paint the selected polygons.
  340. """
  341. toolName = "Paint Tool"
  342. def __init__(self, app, fcdraw):
  343. FlatCAMTool.__init__(self, app)
  344. self.app = app
  345. self.fcdraw = fcdraw
  346. # Title
  347. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  348. title_label.setStyleSheet("""
  349. QLabel
  350. {
  351. font-size: 16px;
  352. font-weight: bold;
  353. }
  354. """)
  355. self.layout.addWidget(title_label)
  356. grid = QtWidgets.QGridLayout()
  357. self.layout.addLayout(grid)
  358. # Tool dia
  359. ptdlabel = QtWidgets.QLabel('%s:' % _('Tool dia'))
  360. ptdlabel.setToolTip(
  361. _("Diameter of the tool to\n"
  362. "be used in the operation.")
  363. )
  364. grid.addWidget(ptdlabel, 0, 0)
  365. self.painttooldia_entry = FCEntry()
  366. grid.addWidget(self.painttooldia_entry, 0, 1)
  367. # Overlap
  368. ovlabel = QtWidgets.QLabel('%s:' % _('Overlap Rate'))
  369. ovlabel.setToolTip(
  370. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  371. "Example:\n"
  372. "A value here of 0.25 means 25%% from the tool diameter found above.\n\n"
  373. "Adjust the value starting with lower values\n"
  374. "and increasing it if areas that should be painted are still \n"
  375. "not painted.\n"
  376. "Lower values = faster processing, faster execution on PCB.\n"
  377. "Higher values = slow processing and slow execution on CNC\n"
  378. "due of too many paths.")
  379. )
  380. grid.addWidget(ovlabel, 1, 0)
  381. self.paintoverlap_entry = FCEntry()
  382. self.paintoverlap_entry.setValidator(QtGui.QDoubleValidator(0.0000, 1.0000, 4))
  383. grid.addWidget(self.paintoverlap_entry, 1, 1)
  384. # Margin
  385. marginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  386. marginlabel.setToolTip(
  387. _("Distance by which to avoid\n"
  388. "the edges of the polygon to\n"
  389. "be painted.")
  390. )
  391. grid.addWidget(marginlabel, 2, 0)
  392. self.paintmargin_entry = FCEntry()
  393. grid.addWidget(self.paintmargin_entry, 2, 1)
  394. # Method
  395. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  396. methodlabel.setToolTip(
  397. _("Algorithm to paint the polygon:<BR>"
  398. "<B>Standard</B>: Fixed step inwards.<BR>"
  399. "<B>Seed-based</B>: Outwards from seed.")
  400. )
  401. grid.addWidget(methodlabel, 3, 0)
  402. self.paintmethod_combo = RadioSet([
  403. {"label": _("Standard"), "value": "standard"},
  404. {"label": _("Seed-based"), "value": "seed"},
  405. {"label": _("Straight lines"), "value": "lines"}
  406. ], orientation='vertical', stretch=False)
  407. grid.addWidget(self.paintmethod_combo, 3, 1)
  408. # Connect lines
  409. pathconnectlabel = QtWidgets.QLabel(_("Connect:"))
  410. pathconnectlabel.setToolTip(
  411. _("Draw lines between resulting\n"
  412. "segments to minimize tool lifts.")
  413. )
  414. grid.addWidget(pathconnectlabel, 4, 0)
  415. self.pathconnect_cb = FCCheckBox()
  416. grid.addWidget(self.pathconnect_cb, 4, 1)
  417. contourlabel = QtWidgets.QLabel(_("Contour:"))
  418. contourlabel.setToolTip(
  419. _("Cut around the perimeter of the polygon\n"
  420. "to trim rough edges.")
  421. )
  422. grid.addWidget(contourlabel, 5, 0)
  423. self.paintcontour_cb = FCCheckBox()
  424. grid.addWidget(self.paintcontour_cb, 5, 1)
  425. # Buttons
  426. hlay = QtWidgets.QHBoxLayout()
  427. self.layout.addLayout(hlay)
  428. hlay.addStretch()
  429. self.paint_button = QtWidgets.QPushButton(_("Paint"))
  430. hlay.addWidget(self.paint_button)
  431. self.layout.addStretch()
  432. # Signals
  433. self.paint_button.clicked.connect(self.on_paint)
  434. self.set_tool_ui()
  435. def run(self):
  436. self.app.report_usage("Geo Editor ToolPaint()")
  437. FlatCAMTool.run(self)
  438. # if the splitter us hidden, display it
  439. if self.app.ui.splitter.sizes()[0] == 0:
  440. self.app.ui.splitter.setSizes([1, 1])
  441. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  442. def set_tool_ui(self):
  443. # Init GUI
  444. if self.app.defaults["tools_painttooldia"]:
  445. self.painttooldia_entry.set_value(self.app.defaults["tools_painttooldia"])
  446. else:
  447. self.painttooldia_entry.set_value(0.0)
  448. if self.app.defaults["tools_paintoverlap"]:
  449. self.paintoverlap_entry.set_value(self.app.defaults["tools_paintoverlap"])
  450. else:
  451. self.paintoverlap_entry.set_value(0.0)
  452. if self.app.defaults["tools_paintmargin"]:
  453. self.paintmargin_entry.set_value(self.app.defaults["tools_paintmargin"])
  454. else:
  455. self.paintmargin_entry.set_value(0.0)
  456. if self.app.defaults["tools_paintmethod"]:
  457. self.paintmethod_combo.set_value(self.app.defaults["tools_paintmethod"])
  458. else:
  459. self.paintmethod_combo.set_value("seed")
  460. if self.app.defaults["tools_pathconnect"]:
  461. self.pathconnect_cb.set_value(self.app.defaults["tools_pathconnect"])
  462. else:
  463. self.pathconnect_cb.set_value(False)
  464. if self.app.defaults["tools_paintcontour"]:
  465. self.paintcontour_cb.set_value(self.app.defaults["tools_paintcontour"])
  466. else:
  467. self.paintcontour_cb.set_value(False)
  468. def on_paint(self):
  469. if not self.fcdraw.selected:
  470. self.app.inform.emit('[WARNING_NOTCL] %s' %
  471. _("Paint cancelled. No shape selected."))
  472. return
  473. try:
  474. tooldia = float(self.painttooldia_entry.get_value())
  475. except ValueError:
  476. # try to convert comma to decimal point. if it's still not working error message and return
  477. try:
  478. tooldia = float(self.painttooldia_entry.get_value().replace(',', '.'))
  479. self.painttooldia_entry.set_value(tooldia)
  480. except ValueError:
  481. self.app.inform.emit('[WARNING_NOTCL] %s' %
  482. _("Tool diameter value is missing or wrong format. Add it and retry."))
  483. return
  484. try:
  485. overlap = float(self.paintoverlap_entry.get_value())
  486. except ValueError:
  487. # try to convert comma to decimal point. if it's still not working error message and return
  488. try:
  489. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  490. self.paintoverlap_entry.set_value(overlap)
  491. except ValueError:
  492. self.app.inform.emit('[WARNING_NOTCL] %s' %
  493. _("Overlap value is missing or wrong format. Add it and retry."))
  494. return
  495. try:
  496. margin = float(self.paintmargin_entry.get_value())
  497. except ValueError:
  498. # try to convert comma to decimal point. if it's still not working error message and return
  499. try:
  500. margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  501. self.paintmargin_entry.set_value(margin)
  502. except ValueError:
  503. self.app.inform.emit('[WARNING_NOTCL] %s' %
  504. _("Margin distance value is missing or wrong format. Add it and retry."))
  505. return
  506. method = self.paintmethod_combo.get_value()
  507. contour = self.paintcontour_cb.get_value()
  508. connect = self.pathconnect_cb.get_value()
  509. self.fcdraw.paint(tooldia, overlap, margin, connect=connect, contour=contour, method=method)
  510. self.fcdraw.select_tool("select")
  511. self.app.ui.notebook.setTabText(2, _("Tools"))
  512. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  513. self.app.ui.splitter.setSizes([0, 1])
  514. class TransformEditorTool(FlatCAMTool):
  515. """
  516. Inputs to specify how to paint the selected polygons.
  517. """
  518. toolName = _("Transform Tool")
  519. rotateName = _("Rotate")
  520. skewName = _("Skew/Shear")
  521. scaleName = _("Scale")
  522. flipName = _("Mirror (Flip)")
  523. offsetName = _("Offset")
  524. def __init__(self, app, draw_app):
  525. FlatCAMTool.__init__(self, app)
  526. self.app = app
  527. self.draw_app = draw_app
  528. self.transform_lay = QtWidgets.QVBoxLayout()
  529. self.layout.addLayout(self.transform_lay)
  530. # ## Title
  531. title_label = QtWidgets.QLabel("%s %s" % (_('Editor'), str(self.toolName)))
  532. title_label.setStyleSheet("""
  533. QLabel
  534. {
  535. font-size: 16px;
  536. font-weight: bold;
  537. }
  538. """)
  539. self.transform_lay.addWidget(title_label)
  540. self.empty_label = QtWidgets.QLabel("")
  541. self.empty_label.setMinimumWidth(50)
  542. self.empty_label1 = QtWidgets.QLabel("")
  543. self.empty_label1.setMinimumWidth(70)
  544. self.empty_label2 = QtWidgets.QLabel("")
  545. self.empty_label2.setMinimumWidth(70)
  546. self.empty_label3 = QtWidgets.QLabel("")
  547. self.empty_label3.setMinimumWidth(70)
  548. self.empty_label4 = QtWidgets.QLabel("")
  549. self.empty_label4.setMinimumWidth(70)
  550. self.transform_lay.addWidget(self.empty_label)
  551. # Rotate Title
  552. rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName)
  553. self.transform_lay.addWidget(rotate_title_label)
  554. # Layout
  555. form_layout = QtWidgets.QFormLayout()
  556. self.transform_lay.addLayout(form_layout)
  557. form_child = QtWidgets.QHBoxLayout()
  558. self.rotate_label = QtWidgets.QLabel(_("Angle:"))
  559. self.rotate_label.setToolTip(
  560. _("Angle for Rotation action, in degrees.\n"
  561. "Float number between -360 and 359.\n"
  562. "Positive numbers for CW motion.\n"
  563. "Negative numbers for CCW motion.")
  564. )
  565. self.rotate_label.setFixedWidth(50)
  566. self.rotate_entry = FCEntry()
  567. # self.rotate_entry.setFixedWidth(60)
  568. self.rotate_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  569. self.rotate_button = FCButton()
  570. self.rotate_button.set_value(_("Rotate"))
  571. self.rotate_button.setToolTip(
  572. _("Rotate the selected shape(s).\n"
  573. "The point of reference is the middle of\n"
  574. "the bounding box for all selected shapes.")
  575. )
  576. self.rotate_button.setFixedWidth(60)
  577. form_child.addWidget(self.rotate_entry)
  578. form_child.addWidget(self.rotate_button)
  579. form_layout.addRow(self.rotate_label, form_child)
  580. self.transform_lay.addWidget(self.empty_label1)
  581. # Skew Title
  582. skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName)
  583. self.transform_lay.addWidget(skew_title_label)
  584. # Form Layout
  585. form1_layout = QtWidgets.QFormLayout()
  586. self.transform_lay.addLayout(form1_layout)
  587. form1_child_1 = QtWidgets.QHBoxLayout()
  588. form1_child_2 = QtWidgets.QHBoxLayout()
  589. self.skewx_label = QtWidgets.QLabel(_("Angle X:"))
  590. self.skewx_label.setToolTip(
  591. _("Angle for Skew action, in degrees.\n"
  592. "Float number between -360 and 359.")
  593. )
  594. self.skewx_label.setFixedWidth(50)
  595. self.skewx_entry = FCEntry()
  596. self.skewx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  597. # self.skewx_entry.setFixedWidth(60)
  598. self.skewx_button = FCButton()
  599. self.skewx_button.set_value(_("Skew X"))
  600. self.skewx_button.setToolTip(
  601. _("Skew/shear the selected shape(s).\n"
  602. "The point of reference is the middle of\n"
  603. "the bounding box for all selected shapes."))
  604. self.skewx_button.setFixedWidth(60)
  605. self.skewy_label = QtWidgets.QLabel(_("Angle Y:"))
  606. self.skewy_label.setToolTip(
  607. _("Angle for Skew action, in degrees.\n"
  608. "Float number between -360 and 359.")
  609. )
  610. self.skewy_label.setFixedWidth(50)
  611. self.skewy_entry = FCEntry()
  612. self.skewy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  613. # self.skewy_entry.setFixedWidth(60)
  614. self.skewy_button = FCButton()
  615. self.skewy_button.set_value(_("Skew Y"))
  616. self.skewy_button.setToolTip(
  617. _("Skew/shear the selected shape(s).\n"
  618. "The point of reference is the middle of\n"
  619. "the bounding box for all selected shapes."))
  620. self.skewy_button.setFixedWidth(60)
  621. form1_child_1.addWidget(self.skewx_entry)
  622. form1_child_1.addWidget(self.skewx_button)
  623. form1_child_2.addWidget(self.skewy_entry)
  624. form1_child_2.addWidget(self.skewy_button)
  625. form1_layout.addRow(self.skewx_label, form1_child_1)
  626. form1_layout.addRow(self.skewy_label, form1_child_2)
  627. self.transform_lay.addWidget(self.empty_label2)
  628. # Scale Title
  629. scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName)
  630. self.transform_lay.addWidget(scale_title_label)
  631. # Form Layout
  632. form2_layout = QtWidgets.QFormLayout()
  633. self.transform_lay.addLayout(form2_layout)
  634. form2_child_1 = QtWidgets.QHBoxLayout()
  635. form2_child_2 = QtWidgets.QHBoxLayout()
  636. self.scalex_label = QtWidgets.QLabel(_("Factor X:"))
  637. self.scalex_label.setToolTip(
  638. _("Factor for Scale action over X axis.")
  639. )
  640. self.scalex_label.setFixedWidth(50)
  641. self.scalex_entry = FCEntry()
  642. self.scalex_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  643. # self.scalex_entry.setFixedWidth(60)
  644. self.scalex_button = FCButton()
  645. self.scalex_button.set_value(_("Scale X"))
  646. self.scalex_button.setToolTip(
  647. _("Scale the selected shape(s).\n"
  648. "The point of reference depends on \n"
  649. "the Scale reference checkbox state."))
  650. self.scalex_button.setFixedWidth(60)
  651. self.scaley_label = QtWidgets.QLabel(_("Factor Y:"))
  652. self.scaley_label.setToolTip(
  653. _("Factor for Scale action over Y axis.")
  654. )
  655. self.scaley_label.setFixedWidth(50)
  656. self.scaley_entry = FCEntry()
  657. self.scaley_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  658. # self.scaley_entry.setFixedWidth(60)
  659. self.scaley_button = FCButton()
  660. self.scaley_button.set_value(_("Scale Y"))
  661. self.scaley_button.setToolTip(
  662. _("Scale the selected shape(s).\n"
  663. "The point of reference depends on \n"
  664. "the Scale reference checkbox state."))
  665. self.scaley_button.setFixedWidth(60)
  666. self.scale_link_cb = FCCheckBox()
  667. self.scale_link_cb.set_value(True)
  668. self.scale_link_cb.setText(_("Link"))
  669. self.scale_link_cb.setToolTip(
  670. _("Scale the selected shape(s)\n"
  671. "using the Scale Factor X for both axis."))
  672. self.scale_link_cb.setFixedWidth(50)
  673. self.scale_zero_ref_cb = FCCheckBox()
  674. self.scale_zero_ref_cb.set_value(True)
  675. self.scale_zero_ref_cb.setText(_("Scale Reference"))
  676. self.scale_zero_ref_cb.setToolTip(
  677. _("Scale the selected shape(s)\n"
  678. "using the origin reference when checked,\n"
  679. "and the center of the biggest bounding box\n"
  680. "of the selected shapes when unchecked."))
  681. form2_child_1.addWidget(self.scalex_entry)
  682. form2_child_1.addWidget(self.scalex_button)
  683. form2_child_2.addWidget(self.scaley_entry)
  684. form2_child_2.addWidget(self.scaley_button)
  685. form2_layout.addRow(self.scalex_label, form2_child_1)
  686. form2_layout.addRow(self.scaley_label, form2_child_2)
  687. form2_layout.addRow(self.scale_link_cb, self.scale_zero_ref_cb)
  688. self.ois_scale = OptionalInputSection(self.scale_link_cb, [self.scaley_entry, self.scaley_button], logic=False)
  689. self.transform_lay.addWidget(self.empty_label3)
  690. # Offset Title
  691. offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName)
  692. self.transform_lay.addWidget(offset_title_label)
  693. # Form Layout
  694. form3_layout = QtWidgets.QFormLayout()
  695. self.transform_lay.addLayout(form3_layout)
  696. form3_child_1 = QtWidgets.QHBoxLayout()
  697. form3_child_2 = QtWidgets.QHBoxLayout()
  698. self.offx_label = QtWidgets.QLabel(_("Value X:"))
  699. self.offx_label.setToolTip(
  700. _("Value for Offset action on X axis.")
  701. )
  702. self.offx_label.setFixedWidth(50)
  703. self.offx_entry = FCEntry()
  704. self.offx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  705. # self.offx_entry.setFixedWidth(60)
  706. self.offx_button = FCButton()
  707. self.offx_button.set_value(_("Offset X"))
  708. self.offx_button.setToolTip(
  709. _("Offset the selected shape(s).\n"
  710. "The point of reference is the middle of\n"
  711. "the bounding box for all selected shapes.\n")
  712. )
  713. self.offx_button.setFixedWidth(60)
  714. self.offy_label = QtWidgets.QLabel(_("Value Y:"))
  715. self.offy_label.setToolTip(
  716. _("Value for Offset action on Y axis.")
  717. )
  718. self.offy_label.setFixedWidth(50)
  719. self.offy_entry = FCEntry()
  720. self.offy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  721. # self.offy_entry.setFixedWidth(60)
  722. self.offy_button = FCButton()
  723. self.offy_button.set_value(_("Offset Y"))
  724. self.offy_button.setToolTip(
  725. _("Offset the selected shape(s).\n"
  726. "The point of reference is the middle of\n"
  727. "the bounding box for all selected shapes.\n")
  728. )
  729. self.offy_button.setFixedWidth(60)
  730. form3_child_1.addWidget(self.offx_entry)
  731. form3_child_1.addWidget(self.offx_button)
  732. form3_child_2.addWidget(self.offy_entry)
  733. form3_child_2.addWidget(self.offy_button)
  734. form3_layout.addRow(self.offx_label, form3_child_1)
  735. form3_layout.addRow(self.offy_label, form3_child_2)
  736. self.transform_lay.addWidget(self.empty_label4)
  737. # Flip Title
  738. flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName)
  739. self.transform_lay.addWidget(flip_title_label)
  740. # Form Layout
  741. form4_layout = QtWidgets.QFormLayout()
  742. form4_child_hlay = QtWidgets.QHBoxLayout()
  743. self.transform_lay.addLayout(form4_child_hlay)
  744. self.transform_lay.addLayout(form4_layout)
  745. form4_child_1 = QtWidgets.QHBoxLayout()
  746. self.flipx_button = FCButton()
  747. self.flipx_button.set_value(_("Flip on X"))
  748. self.flipx_button.setToolTip(
  749. _("Flip the selected shape(s) over the X axis.\n"
  750. "Does not create a new shape.")
  751. )
  752. self.flipx_button.setFixedWidth(60)
  753. self.flipy_button = FCButton()
  754. self.flipy_button.set_value(_("Flip on Y"))
  755. self.flipy_button.setToolTip(
  756. _("Flip the selected shape(s) over the X axis.\n"
  757. "Does not create a new shape.")
  758. )
  759. self.flipy_button.setFixedWidth(60)
  760. self.flip_ref_cb = FCCheckBox()
  761. self.flip_ref_cb.set_value(True)
  762. self.flip_ref_cb.setText(_("Ref Pt"))
  763. self.flip_ref_cb.setToolTip(
  764. _("Flip the selected shape(s)\n"
  765. "around the point in Point Entry Field.\n"
  766. "\n"
  767. "The point coordinates can be captured by\n"
  768. "left click on canvas together with pressing\n"
  769. "SHIFT key. \n"
  770. "Then click Add button to insert coordinates.\n"
  771. "Or enter the coords in format (x, y) in the\n"
  772. "Point Entry field and click Flip on X(Y)")
  773. )
  774. self.flip_ref_cb.setFixedWidth(50)
  775. self.flip_ref_label = QtWidgets.QLabel(_("Point:"))
  776. self.flip_ref_label.setToolTip(
  777. _("Coordinates in format (x, y) used as reference for mirroring.\n"
  778. "The 'x' in (x, y) will be used when using Flip on X and\n"
  779. "the 'y' in (x, y) will be used when using Flip on Y.")
  780. )
  781. self.flip_ref_label.setFixedWidth(50)
  782. self.flip_ref_entry = EvalEntry2("(0, 0)")
  783. self.flip_ref_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  784. # self.flip_ref_entry.setFixedWidth(60)
  785. self.flip_ref_button = FCButton()
  786. self.flip_ref_button.set_value(_("Add"))
  787. self.flip_ref_button.setToolTip(
  788. _("The point coordinates can be captured by\n"
  789. "left click on canvas together with pressing\n"
  790. "SHIFT key. Then click Add button to insert.")
  791. )
  792. self.flip_ref_button.setFixedWidth(60)
  793. form4_child_hlay.addStretch()
  794. form4_child_hlay.addWidget(self.flipx_button)
  795. form4_child_hlay.addWidget(self.flipy_button)
  796. form4_child_1.addWidget(self.flip_ref_entry)
  797. form4_child_1.addWidget(self.flip_ref_button)
  798. form4_layout.addRow(self.flip_ref_cb)
  799. form4_layout.addRow(self.flip_ref_label, form4_child_1)
  800. self.ois_flip = OptionalInputSection(self.flip_ref_cb,
  801. [self.flip_ref_entry, self.flip_ref_button], logic=True)
  802. self.transform_lay.addStretch()
  803. # Signals
  804. self.rotate_button.clicked.connect(self.on_rotate)
  805. self.skewx_button.clicked.connect(self.on_skewx)
  806. self.skewy_button.clicked.connect(self.on_skewy)
  807. self.scalex_button.clicked.connect(self.on_scalex)
  808. self.scaley_button.clicked.connect(self.on_scaley)
  809. self.offx_button.clicked.connect(self.on_offx)
  810. self.offy_button.clicked.connect(self.on_offy)
  811. self.flipx_button.clicked.connect(self.on_flipx)
  812. self.flipy_button.clicked.connect(self.on_flipy)
  813. self.flip_ref_button.clicked.connect(self.on_flip_add_coords)
  814. self.rotate_entry.returnPressed.connect(self.on_rotate)
  815. self.skewx_entry.returnPressed.connect(self.on_skewx)
  816. self.skewy_entry.returnPressed.connect(self.on_skewy)
  817. self.scalex_entry.returnPressed.connect(self.on_scalex)
  818. self.scaley_entry.returnPressed.connect(self.on_scaley)
  819. self.offx_entry.returnPressed.connect(self.on_offx)
  820. self.offy_entry.returnPressed.connect(self.on_offy)
  821. self.set_tool_ui()
  822. def run(self):
  823. self.app.report_usage("Geo Editor Transform Tool()")
  824. FlatCAMTool.run(self)
  825. self.set_tool_ui()
  826. # if the splitter us hidden, display it
  827. if self.app.ui.splitter.sizes()[0] == 0:
  828. self.app.ui.splitter.setSizes([1, 1])
  829. self.app.ui.notebook.setTabText(2, _("Transform Tool"))
  830. def install(self, icon=None, separator=None, **kwargs):
  831. FlatCAMTool.install(self, icon, separator, shortcut='ALT+T', **kwargs)
  832. def set_tool_ui(self):
  833. # Initialize form
  834. if self.app.defaults["tools_transform_rotate"]:
  835. self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"])
  836. else:
  837. self.rotate_entry.set_value(0.0)
  838. if self.app.defaults["tools_transform_skew_x"]:
  839. self.skewx_entry.set_value(self.app.defaults["tools_transform_skew_x"])
  840. else:
  841. self.skewx_entry.set_value(0.0)
  842. if self.app.defaults["tools_transform_skew_y"]:
  843. self.skewy_entry.set_value(self.app.defaults["tools_transform_skew_y"])
  844. else:
  845. self.skewy_entry.set_value(0.0)
  846. if self.app.defaults["tools_transform_scale_x"]:
  847. self.scalex_entry.set_value(self.app.defaults["tools_transform_scale_x"])
  848. else:
  849. self.scalex_entry.set_value(1.0)
  850. if self.app.defaults["tools_transform_scale_y"]:
  851. self.scaley_entry.set_value(self.app.defaults["tools_transform_scale_y"])
  852. else:
  853. self.scaley_entry.set_value(1.0)
  854. if self.app.defaults["tools_transform_scale_link"]:
  855. self.scale_link_cb.set_value(self.app.defaults["tools_transform_scale_link"])
  856. else:
  857. self.scale_link_cb.set_value(True)
  858. if self.app.defaults["tools_transform_scale_reference"]:
  859. self.scale_zero_ref_cb.set_value(self.app.defaults["tools_transform_scale_reference"])
  860. else:
  861. self.scale_zero_ref_cb.set_value(True)
  862. if self.app.defaults["tools_transform_offset_x"]:
  863. self.offx_entry.set_value(self.app.defaults["tools_transform_offset_x"])
  864. else:
  865. self.offx_entry.set_value(0.0)
  866. if self.app.defaults["tools_transform_offset_y"]:
  867. self.offy_entry.set_value(self.app.defaults["tools_transform_offset_y"])
  868. else:
  869. self.offy_entry.set_value(0.0)
  870. if self.app.defaults["tools_transform_mirror_reference"]:
  871. self.flip_ref_cb.set_value(self.app.defaults["tools_transform_mirror_reference"])
  872. else:
  873. self.flip_ref_cb.set_value(False)
  874. if self.app.defaults["tools_transform_mirror_point"]:
  875. self.flip_ref_entry.set_value(self.app.defaults["tools_transform_mirror_point"])
  876. else:
  877. self.flip_ref_entry.set_value((0, 0))
  878. def template(self):
  879. if not self.fcdraw.selected:
  880. self.app.inform.emit('[WARNING_NOTCL] %s' %
  881. _("Transformation cancelled. No shape selected."))
  882. return
  883. self.draw_app.select_tool("select")
  884. self.app.ui.notebook.setTabText(2, "Tools")
  885. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  886. self.app.ui.splitter.setSizes([0, 1])
  887. def on_rotate(self, sig=None, val=None):
  888. if val:
  889. value = val
  890. else:
  891. try:
  892. value = float(self.rotate_entry.get_value())
  893. except ValueError:
  894. # try to convert comma to decimal point. if it's still not working error message and return
  895. try:
  896. value = float(self.rotate_entry.get_value().replace(',', '.'))
  897. except ValueError:
  898. self.app.inform.emit('[ERROR_NOTCL] %s' %
  899. _("Wrong value format entered, use a number."))
  900. return
  901. self.app.worker_task.emit({'fcn': self.on_rotate_action,
  902. 'params': [value]})
  903. # self.on_rotate_action(value)
  904. return
  905. def on_flipx(self):
  906. # self.on_flip("Y")
  907. axis = 'Y'
  908. self.app.worker_task.emit({'fcn': self.on_flip,
  909. 'params': [axis]})
  910. return
  911. def on_flipy(self):
  912. # self.on_flip("X")
  913. axis = 'X'
  914. self.app.worker_task.emit({'fcn': self.on_flip,
  915. 'params': [axis]})
  916. return
  917. def on_flip_add_coords(self):
  918. val = self.app.clipboard.text()
  919. self.flip_ref_entry.set_value(val)
  920. def on_skewx(self, sig=None, val=None):
  921. if val:
  922. value = val
  923. else:
  924. try:
  925. value = float(self.skewx_entry.get_value())
  926. except ValueError:
  927. # try to convert comma to decimal point. if it's still not working error message and return
  928. try:
  929. value = float(self.skewx_entry.get_value().replace(',', '.'))
  930. except ValueError:
  931. self.app.inform.emit('[ERROR_NOTCL] %s' %
  932. _("Wrong value format entered, use a number."))
  933. return
  934. # self.on_skew("X", value)
  935. axis = 'X'
  936. self.app.worker_task.emit({'fcn': self.on_skew,
  937. 'params': [axis, value]})
  938. return
  939. def on_skewy(self, sig=None, val=None):
  940. if val:
  941. value = val
  942. else:
  943. try:
  944. value = float(self.skewy_entry.get_value())
  945. except ValueError:
  946. # try to convert comma to decimal point. if it's still not working error message and return
  947. try:
  948. value = float(self.skewy_entry.get_value().replace(',', '.'))
  949. except ValueError:
  950. self.app.inform.emit('[ERROR_NOTCL] %s' %
  951. _("Wrong value format entered, use a number."))
  952. return
  953. # self.on_skew("Y", value)
  954. axis = 'Y'
  955. self.app.worker_task.emit({'fcn': self.on_skew,
  956. 'params': [axis, value]})
  957. return
  958. def on_scalex(self, sig=None, val=None):
  959. if val:
  960. xvalue = val
  961. else:
  962. try:
  963. xvalue = float(self.scalex_entry.get_value())
  964. except ValueError:
  965. # try to convert comma to decimal point. if it's still not working error message and return
  966. try:
  967. xvalue = float(self.scalex_entry.get_value().replace(',', '.'))
  968. except ValueError:
  969. self.app.inform.emit('[ERROR_NOTCL] %s' %
  970. _("Wrong value format entered, use a number."))
  971. return
  972. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  973. if xvalue == 0:
  974. xvalue = 1
  975. if self.scale_link_cb.get_value():
  976. yvalue = xvalue
  977. else:
  978. yvalue = 1
  979. axis = 'X'
  980. point = (0, 0)
  981. if self.scale_zero_ref_cb.get_value():
  982. self.app.worker_task.emit({'fcn': self.on_scale,
  983. 'params': [axis, xvalue, yvalue, point]})
  984. # self.on_scale("X", xvalue, yvalue, point=(0,0))
  985. else:
  986. # self.on_scale("X", xvalue, yvalue)
  987. self.app.worker_task.emit({'fcn': self.on_scale,
  988. 'params': [axis, xvalue, yvalue]})
  989. return
  990. def on_scaley(self, sig=None, val=None):
  991. xvalue = 1
  992. if val:
  993. yvalue = val
  994. else:
  995. try:
  996. yvalue = float(self.scaley_entry.get_value())
  997. except ValueError:
  998. # try to convert comma to decimal point. if it's still not working error message and return
  999. try:
  1000. yvalue = float(self.scaley_entry.get_value().replace(',', '.'))
  1001. except ValueError:
  1002. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1003. _("Wrong value format entered, use a number."))
  1004. return
  1005. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  1006. if yvalue == 0:
  1007. yvalue = 1
  1008. axis = 'Y'
  1009. point = (0, 0)
  1010. if self.scale_zero_ref_cb.get_value():
  1011. self.app.worker_task.emit({'fcn': self.on_scale,
  1012. 'params': [axis, xvalue, yvalue, point]})
  1013. # self.on_scale("Y", xvalue, yvalue, point=(0,0))
  1014. else:
  1015. # self.on_scale("Y", xvalue, yvalue)
  1016. self.app.worker_task.emit({'fcn': self.on_scale,
  1017. 'params': [axis, xvalue, yvalue]})
  1018. return
  1019. def on_offx(self, sig=None, val=None):
  1020. if val:
  1021. value = val
  1022. else:
  1023. try:
  1024. value = float(self.offx_entry.get_value())
  1025. except ValueError:
  1026. # try to convert comma to decimal point. if it's still not working error message and return
  1027. try:
  1028. value = float(self.offx_entry.get_value().replace(',', '.'))
  1029. except ValueError:
  1030. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1031. _("Wrong value format entered, use a number."))
  1032. return
  1033. # self.on_offset("X", value)
  1034. axis = 'X'
  1035. self.app.worker_task.emit({'fcn': self.on_offset,
  1036. 'params': [axis, value]})
  1037. return
  1038. def on_offy(self, sig=None, val=None):
  1039. if val:
  1040. value = val
  1041. else:
  1042. try:
  1043. value = float(self.offy_entry.get_value())
  1044. except ValueError:
  1045. # try to convert comma to decimal point. if it's still not working error message and return
  1046. try:
  1047. value = float(self.offy_entry.get_value().replace(',', '.'))
  1048. except ValueError:
  1049. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1050. _("Wrong value format entered, use a number."))
  1051. return
  1052. # self.on_offset("Y", value)
  1053. axis = 'Y'
  1054. self.app.worker_task.emit({'fcn': self.on_offset,
  1055. 'params': [axis, value]})
  1056. return
  1057. def on_rotate_action(self, num):
  1058. shape_list = self.draw_app.selected
  1059. xminlist = []
  1060. yminlist = []
  1061. xmaxlist = []
  1062. ymaxlist = []
  1063. if not shape_list:
  1064. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1065. _("No shape selected. Please Select a shape to rotate!"))
  1066. return
  1067. else:
  1068. with self.app.proc_container.new(_("Appying Rotate")):
  1069. try:
  1070. # first get a bounding box to fit all
  1071. for sha in shape_list:
  1072. xmin, ymin, xmax, ymax = sha.bounds()
  1073. xminlist.append(xmin)
  1074. yminlist.append(ymin)
  1075. xmaxlist.append(xmax)
  1076. ymaxlist.append(ymax)
  1077. # get the minimum x,y and maximum x,y for all objects selected
  1078. xminimal = min(xminlist)
  1079. yminimal = min(yminlist)
  1080. xmaximal = max(xmaxlist)
  1081. ymaximal = max(ymaxlist)
  1082. self.app.progress.emit(20)
  1083. for sel_sha in shape_list:
  1084. px = 0.5 * (xminimal + xmaximal)
  1085. py = 0.5 * (yminimal + ymaximal)
  1086. sel_sha.rotate(-num, point=(px, py))
  1087. self.draw_app.replot()
  1088. # self.draw_app.add_shape(DrawToolShape(sel_sha.geo))
  1089. # self.draw_app.transform_complete.emit()
  1090. self.app.inform.emit('[success] %s' %
  1091. _("Done. Rotate completed."))
  1092. self.app.progress.emit(100)
  1093. except Exception as e:
  1094. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  1095. (_("Rotation action was not executed"),str(e)))
  1096. return
  1097. def on_flip(self, axis):
  1098. shape_list = self.draw_app.selected
  1099. xminlist = []
  1100. yminlist = []
  1101. xmaxlist = []
  1102. ymaxlist = []
  1103. if not shape_list:
  1104. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1105. _("No shape selected. Please Select a shape to flip!"))
  1106. return
  1107. else:
  1108. with self.app.proc_container.new(_("Applying Flip")):
  1109. try:
  1110. # get mirroring coords from the point entry
  1111. if self.flip_ref_cb.isChecked():
  1112. px, py = eval('{}'.format(self.flip_ref_entry.text()))
  1113. # get mirroing coords from the center of an all-enclosing bounding box
  1114. else:
  1115. # first get a bounding box to fit all
  1116. for sha in shape_list:
  1117. xmin, ymin, xmax, ymax = sha.bounds()
  1118. xminlist.append(xmin)
  1119. yminlist.append(ymin)
  1120. xmaxlist.append(xmax)
  1121. ymaxlist.append(ymax)
  1122. # get the minimum x,y and maximum x,y for all objects selected
  1123. xminimal = min(xminlist)
  1124. yminimal = min(yminlist)
  1125. xmaximal = max(xmaxlist)
  1126. ymaximal = max(ymaxlist)
  1127. px = 0.5 * (xminimal + xmaximal)
  1128. py = 0.5 * (yminimal + ymaximal)
  1129. self.app.progress.emit(20)
  1130. # execute mirroring
  1131. for sha in shape_list:
  1132. if axis is 'X':
  1133. sha.mirror('X', (px, py))
  1134. self.app.inform.emit('[success] %s...' %
  1135. _('Flip on the Y axis done'))
  1136. elif axis is 'Y':
  1137. sha.mirror('Y', (px, py))
  1138. self.app.inform.emit('[success] %s' %
  1139. _('Flip on the X axis done'))
  1140. self.draw_app.replot()
  1141. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1142. #
  1143. # self.draw_app.transform_complete.emit()
  1144. self.app.progress.emit(100)
  1145. except Exception as e:
  1146. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  1147. (_("Flip action was not executed"), str(e)))
  1148. return
  1149. def on_skew(self, axis, num):
  1150. shape_list = self.draw_app.selected
  1151. xminlist = []
  1152. yminlist = []
  1153. if not shape_list:
  1154. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1155. _("No shape selected. Please Select a shape to shear/skew!"))
  1156. return
  1157. else:
  1158. with self.app.proc_container.new(_("Applying Skew")):
  1159. try:
  1160. # first get a bounding box to fit all
  1161. for sha in shape_list:
  1162. xmin, ymin, xmax, ymax = sha.bounds()
  1163. xminlist.append(xmin)
  1164. yminlist.append(ymin)
  1165. # get the minimum x,y and maximum x,y for all objects selected
  1166. xminimal = min(xminlist)
  1167. yminimal = min(yminlist)
  1168. self.app.progress.emit(20)
  1169. for sha in shape_list:
  1170. if axis is 'X':
  1171. sha.skew(num, 0, point=(xminimal, yminimal))
  1172. elif axis is 'Y':
  1173. sha.skew(0, num, point=(xminimal, yminimal))
  1174. self.draw_app.replot()
  1175. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1176. #
  1177. # self.draw_app.transform_complete.emit()
  1178. if axis == 'X':
  1179. self.app.inform.emit('[success] %s...' %
  1180. _('Skew on the X axis done'))
  1181. else:
  1182. self.app.inform.emit('[success] %s...' %
  1183. _('Skew on the Y axis done'))
  1184. self.app.progress.emit(100)
  1185. except Exception as e:
  1186. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  1187. (_("Skew action was not executed"), str(e)))
  1188. return
  1189. def on_scale(self, axis, xfactor, yfactor, point=None):
  1190. shape_list = self.draw_app.selected
  1191. xminlist = []
  1192. yminlist = []
  1193. xmaxlist = []
  1194. ymaxlist = []
  1195. if not shape_list:
  1196. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1197. _("No shape selected. Please Select a shape to scale!"))
  1198. return
  1199. else:
  1200. with self.app.proc_container.new(_("Applying Scale")):
  1201. try:
  1202. # first get a bounding box to fit all
  1203. for sha in shape_list:
  1204. xmin, ymin, xmax, ymax = sha.bounds()
  1205. xminlist.append(xmin)
  1206. yminlist.append(ymin)
  1207. xmaxlist.append(xmax)
  1208. ymaxlist.append(ymax)
  1209. # get the minimum x,y and maximum x,y for all objects selected
  1210. xminimal = min(xminlist)
  1211. yminimal = min(yminlist)
  1212. xmaximal = max(xmaxlist)
  1213. ymaximal = max(ymaxlist)
  1214. self.app.progress.emit(20)
  1215. if point is None:
  1216. px = 0.5 * (xminimal + xmaximal)
  1217. py = 0.5 * (yminimal + ymaximal)
  1218. else:
  1219. px = 0
  1220. py = 0
  1221. for sha in shape_list:
  1222. sha.scale(xfactor, yfactor, point=(px, py))
  1223. self.draw_app.replot()
  1224. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1225. #
  1226. # self.draw_app.transform_complete.emit()
  1227. if str(axis) == 'X':
  1228. self.app.inform.emit('[success] %s...' %
  1229. _('Scale on the X axis done'))
  1230. else:
  1231. self.app.inform.emit('[success] %s...' %
  1232. _('Scale on the Y axis done'))
  1233. self.app.progress.emit(100)
  1234. except Exception as e:
  1235. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  1236. (_("Scale action was not executed"), str(e)))
  1237. return
  1238. def on_offset(self, axis, num):
  1239. shape_list = self.draw_app.selected
  1240. xminlist = []
  1241. yminlist = []
  1242. if not shape_list:
  1243. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1244. _("No shape selected. Please Select a shape to offset!"))
  1245. return
  1246. else:
  1247. with self.app.proc_container.new(_("Applying Offset")):
  1248. try:
  1249. self.app.progress.emit(20)
  1250. for sha in shape_list:
  1251. if axis is 'X':
  1252. sha.offset((num, 0))
  1253. elif axis is 'Y':
  1254. sha.offset((0, num))
  1255. self.draw_app.replot()
  1256. if axis == 'X':
  1257. self.app.inform.emit('[success] %s...' %
  1258. _('Offset on the X axis done'))
  1259. else:
  1260. self.app.inform.emit('[success] %s...' %
  1261. _('Offset on the Y axis done'))
  1262. self.app.progress.emit(100)
  1263. except Exception as e:
  1264. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  1265. (_("Offset action was not executed"), str(e)))
  1266. return
  1267. def on_rotate_key(self):
  1268. val_box = FCInputDialog(title=_("Rotate ..."),
  1269. text='%s:' % _('Enter an Angle Value (degrees)'),
  1270. min=-359.9999, max=360.0000, decimals=4,
  1271. init_val=float(self.app.defaults['tools_transform_rotate']))
  1272. val_box.setWindowIcon(QtGui.QIcon('share/rotate.png'))
  1273. val, ok = val_box.get_value()
  1274. if ok:
  1275. self.on_rotate(val=val)
  1276. self.app.inform.emit('[success] %s...' %
  1277. _("Geometry shape rotate done"))
  1278. return
  1279. else:
  1280. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1281. _("Geometry shape rotate cancelled"))
  1282. def on_offx_key(self):
  1283. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  1284. val_box = FCInputDialog(title=_("Offset on X axis ..."),
  1285. text='%s: (%s)' % (_('Enter a distance Value'), str(units)),
  1286. min=-9999.9999, max=10000.0000, decimals=4,
  1287. init_val=float(self.app.defaults['tools_transform_offset_x']))
  1288. val_box.setWindowIcon(QtGui.QIcon('share/offsetx32.png'))
  1289. val, ok = val_box.get_value()
  1290. if ok:
  1291. self.on_offx(val=val)
  1292. self.app.inform.emit('[success] %s' %
  1293. _("Geometry shape offset on X axis done"))
  1294. return
  1295. else:
  1296. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1297. _("Geometry shape offset X cancelled"))
  1298. def on_offy_key(self):
  1299. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  1300. val_box = FCInputDialog(title=_("Offset on Y axis ..."),
  1301. text='%s: (%s)' % (_('Enter a distance Value'), str(units)),
  1302. min=-9999.9999, max=10000.0000, decimals=4,
  1303. init_val=float(self.app.defaults['tools_transform_offset_y']))
  1304. val_box.setWindowIcon(QtGui.QIcon('share/offsety32.png'))
  1305. val, ok = val_box.get_value()
  1306. if ok:
  1307. self.on_offx(val=val)
  1308. self.app.inform.emit('[success] %s...' %
  1309. _("Geometry shape offset on Y axis done"))
  1310. return
  1311. else:
  1312. self.app.inform.emit('[success] %s...' %
  1313. _("Geometry shape offset on Y axis canceled"))
  1314. def on_skewx_key(self):
  1315. val_box = FCInputDialog(title=_("Skew on X axis ..."),
  1316. text='%s:' % _('Enter an Angle Value (degrees)'),
  1317. min=-359.9999, max=360.0000, decimals=4,
  1318. init_val=float(self.app.defaults['tools_transform_skew_x']))
  1319. val_box.setWindowIcon(QtGui.QIcon('share/skewX.png'))
  1320. val, ok = val_box.get_value()
  1321. if ok:
  1322. self.on_skewx(val=val)
  1323. self.app.inform.emit('[success] %s...' %
  1324. _("Geometry shape skew on X axis done"))
  1325. return
  1326. else:
  1327. self.app.inform.emit('[success] %s...' %
  1328. _("Geometry shape skew on X axis canceled"))
  1329. def on_skewy_key(self):
  1330. val_box = FCInputDialog(title=_("Skew on Y axis ..."),
  1331. text='%s:' % _('Enter an Angle Value (degrees)'),
  1332. min=-359.9999, max=360.0000, decimals=4,
  1333. init_val=float(self.app.defaults['tools_transform_skew_y']))
  1334. val_box.setWindowIcon(QtGui.QIcon('share/skewY.png'))
  1335. val, ok = val_box.get_value()
  1336. if ok:
  1337. self.on_skewx(val=val)
  1338. self.app.inform.emit('[success] %s...' %
  1339. _("Geometry shape skew on Y axis done"))
  1340. return
  1341. else:
  1342. self.app.inform.emit('[success] %s...' %
  1343. _("Geometry shape skew on Y axis canceled"))
  1344. class DrawToolShape(object):
  1345. """
  1346. Encapsulates "shapes" under a common class.
  1347. """
  1348. tolerance = None
  1349. @staticmethod
  1350. def get_pts(o):
  1351. """
  1352. Returns a list of all points in the object, where
  1353. the object can be a Polygon, Not a polygon, or a list
  1354. of such. Search is done recursively.
  1355. :param: geometric object
  1356. :return: List of points
  1357. :rtype: list
  1358. """
  1359. pts = []
  1360. # Iterable: descend into each item.
  1361. try:
  1362. for subo in o:
  1363. pts += DrawToolShape.get_pts(subo)
  1364. # Non-iterable
  1365. except TypeError:
  1366. if o is not None:
  1367. # DrawToolShape: descend into .geo.
  1368. if isinstance(o, DrawToolShape):
  1369. pts += DrawToolShape.get_pts(o.geo)
  1370. # Descend into .exerior and .interiors
  1371. elif type(o) == Polygon:
  1372. pts += DrawToolShape.get_pts(o.exterior)
  1373. for i in o.interiors:
  1374. pts += DrawToolShape.get_pts(i)
  1375. elif type(o) == MultiLineString:
  1376. for line in o:
  1377. pts += DrawToolShape.get_pts(line)
  1378. # Has .coords: list them.
  1379. else:
  1380. if DrawToolShape.tolerance is not None:
  1381. pts += list(o.simplify(DrawToolShape.tolerance).coords)
  1382. else:
  1383. pts += list(o.coords)
  1384. else:
  1385. return
  1386. return pts
  1387. def __init__(self, geo=[]):
  1388. # Shapely type or list of such
  1389. self.geo = geo
  1390. self.utility = False
  1391. def get_all_points(self):
  1392. return DrawToolShape.get_pts(self)
  1393. def bounds(self):
  1394. """
  1395. Returns coordinates of rectangular bounds
  1396. of geometry: (xmin, ymin, xmax, ymax).
  1397. """
  1398. # fixed issue of getting bounds only for one level lists of objects
  1399. # now it can get bounds for nested lists of objects
  1400. def bounds_rec(shape_el):
  1401. if type(shape_el) is list:
  1402. minx = Inf
  1403. miny = Inf
  1404. maxx = -Inf
  1405. maxy = -Inf
  1406. for k in shape_el:
  1407. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1408. minx = min(minx, minx_)
  1409. miny = min(miny, miny_)
  1410. maxx = max(maxx, maxx_)
  1411. maxy = max(maxy, maxy_)
  1412. return minx, miny, maxx, maxy
  1413. else:
  1414. # it's a Shapely object, return it's bounds
  1415. return shape_el.bounds
  1416. bounds_coords = bounds_rec(self.geo)
  1417. return bounds_coords
  1418. def mirror(self, axis, point):
  1419. """
  1420. Mirrors the shape around a specified axis passing through
  1421. the given point.
  1422. :param axis: "X" or "Y" indicates around which axis to mirror.
  1423. :type axis: str
  1424. :param point: [x, y] point belonging to the mirror axis.
  1425. :type point: list
  1426. :return: None
  1427. """
  1428. px, py = point
  1429. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1430. def mirror_geom(shape_el):
  1431. if type(shape_el) is list:
  1432. new_obj = []
  1433. for g in shape_el:
  1434. new_obj.append(mirror_geom(g))
  1435. return new_obj
  1436. else:
  1437. return affinity.scale(shape_el, xscale, yscale, origin=(px, py))
  1438. try:
  1439. self.geo = mirror_geom(self.geo)
  1440. except AttributeError:
  1441. log.debug("DrawToolShape.mirror() --> Failed to mirror. No shape selected")
  1442. def rotate(self, angle, point):
  1443. """
  1444. Rotate a shape by an angle (in degrees) around the provided coordinates.
  1445. Parameters
  1446. ----------
  1447. The angle of rotation are specified in degrees (default). Positive angles are
  1448. counter-clockwise and negative are clockwise rotations.
  1449. The point of origin can be a keyword 'center' for the bounding box
  1450. center (default), 'centroid' for the geometry's centroid, a Point object
  1451. or a coordinate tuple (x0, y0).
  1452. See shapely manual for more information:
  1453. http://toblerity.org/shapely/manual.html#affine-transformations
  1454. """
  1455. px, py = point
  1456. def rotate_geom(shape_el):
  1457. if type(shape_el) is list:
  1458. new_obj = []
  1459. for g in shape_el:
  1460. new_obj.append(rotate_geom(g))
  1461. return new_obj
  1462. else:
  1463. return affinity.rotate(shape_el, angle, origin=(px, py))
  1464. try:
  1465. self.geo = rotate_geom(self.geo)
  1466. except AttributeError:
  1467. log.debug("DrawToolShape.rotate() --> Failed to rotate. No shape selected")
  1468. def skew(self, angle_x, angle_y, point):
  1469. """
  1470. Shear/Skew a shape by angles along x and y dimensions.
  1471. Parameters
  1472. ----------
  1473. angle_x, angle_y : float, float
  1474. The shear angle(s) for the x and y axes respectively. These can be
  1475. specified in either degrees (default) or radians by setting
  1476. use_radians=True.
  1477. point: tuple of coordinates (x,y)
  1478. See shapely manual for more information:
  1479. http://toblerity.org/shapely/manual.html#affine-transformations
  1480. """
  1481. px, py = point
  1482. def skew_geom(shape_el):
  1483. if type(shape_el) is list:
  1484. new_obj = []
  1485. for g in shape_el:
  1486. new_obj.append(skew_geom(g))
  1487. return new_obj
  1488. else:
  1489. return affinity.skew(shape_el, angle_x, angle_y, origin=(px, py))
  1490. try:
  1491. self.geo = skew_geom(self.geo)
  1492. except AttributeError:
  1493. log.debug("DrawToolShape.skew() --> Failed to skew. No shape selected")
  1494. def offset(self, vect):
  1495. """
  1496. Offsets all shapes by a given vector/
  1497. :param vect: (x, y) vector by which to offset the shape geometry
  1498. :type vect: tuple
  1499. :return: None
  1500. :rtype: None
  1501. """
  1502. try:
  1503. dx, dy = vect
  1504. except TypeError:
  1505. log.debug("DrawToolShape.offset() --> An (x,y) pair of values are needed. "
  1506. "Probable you entered only one value in the Offset field.")
  1507. return
  1508. def translate_recursion(geom):
  1509. if type(geom) == list:
  1510. geoms = list()
  1511. for local_geom in geom:
  1512. geoms.append(translate_recursion(local_geom))
  1513. return geoms
  1514. else:
  1515. return affinity.translate(geom, xoff=dx, yoff=dy)
  1516. try:
  1517. self.geo = translate_recursion(self.geo)
  1518. except AttributeError:
  1519. log.debug("DrawToolShape.offset() --> Failed to offset. No shape selected")
  1520. def scale(self, xfactor, yfactor=None, point=None):
  1521. """
  1522. Scales all shape geometry by a given factor.
  1523. :param xfactor: Factor by which to scale the shape's geometry/
  1524. :type xfactor: float
  1525. :param yfactor: Factor by which to scale the shape's geometry/
  1526. :type yfactor: float
  1527. :return: None
  1528. :rtype: None
  1529. """
  1530. try:
  1531. xfactor = float(xfactor)
  1532. except:
  1533. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1534. return
  1535. if yfactor is None:
  1536. yfactor = xfactor
  1537. else:
  1538. try:
  1539. yfactor = float(yfactor)
  1540. except:
  1541. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1542. return
  1543. if point is None:
  1544. px = 0
  1545. py = 0
  1546. else:
  1547. px, py = point
  1548. def scale_recursion(geom):
  1549. if type(geom) == list:
  1550. geoms = list()
  1551. for local_geom in geom:
  1552. geoms.append(scale_recursion(local_geom))
  1553. return geoms
  1554. else:
  1555. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  1556. try:
  1557. self.geo = scale_recursion(self.geo)
  1558. except AttributeError:
  1559. log.debug("DrawToolShape.scale() --> Failed to scale. No shape selected")
  1560. class DrawToolUtilityShape(DrawToolShape):
  1561. """
  1562. Utility shapes are temporary geometry in the editor
  1563. to assist in the creation of shapes. For example it
  1564. will show the outline of a rectangle from the first
  1565. point to the current mouse pointer before the second
  1566. point is clicked and the final geometry is created.
  1567. """
  1568. def __init__(self, geo=[]):
  1569. super(DrawToolUtilityShape, self).__init__(geo=geo)
  1570. self.utility = True
  1571. class DrawTool(object):
  1572. """
  1573. Abstract Class representing a tool in the drawing
  1574. program. Can generate geometry, including temporary
  1575. utility geometry that is updated on user clicks
  1576. and mouse motion.
  1577. """
  1578. def __init__(self, draw_app):
  1579. self.draw_app = draw_app
  1580. self.complete = False
  1581. self.points = []
  1582. self.geometry = None # DrawToolShape or None
  1583. def click(self, point):
  1584. """
  1585. :param point: [x, y] Coordinate pair.
  1586. """
  1587. return ""
  1588. def click_release(self, point):
  1589. """
  1590. :param point: [x, y] Coordinate pair.
  1591. """
  1592. return ""
  1593. def on_key(self, key):
  1594. return None
  1595. def utility_geometry(self, data=None):
  1596. return None
  1597. def bounds(self, obj):
  1598. def bounds_rec(o):
  1599. if type(o) is list:
  1600. minx = Inf
  1601. miny = Inf
  1602. maxx = -Inf
  1603. maxy = -Inf
  1604. for k in o:
  1605. try:
  1606. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1607. except Exception as e:
  1608. log.debug("camlib.Gerber.bounds() --> %s" % str(e))
  1609. return
  1610. minx = min(minx, minx_)
  1611. miny = min(miny, miny_)
  1612. maxx = max(maxx, maxx_)
  1613. maxy = max(maxy, maxy_)
  1614. return minx, miny, maxx, maxy
  1615. else:
  1616. # it's a Shapely object, return it's bounds
  1617. return o.geo.bounds
  1618. bounds_coords = bounds_rec(obj)
  1619. return bounds_coords
  1620. class FCShapeTool(DrawTool):
  1621. """
  1622. Abstract class for tools that create a shape.
  1623. """
  1624. def __init__(self, draw_app):
  1625. DrawTool.__init__(self, draw_app)
  1626. def make(self):
  1627. pass
  1628. class FCCircle(FCShapeTool):
  1629. """
  1630. Resulting type: Polygon
  1631. """
  1632. def __init__(self, draw_app):
  1633. DrawTool.__init__(self, draw_app)
  1634. self.name = 'circle'
  1635. try:
  1636. QtGui.QGuiApplication.restoreOverrideCursor()
  1637. except Exception as e:
  1638. pass
  1639. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_circle_geo.png'))
  1640. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1641. self.draw_app.app.inform.emit(_("Click on Center point ..."))
  1642. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1643. def click(self, point):
  1644. self.points.append(point)
  1645. if len(self.points) == 1:
  1646. self.draw_app.app.inform.emit(_("Click on Perimeter point to complete ..."))
  1647. return "Click on perimeter to complete ..."
  1648. if len(self.points) == 2:
  1649. self.make()
  1650. return "Done."
  1651. return ""
  1652. def utility_geometry(self, data=None):
  1653. if len(self.points) == 1:
  1654. p1 = self.points[0]
  1655. p2 = data
  1656. radius = sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
  1657. return DrawToolUtilityShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1658. return None
  1659. def make(self):
  1660. try:
  1661. QtGui.QGuiApplication.restoreOverrideCursor()
  1662. except Exception as e:
  1663. pass
  1664. p1 = self.points[0]
  1665. p2 = self.points[1]
  1666. radius = distance(p1, p2)
  1667. self.geometry = DrawToolShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1668. self.complete = True
  1669. self.draw_app.app.inform.emit('[success] %s' %
  1670. _("Done. Adding Circle completed."))
  1671. class FCArc(FCShapeTool):
  1672. def __init__(self, draw_app):
  1673. DrawTool.__init__(self, draw_app)
  1674. self.name = 'arc'
  1675. try:
  1676. QtGui.QGuiApplication.restoreOverrideCursor()
  1677. except Exception as e:
  1678. pass
  1679. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_arc.png'))
  1680. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1681. self.draw_app.app.inform.emit(_("Click on Center point ..."))
  1682. # Direction of rotation between point 1 and 2.
  1683. # 'cw' or 'ccw'. Switch direction by hitting the
  1684. # 'o' key.
  1685. self.direction = "cw"
  1686. # Mode
  1687. # C12 = Center, p1, p2
  1688. # 12C = p1, p2, Center
  1689. # 132 = p1, p3, p2
  1690. self.mode = "c12" # Center, p1, p2
  1691. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1692. def click(self, point):
  1693. self.points.append(point)
  1694. if len(self.points) == 1:
  1695. if self.mode == 'c12':
  1696. self.draw_app.app.inform.emit(_("Click on Start point ..."))
  1697. elif self.mode == '132':
  1698. self.draw_app.app.inform.emit(_("Click on Point3 ..."))
  1699. else:
  1700. self.draw_app.app.inform.emit(_("Click on Stop point ..."))
  1701. return "Click on 1st point ..."
  1702. if len(self.points) == 2:
  1703. if self.mode == 'c12':
  1704. self.draw_app.app.inform.emit(_("Click on Stop point to complete ..."))
  1705. elif self.mode == '132':
  1706. self.draw_app.app.inform.emit(_("Click on Point2 to complete ..."))
  1707. else:
  1708. self.draw_app.app.inform.emit(_("Click on Center point to complete ..."))
  1709. return "Click on 2nd point to complete ..."
  1710. if len(self.points) == 3:
  1711. self.make()
  1712. return "Done."
  1713. return ""
  1714. def on_key(self, key):
  1715. if key == 'D' or key == QtCore.Qt.Key_D:
  1716. self.direction = 'cw' if self.direction == 'ccw' else 'ccw'
  1717. return _('Direction: %s') % self.direction.upper()
  1718. if key == 'M' or key == QtCore.Qt.Key_M:
  1719. # delete the possible points made before this action; we want to start anew
  1720. self.points[:] = []
  1721. # and delete the utility geometry made up until this point
  1722. self.draw_app.delete_utility_geometry()
  1723. if self.mode == 'c12':
  1724. self.mode = '12c'
  1725. return _('Mode: Start -> Stop -> Center. Click on Start point ...')
  1726. elif self.mode == '12c':
  1727. self.mode = '132'
  1728. return _('Mode: Point1 -> Point3 -> Point2. Click on Point1 ...')
  1729. else:
  1730. self.mode = 'c12'
  1731. return _('Mode: Center -> Start -> Stop. Click on Center point ...')
  1732. def utility_geometry(self, data=None):
  1733. if len(self.points) == 1: # Show the radius
  1734. center = self.points[0]
  1735. p1 = data
  1736. return DrawToolUtilityShape(LineString([center, p1]))
  1737. if len(self.points) == 2: # Show the arc
  1738. if self.mode == 'c12':
  1739. center = self.points[0]
  1740. p1 = self.points[1]
  1741. p2 = data
  1742. radius = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  1743. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1744. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1745. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1746. self.direction, self.steps_per_circ)),
  1747. Point(center)])
  1748. elif self.mode == '132':
  1749. p1 = array(self.points[0])
  1750. p3 = array(self.points[1])
  1751. p2 = array(data)
  1752. try:
  1753. center, radius, t = three_point_circle(p1, p2, p3)
  1754. except TypeError:
  1755. return
  1756. direction = 'cw' if sign(t) > 0 else 'ccw'
  1757. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1758. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1759. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1760. direction, self.steps_per_circ)),
  1761. Point(center), Point(p1), Point(p3)])
  1762. else: # '12c'
  1763. p1 = array(self.points[0])
  1764. p2 = array(self.points[1])
  1765. # Midpoint
  1766. a = (p1 + p2) / 2.0
  1767. # Parallel vector
  1768. c = p2 - p1
  1769. # Perpendicular vector
  1770. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1771. b /= numpy_norm(b)
  1772. # Distance
  1773. t = distance(data, a)
  1774. # Which side? Cross product with c.
  1775. # cross(M-A, B-A), where line is AB and M is test point.
  1776. side = (data[0] - p1[0]) * c[1] - (data[1] - p1[1]) * c[0]
  1777. t *= sign(side)
  1778. # Center = a + bt
  1779. center = a + b * t
  1780. radius = numpy_norm(center - p1)
  1781. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1782. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1783. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1784. self.direction, self.steps_per_circ)),
  1785. Point(center)])
  1786. return None
  1787. def make(self):
  1788. if self.mode == 'c12':
  1789. center = self.points[0]
  1790. p1 = self.points[1]
  1791. p2 = self.points[2]
  1792. radius = distance(center, p1)
  1793. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1794. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1795. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1796. self.direction, self.steps_per_circ)))
  1797. elif self.mode == '132':
  1798. p1 = array(self.points[0])
  1799. p3 = array(self.points[1])
  1800. p2 = array(self.points[2])
  1801. center, radius, t = three_point_circle(p1, p2, p3)
  1802. direction = 'cw' if sign(t) > 0 else 'ccw'
  1803. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1804. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1805. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1806. direction, self.steps_per_circ)))
  1807. else: # self.mode == '12c'
  1808. p1 = array(self.points[0])
  1809. p2 = array(self.points[1])
  1810. pc = array(self.points[2])
  1811. # Midpoint
  1812. a = (p1 + p2) / 2.0
  1813. # Parallel vector
  1814. c = p2 - p1
  1815. # Perpendicular vector
  1816. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1817. b /= numpy_norm(b)
  1818. # Distance
  1819. t = distance(pc, a)
  1820. # Which side? Cross product with c.
  1821. # cross(M-A, B-A), where line is AB and M is test point.
  1822. side = (pc[0] - p1[0]) * c[1] - (pc[1] - p1[1]) * c[0]
  1823. t *= sign(side)
  1824. # Center = a + bt
  1825. center = a + b * t
  1826. radius = numpy_norm(center - p1)
  1827. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1828. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1829. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1830. self.direction, self.steps_per_circ)))
  1831. self.complete = True
  1832. self.draw_app.app.inform.emit('[success] %s' %
  1833. _("Done. Arc completed."))
  1834. class FCRectangle(FCShapeTool):
  1835. """
  1836. Resulting type: Polygon
  1837. """
  1838. def __init__(self, draw_app):
  1839. DrawTool.__init__(self, draw_app)
  1840. self.name = 'rectangle'
  1841. try:
  1842. QtGui.QGuiApplication.restoreOverrideCursor()
  1843. except Exception as e:
  1844. pass
  1845. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero.png'))
  1846. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1847. self.draw_app.app.inform.emit( _("Click on 1st corner ..."))
  1848. def click(self, point):
  1849. self.points.append(point)
  1850. if len(self.points) == 1:
  1851. self.draw_app.app.inform.emit(_("Click on opposite corner to complete ..."))
  1852. return "Click on opposite corner to complete ..."
  1853. if len(self.points) == 2:
  1854. self.make()
  1855. return "Done."
  1856. return ""
  1857. def utility_geometry(self, data=None):
  1858. if len(self.points) == 1:
  1859. p1 = self.points[0]
  1860. p2 = data
  1861. return DrawToolUtilityShape(LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1862. return None
  1863. def make(self):
  1864. try:
  1865. QtGui.QGuiApplication.restoreOverrideCursor()
  1866. except Exception as e:
  1867. pass
  1868. p1 = self.points[0]
  1869. p2 = self.points[1]
  1870. # self.geometry = LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])])
  1871. self.geometry = DrawToolShape(Polygon([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1872. self.complete = True
  1873. self.draw_app.app.inform.emit('[success] %s' %
  1874. _("Done. Rectangle completed."))
  1875. class FCPolygon(FCShapeTool):
  1876. """
  1877. Resulting type: Polygon
  1878. """
  1879. def __init__(self, draw_app):
  1880. DrawTool.__init__(self, draw_app)
  1881. self.name = 'polygon'
  1882. try:
  1883. QtGui.QGuiApplication.restoreOverrideCursor()
  1884. except Exception as e:
  1885. pass
  1886. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero.png'))
  1887. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1888. self.draw_app.app.inform.emit(_("Click on 1st corner ..."))
  1889. def click(self, point):
  1890. self.draw_app.in_action = True
  1891. self.points.append(point)
  1892. if len(self.points) > 0:
  1893. self.draw_app.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  1894. return "Click on next point or hit ENTER to complete ..."
  1895. return ""
  1896. def utility_geometry(self, data=None):
  1897. if len(self.points) == 1:
  1898. temp_points = [x for x in self.points]
  1899. temp_points.append(data)
  1900. return DrawToolUtilityShape(LineString(temp_points))
  1901. if len(self.points) > 1:
  1902. temp_points = [x for x in self.points]
  1903. temp_points.append(data)
  1904. return DrawToolUtilityShape(LinearRing(temp_points))
  1905. return None
  1906. def make(self):
  1907. try:
  1908. QtGui.QGuiApplication.restoreOverrideCursor()
  1909. except Exception as e:
  1910. pass
  1911. # self.geometry = LinearRing(self.points)
  1912. self.geometry = DrawToolShape(Polygon(self.points))
  1913. self.draw_app.in_action = False
  1914. self.complete = True
  1915. self.draw_app.app.inform.emit('[success] %s' %
  1916. _("Done. Polygon completed."))
  1917. def on_key(self, key):
  1918. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  1919. if len(self.points) > 0:
  1920. self.points = self.points[0:-1]
  1921. # Remove any previous utility shape
  1922. self.draw_app.tool_shape.clear(update=False)
  1923. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  1924. self.draw_app.draw_utility_geometry(geo=geo)
  1925. return _("Backtracked one point ...")
  1926. class FCPath(FCPolygon):
  1927. """
  1928. Resulting type: LineString
  1929. """
  1930. def __init__(self, draw_app):
  1931. FCPolygon.__init__(self, draw_app)
  1932. try:
  1933. QtGui.QGuiApplication.restoreOverrideCursor()
  1934. except Exception as e:
  1935. pass
  1936. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_path5.png'))
  1937. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1938. def make(self):
  1939. self.geometry = DrawToolShape(LineString(self.points))
  1940. self.name = 'path'
  1941. try:
  1942. QtGui.QGuiApplication.restoreOverrideCursor()
  1943. except Exception as e:
  1944. pass
  1945. self.draw_app.in_action = False
  1946. self.complete = True
  1947. self.draw_app.app.inform.emit('[success] %s' % _("Done. Path completed."))
  1948. def utility_geometry(self, data=None):
  1949. if len(self.points) > 0:
  1950. temp_points = [x for x in self.points]
  1951. temp_points.append(data)
  1952. return DrawToolUtilityShape(LineString(temp_points))
  1953. return None
  1954. def on_key(self, key):
  1955. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  1956. if len(self.points) > 0:
  1957. self.points = self.points[0:-1]
  1958. # Remove any previous utility shape
  1959. self.draw_app.tool_shape.clear(update=False)
  1960. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  1961. self.draw_app.draw_utility_geometry(geo=geo)
  1962. return _("Backtracked one point ...")
  1963. class FCSelect(DrawTool):
  1964. def __init__(self, draw_app):
  1965. DrawTool.__init__(self, draw_app)
  1966. self.name = 'select'
  1967. try:
  1968. QtGui.QGuiApplication.restoreOverrideCursor()
  1969. except Exception as e:
  1970. pass
  1971. self.storage = self.draw_app.storage
  1972. # self.shape_buffer = self.draw_app.shape_buffer
  1973. # self.selected = self.draw_app.selected
  1974. def click_release(self, point):
  1975. # list where we store the overlapped shapes under our mouse left click position
  1976. over_shape_list = []
  1977. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  1978. for obj_shape in self.storage.get_objects():
  1979. # first method of click selection -> inconvenient
  1980. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  1981. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  1982. # over_shape_list.append(obj_shape)
  1983. # second method of click selection -> slow
  1984. # outside = obj_shape.geo.buffer(0.1)
  1985. # inside = obj_shape.geo.buffer(-0.1)
  1986. # shape_band = outside.difference(inside)
  1987. # if Point(pos).within(shape_band):
  1988. # over_shape_list.append(obj_shape)
  1989. # 3rd method of click selection -> inconvenient
  1990. try:
  1991. _, closest_shape = self.storage.nearest(point)
  1992. except StopIteration:
  1993. return ""
  1994. over_shape_list.append(closest_shape)
  1995. try:
  1996. # if there is no shape under our click then deselect all shapes
  1997. # it will not work for 3rd method of click selection
  1998. if not over_shape_list:
  1999. self.draw_app.selected = []
  2000. FlatCAMGeoEditor.draw_shape_idx = -1
  2001. else:
  2002. # if there are shapes under our click then advance through the list of them, one at the time in a
  2003. # circular way
  2004. FlatCAMGeoEditor.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  2005. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  2006. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2007. if key_modifier == QtCore.Qt.ShiftModifier:
  2008. mod_key = 'Shift'
  2009. elif key_modifier == QtCore.Qt.ControlModifier:
  2010. mod_key = 'Control'
  2011. else:
  2012. mod_key = None
  2013. if mod_key == self.draw_app.app.defaults["global_mselect_key"]:
  2014. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  2015. # in the selected list, we removed it. Therefore first click selects, second deselects.
  2016. if obj_to_add in self.draw_app.selected:
  2017. self.draw_app.selected.remove(obj_to_add)
  2018. else:
  2019. self.draw_app.selected.append(obj_to_add)
  2020. else:
  2021. self.draw_app.selected = []
  2022. self.draw_app.selected.append(obj_to_add)
  2023. except Exception as e:
  2024. log.error("[ERROR] Something went bad. %s" % str(e))
  2025. raise
  2026. return ""
  2027. class FCMove(FCShapeTool):
  2028. def __init__(self, draw_app):
  2029. FCShapeTool.__init__(self, draw_app)
  2030. self.name = 'move'
  2031. try:
  2032. QtGui.QGuiApplication.restoreOverrideCursor()
  2033. except Exception as e:
  2034. pass
  2035. self.storage = self.draw_app.storage
  2036. self.origin = None
  2037. self.destination = None
  2038. self.sel_limit = self.draw_app.app.defaults["geometry_editor_sel_limit"]
  2039. self.selection_shape = self.selection_bbox()
  2040. if len(self.draw_app.get_selected()) == 0:
  2041. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s...' %
  2042. _("MOVE: No shape selected. Select a shape to move"))
  2043. else:
  2044. self.draw_app.app.inform.emit(_(" MOVE: Click on reference point ..."))
  2045. def set_origin(self, origin):
  2046. self.draw_app.app.inform.emit(_(" Click on destination point ..."))
  2047. self.origin = origin
  2048. def click(self, point):
  2049. if len(self.draw_app.get_selected()) == 0:
  2050. # self.complete = True
  2051. # self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  2052. self.select_shapes(point)
  2053. self.draw_app.replot()
  2054. self.draw_app.app.inform.emit(_(" MOVE: Click on reference point ..."))
  2055. return
  2056. if self.origin is None:
  2057. self.set_origin(point)
  2058. self.selection_shape = self.selection_bbox()
  2059. return "Click on final location."
  2060. else:
  2061. self.destination = point
  2062. self.make()
  2063. # self.draw_app.app.worker_task.emit(({'fcn': self.make,
  2064. # 'params': []}))
  2065. return "Done."
  2066. def make(self):
  2067. with self.draw_app.app.proc_container.new("Moving Geometry ..."):
  2068. # Create new geometry
  2069. dx = self.destination[0] - self.origin[0]
  2070. dy = self.destination[1] - self.origin[1]
  2071. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2072. for geom in self.draw_app.get_selected()]
  2073. # Delete old
  2074. self.draw_app.delete_selected()
  2075. self.complete = True
  2076. self.draw_app.app.inform.emit('[success] %s' %
  2077. _("Done. Geometry(s) Move completed."))
  2078. def selection_bbox(self):
  2079. geo_list = []
  2080. for select_shape in self.draw_app.get_selected():
  2081. geometric_data = select_shape.geo
  2082. try:
  2083. for g in geometric_data:
  2084. geo_list.append(g)
  2085. except TypeError:
  2086. geo_list.append(geometric_data)
  2087. xmin, ymin, xmax, ymax = get_shapely_list_bounds(geo_list)
  2088. pt1 = (xmin, ymin)
  2089. pt2 = (xmax, ymin)
  2090. pt3 = (xmax, ymax)
  2091. pt4 = (xmin, ymax)
  2092. return Polygon([pt1, pt2, pt3, pt4])
  2093. def utility_geometry(self, data=None):
  2094. """
  2095. Temporary geometry on screen while using this tool.
  2096. :param data:
  2097. :return:
  2098. """
  2099. geo_list = []
  2100. if self.origin is None:
  2101. return None
  2102. if len(self.draw_app.get_selected()) == 0:
  2103. return None
  2104. dx = data[0] - self.origin[0]
  2105. dy = data[1] - self.origin[1]
  2106. if len(self.draw_app.get_selected()) <= self.sel_limit:
  2107. try:
  2108. for geom in self.draw_app.get_selected():
  2109. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2110. except AttributeError:
  2111. self.draw_app.select_tool('select')
  2112. self.draw_app.selected = []
  2113. return
  2114. return DrawToolUtilityShape(geo_list)
  2115. else:
  2116. try:
  2117. ss_el = affinity.translate(self.selection_shape, xoff=dx, yoff=dy)
  2118. except ValueError:
  2119. ss_el = None
  2120. return DrawToolUtilityShape(ss_el)
  2121. def select_shapes(self, pos):
  2122. # list where we store the overlapped shapes under our mouse left click position
  2123. over_shape_list = []
  2124. try:
  2125. _, closest_shape = self.storage.nearest(pos)
  2126. except StopIteration:
  2127. return ""
  2128. over_shape_list.append(closest_shape)
  2129. try:
  2130. # if there is no shape under our click then deselect all shapes
  2131. # it will not work for 3rd method of click selection
  2132. if not over_shape_list:
  2133. self.draw_app.selected = []
  2134. self.draw_app.draw_shape_idx = -1
  2135. else:
  2136. # if there are shapes under our click then advance through the list of them, one at the time in a
  2137. # circular way
  2138. self.draw_app.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  2139. try:
  2140. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  2141. except IndexError:
  2142. return
  2143. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2144. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  2145. # if CONTROL key is pressed then we add to the selected list the current shape but if it's
  2146. # already in the selected list, we removed it. Therefore first click selects, second deselects.
  2147. if key_modifier == Qt.ControlModifier:
  2148. if obj_to_add in self.draw_app.selected:
  2149. self.draw_app.selected.remove(obj_to_add)
  2150. else:
  2151. self.draw_app.selected.append(obj_to_add)
  2152. else:
  2153. self.draw_app.selected = []
  2154. self.draw_app.selected.append(obj_to_add)
  2155. else:
  2156. if key_modifier == Qt.ShiftModifier:
  2157. if obj_to_add in self.draw_app.selected:
  2158. self.draw_app.selected.remove(obj_to_add)
  2159. else:
  2160. self.draw_app.selected.append(obj_to_add)
  2161. else:
  2162. self.draw_app.selected = []
  2163. self.draw_app.selected.append(obj_to_add)
  2164. except Exception as e:
  2165. log.error("[ERROR] Something went bad. %s" % str(e))
  2166. raise
  2167. class FCCopy(FCMove):
  2168. def __init__(self, draw_app):
  2169. FCMove.__init__(self, draw_app)
  2170. self.name = 'copy'
  2171. def make(self):
  2172. # Create new geometry
  2173. dx = self.destination[0] - self.origin[0]
  2174. dy = self.destination[1] - self.origin[1]
  2175. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2176. for geom in self.draw_app.get_selected()]
  2177. self.complete = True
  2178. self.draw_app.app.inform.emit('[success] %s' %
  2179. _("Done. Geometry(s) Copy completed."))
  2180. class FCText(FCShapeTool):
  2181. def __init__(self, draw_app):
  2182. FCShapeTool.__init__(self, draw_app)
  2183. self.name = 'text'
  2184. try:
  2185. QtGui.QGuiApplication.restoreOverrideCursor()
  2186. except Exception as e:
  2187. pass
  2188. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_text.png'))
  2189. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  2190. # self.shape_buffer = self.draw_app.shape_buffer
  2191. self.draw_app = draw_app
  2192. self.app = draw_app.app
  2193. self.draw_app.app.inform.emit(_("Click on 1st corner ..."))
  2194. self.origin = (0, 0)
  2195. self.text_gui = TextInputTool(self.app)
  2196. self.text_gui.run()
  2197. def click(self, point):
  2198. # Create new geometry
  2199. dx = point[0]
  2200. dy = point[1]
  2201. if self.text_gui.text_path:
  2202. try:
  2203. self.geometry = DrawToolShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2204. except Exception as e:
  2205. log.debug("Font geometry is empty or incorrect: %s" % str(e))
  2206. self.draw_app.app.inform.emit('[ERROR] %s: %s' %
  2207. (_("Font not supported. Only Regular, Bold, Italic and BoldItalic are "
  2208. "supported. Error"), str(e)))
  2209. self.text_gui.text_path = []
  2210. self.text_gui.hide_tool()
  2211. self.draw_app.select_tool('select')
  2212. return
  2213. else:
  2214. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s' %
  2215. _("No text to add."))
  2216. return
  2217. self.text_gui.text_path = []
  2218. self.text_gui.hide_tool()
  2219. self.complete = True
  2220. self.draw_app.app.inform.emit('[success]%s' %
  2221. _(" Done. Adding Text completed."))
  2222. def utility_geometry(self, data=None):
  2223. """
  2224. Temporary geometry on screen while using this tool.
  2225. :param data: mouse position coords
  2226. :return:
  2227. """
  2228. dx = data[0] - self.origin[0]
  2229. dy = data[1] - self.origin[1]
  2230. try:
  2231. return DrawToolUtilityShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2232. except:
  2233. return
  2234. class FCBuffer(FCShapeTool):
  2235. def __init__(self, draw_app):
  2236. FCShapeTool.__init__(self, draw_app)
  2237. self.name = 'buffer'
  2238. # self.shape_buffer = self.draw_app.shape_buffer
  2239. self.draw_app = draw_app
  2240. self.app = draw_app.app
  2241. self.draw_app.app.inform.emit(_("Create buffer geometry ..."))
  2242. self.origin = (0, 0)
  2243. self.buff_tool = BufferSelectionTool(self.app, self.draw_app)
  2244. self.buff_tool.run()
  2245. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  2246. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  2247. self.draw_app.app.ui.splitter.setSizes([1, 1])
  2248. self.activate()
  2249. def on_buffer(self):
  2250. if not self.draw_app.selected:
  2251. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2252. _("Buffer cancelled. No shape selected."))
  2253. return
  2254. try:
  2255. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2256. except ValueError:
  2257. # try to convert comma to decimal point. if it's still not working error message and return
  2258. try:
  2259. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2260. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2261. except ValueError:
  2262. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2263. _("Buffer distance value is missing or wrong format. Add it and retry."))
  2264. return
  2265. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2266. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2267. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2268. ret_val = self.draw_app.buffer(buffer_distance, join_style)
  2269. self.app.ui.notebook.setTabText(2, _("Tools"))
  2270. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2271. self.disactivate()
  2272. if ret_val == 'fail':
  2273. return
  2274. self.draw_app.app.inform.emit('[success] %s' %
  2275. _("Done. Buffer Tool completed."))
  2276. def on_buffer_int(self):
  2277. if not self.draw_app.selected:
  2278. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2279. _("Buffer cancelled. No shape selected."))
  2280. return
  2281. try:
  2282. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2283. except ValueError:
  2284. # try to convert comma to decimal point. if it's still not working error message and return
  2285. try:
  2286. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2287. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2288. except ValueError:
  2289. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2290. _("Buffer distance value is missing or wrong format. Add it and retry."))
  2291. return
  2292. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2293. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2294. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2295. ret_val = self.draw_app.buffer_int(buffer_distance, join_style)
  2296. self.app.ui.notebook.setTabText(2, _("Tools"))
  2297. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2298. self.disactivate()
  2299. if ret_val == 'fail':
  2300. return
  2301. self.draw_app.app.inform.emit('[success] %s' %
  2302. _("Done. Buffer Int Tool completed."))
  2303. def on_buffer_ext(self):
  2304. if not self.draw_app.selected:
  2305. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2306. _("Buffer cancelled. No shape selected."))
  2307. return
  2308. try:
  2309. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2310. except ValueError:
  2311. # try to convert comma to decimal point. if it's still not working error message and return
  2312. try:
  2313. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2314. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2315. except ValueError:
  2316. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2317. _("Buffer distance value is missing or wrong format. Add it and retry."))
  2318. return
  2319. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2320. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2321. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2322. ret_val = self.draw_app.buffer_ext(buffer_distance, join_style)
  2323. self.app.ui.notebook.setTabText(2, _("Tools"))
  2324. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2325. self.disactivate()
  2326. if ret_val == 'fail':
  2327. return
  2328. self.draw_app.app.inform.emit('[success] %s' %
  2329. _("Done. Buffer Ext Tool completed."))
  2330. def activate(self):
  2331. self.buff_tool.buffer_button.clicked.disconnect()
  2332. self.buff_tool.buffer_int_button.clicked.disconnect()
  2333. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2334. self.buff_tool.buffer_button.clicked.connect(self.on_buffer)
  2335. self.buff_tool.buffer_int_button.clicked.connect(self.on_buffer_int)
  2336. self.buff_tool.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  2337. def disactivate(self):
  2338. self.buff_tool.buffer_button.clicked.disconnect()
  2339. self.buff_tool.buffer_int_button.clicked.disconnect()
  2340. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2341. self.buff_tool.buffer_button.clicked.connect(self.buff_tool.on_buffer)
  2342. self.buff_tool.buffer_int_button.clicked.connect(self.buff_tool.on_buffer_int)
  2343. self.buff_tool.buffer_ext_button.clicked.connect(self.buff_tool.on_buffer_ext)
  2344. self.complete = True
  2345. self.draw_app.select_tool("select")
  2346. self.buff_tool.hide_tool()
  2347. class FCEraser(FCShapeTool):
  2348. def __init__(self, draw_app):
  2349. DrawTool.__init__(self, draw_app)
  2350. self.name = 'eraser'
  2351. self.origin = None
  2352. self.destination = None
  2353. if len(self.draw_app.get_selected()) == 0:
  2354. if self.draw_app.launched_from_shortcuts is True:
  2355. self.draw_app.launched_from_shortcuts = False
  2356. self.draw_app.app.inform.emit(_("Select a shape to act as deletion area ..."))
  2357. else:
  2358. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2359. self.geometry = []
  2360. self.storage = self.draw_app.storage
  2361. # Switch notebook to Selected page
  2362. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2363. def set_origin(self, origin):
  2364. self.origin = origin
  2365. def click(self, point):
  2366. if len(self.draw_app.get_selected()) == 0:
  2367. for obj_shape in self.storage.get_objects():
  2368. try:
  2369. __, closest_shape = self.storage.nearest(point)
  2370. self.draw_app.selected.append(closest_shape)
  2371. except StopIteration:
  2372. if len(self.draw_app.selected) > 0:
  2373. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2374. return ""
  2375. if len(self.draw_app.get_selected()) == 0:
  2376. return "Nothing to ersase."
  2377. else:
  2378. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  2379. if self.origin is None:
  2380. self.set_origin(point)
  2381. self.draw_app.app.inform.emit(_("Click to erase ..."))
  2382. return
  2383. else:
  2384. self.destination = point
  2385. self.make()
  2386. # self.draw_app.select_tool("select")
  2387. return
  2388. def make(self):
  2389. eraser_sel_shapes = []
  2390. # create the eraser shape from selection
  2391. for eraser_shape in self.utility_geometry(data=self.destination).geo:
  2392. temp_shape = eraser_shape.buffer(0.0000001)
  2393. temp_shape = Polygon(temp_shape.exterior)
  2394. eraser_sel_shapes.append(temp_shape)
  2395. eraser_sel_shapes = cascaded_union(eraser_sel_shapes)
  2396. for obj_shape in self.storage.get_objects():
  2397. try:
  2398. geometric_data = obj_shape.geo
  2399. if eraser_sel_shapes.intersects(geometric_data):
  2400. obj_shape.geo = geometric_data.difference(eraser_sel_shapes)
  2401. except KeyError:
  2402. pass
  2403. self.draw_app.delete_utility_geometry()
  2404. self.draw_app.plot_all()
  2405. self.draw_app.app.inform.emit('[success] %s' %
  2406. _("Done. Eraser tool action completed."))
  2407. def utility_geometry(self, data=None):
  2408. """
  2409. Temporary geometry on screen while using this tool.
  2410. :param data:
  2411. :return:
  2412. """
  2413. geo_list = []
  2414. if self.origin is None:
  2415. return None
  2416. if len(self.draw_app.get_selected()) == 0:
  2417. return None
  2418. dx = data[0] - self.origin[0]
  2419. dy = data[1] - self.origin[1]
  2420. try:
  2421. for geom in self.draw_app.get_selected():
  2422. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2423. except AttributeError:
  2424. self.draw_app.select_tool('select')
  2425. self.draw_app.selected = []
  2426. return
  2427. return DrawToolUtilityShape(geo_list)
  2428. def clean_up(self):
  2429. self.draw_app.selected = []
  2430. self.draw_app.plot_all()
  2431. class FCPaint(FCShapeTool):
  2432. def __init__(self, draw_app):
  2433. FCShapeTool.__init__(self, draw_app)
  2434. self.name = 'paint'
  2435. # self.shape_buffer = self.draw_app.shape_buffer
  2436. self.draw_app = draw_app
  2437. self.app = draw_app.app
  2438. self.draw_app.app.inform.emit(_("Create Paint geometry ..."))
  2439. self.origin = (0, 0)
  2440. self.draw_app.paint_tool.run()
  2441. class FCTransform(FCShapeTool):
  2442. def __init__(self, draw_app):
  2443. FCShapeTool.__init__(self, draw_app)
  2444. self.name = 'transformation'
  2445. # self.shape_buffer = self.draw_app.shape_buffer
  2446. self.draw_app = draw_app
  2447. self.app = draw_app.app
  2448. self.draw_app.app.inform.emit(_("Shape transformations ..."))
  2449. self.origin = (0, 0)
  2450. self.draw_app.transform_tool.run()
  2451. # ###############################################
  2452. # ################ Main Application #############
  2453. # ###############################################
  2454. class FlatCAMGeoEditor(QtCore.QObject):
  2455. transform_complete = QtCore.pyqtSignal()
  2456. draw_shape_idx = -1
  2457. def __init__(self, app, disabled=False):
  2458. assert isinstance(app, FlatCAMApp.App), \
  2459. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  2460. super(FlatCAMGeoEditor, self).__init__()
  2461. self.app = app
  2462. self.canvas = app.plotcanvas
  2463. # ## Toolbar events and properties
  2464. self.tools = {
  2465. "select": {"button": self.app.ui.geo_select_btn,
  2466. "constructor": FCSelect},
  2467. "arc": {"button": self.app.ui.geo_add_arc_btn,
  2468. "constructor": FCArc},
  2469. "circle": {"button": self.app.ui.geo_add_circle_btn,
  2470. "constructor": FCCircle},
  2471. "path": {"button": self.app.ui.geo_add_path_btn,
  2472. "constructor": FCPath},
  2473. "rectangle": {"button": self.app.ui.geo_add_rectangle_btn,
  2474. "constructor": FCRectangle},
  2475. "polygon": {"button": self.app.ui.geo_add_polygon_btn,
  2476. "constructor": FCPolygon},
  2477. "text": {"button": self.app.ui.geo_add_text_btn,
  2478. "constructor": FCText},
  2479. "buffer": {"button": self.app.ui.geo_add_buffer_btn,
  2480. "constructor": FCBuffer},
  2481. "paint": {"button": self.app.ui.geo_add_paint_btn,
  2482. "constructor": FCPaint},
  2483. "eraser": {"button": self.app.ui.geo_eraser_btn,
  2484. "constructor": FCEraser},
  2485. "move": {"button": self.app.ui.geo_move_btn,
  2486. "constructor": FCMove},
  2487. "transform": {"button": self.app.ui.geo_transform_btn,
  2488. "constructor": FCTransform},
  2489. "copy": {"button": self.app.ui.geo_copy_btn,
  2490. "constructor": FCCopy}
  2491. }
  2492. # # ## Data
  2493. self.active_tool = None
  2494. self.storage = FlatCAMGeoEditor.make_storage()
  2495. self.utility = []
  2496. # VisPy visuals
  2497. self.fcgeometry = None
  2498. if self.app.is_legacy is False:
  2499. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  2500. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  2501. else:
  2502. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2503. self.shapes = ShapeCollectionLegacy()
  2504. self.tool_shape = ShapeCollectionLegacy()
  2505. self.app.pool_recreated.connect(self.pool_recreated)
  2506. # Remove from scene
  2507. self.shapes.enabled = False
  2508. self.tool_shape.enabled = False
  2509. # List of selected shapes.
  2510. self.selected = []
  2511. self.flat_geo = []
  2512. self.move_timer = QtCore.QTimer()
  2513. self.move_timer.setSingleShot(True)
  2514. # this var will store the state of the toolbar before starting the editor
  2515. self.toolbar_old_state = False
  2516. self.key = None # Currently pressed key
  2517. self.geo_key_modifiers = None
  2518. self.x = None # Current mouse cursor pos
  2519. self.y = None
  2520. # if we edit a multigeo geometry store here the tool number
  2521. self.multigeo_tool = None
  2522. # Current snapped mouse pos
  2523. self.snap_x = None
  2524. self.snap_y = None
  2525. self.pos = None
  2526. # signal that there is an action active like polygon or path
  2527. self.in_action = False
  2528. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  2529. self.launched_from_shortcuts = False
  2530. def make_callback(thetool):
  2531. def f():
  2532. self.on_tool_select(thetool)
  2533. return f
  2534. for tool in self.tools:
  2535. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  2536. self.tools[tool]["button"].setCheckable(True) # Checkable
  2537. self.app.ui.grid_snap_btn.triggered.connect(self.on_grid_toggled)
  2538. self.app.ui.corner_snap_btn.setCheckable(True)
  2539. self.app.ui.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  2540. self.options = {
  2541. "global_gridx": 0.1,
  2542. "global_gridy": 0.1,
  2543. "global_snap_max": 0.05,
  2544. "grid_snap": True,
  2545. "corner_snap": False,
  2546. "grid_gap_link": True
  2547. }
  2548. self.app.options_read_form()
  2549. for option in self.options:
  2550. if option in self.app.options:
  2551. self.options[option] = self.app.options[option]
  2552. self.app.ui.grid_gap_x_entry.setText(str(self.options["global_gridx"]))
  2553. self.app.ui.grid_gap_y_entry.setText(str(self.options["global_gridy"]))
  2554. self.app.ui.snap_max_dist_entry.setText(str(self.options["global_snap_max"]))
  2555. self.app.ui.grid_gap_link_cb.setChecked(True)
  2556. self.rtree_index = rtindex.Index()
  2557. def entry2option(option, entry):
  2558. try:
  2559. self.options[option] = float(entry.text())
  2560. except Exception as e:
  2561. log.debug("FlatCAMGeoEditor.__init__().entry2option() --> %s" % str(e))
  2562. return
  2563. def gridx_changed(goption, gentry):
  2564. entry2option(option=goption, entry=gentry)
  2565. # if the grid link is checked copy the value in the GridX field to GridY
  2566. try:
  2567. val = float(self.app.ui.grid_gap_x_entry.get_value())
  2568. except ValueError:
  2569. return
  2570. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  2571. dec = 6 if units == 'IN' else 4
  2572. if self.app.ui.grid_gap_link_cb.isChecked():
  2573. self.app.ui.grid_gap_y_entry.set_value(val, decimals=dec)
  2574. self.app.ui.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  2575. self.app.ui.grid_gap_x_entry.textChanged.connect(
  2576. lambda: gridx_changed("global_gridx", self.app.ui.grid_gap_x_entry))
  2577. self.app.ui.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  2578. self.app.ui.grid_gap_y_entry.textChanged.connect(
  2579. lambda: entry2option("global_gridy", self.app.ui.grid_gap_y_entry))
  2580. self.app.ui.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  2581. self.app.ui.snap_max_dist_entry.textChanged.connect(
  2582. lambda: entry2option("snap_max", self.app.ui.snap_max_dist_entry))
  2583. # if using Paint store here the tool diameter used
  2584. self.paint_tooldia = None
  2585. self.paint_tool = PaintOptionsTool(self.app, self)
  2586. self.transform_tool = TransformEditorTool(self.app, self)
  2587. self.app.ui.geo_add_circle_menuitem.triggered.connect(lambda: self.select_tool('circle'))
  2588. self.app.ui.geo_add_arc_menuitem.triggered.connect(lambda: self.select_tool('arc'))
  2589. self.app.ui.geo_add_rectangle_menuitem.triggered.connect(lambda: self.select_tool('rectangle'))
  2590. self.app.ui.geo_add_polygon_menuitem.triggered.connect(lambda: self.select_tool('polygon'))
  2591. self.app.ui.geo_add_path_menuitem.triggered.connect(lambda: self.select_tool('path'))
  2592. self.app.ui.geo_add_text_menuitem.triggered.connect(lambda: self.select_tool('text'))
  2593. self.app.ui.geo_paint_menuitem.triggered.connect(self.on_paint_tool)
  2594. self.app.ui.geo_buffer_menuitem.triggered.connect(self.on_buffer_tool)
  2595. self.app.ui.geo_transform_menuitem.triggered.connect(self.transform_tool.run)
  2596. self.app.ui.geo_delete_menuitem.triggered.connect(self.on_delete_btn)
  2597. self.app.ui.geo_union_menuitem.triggered.connect(self.union)
  2598. self.app.ui.geo_intersection_menuitem.triggered.connect(self.intersection)
  2599. self.app.ui.geo_subtract_menuitem.triggered.connect(self.subtract)
  2600. self.app.ui.geo_cutpath_menuitem.triggered.connect(self.cutpath)
  2601. self.app.ui.geo_copy_menuitem.triggered.connect(lambda: self.select_tool('copy'))
  2602. self.app.ui.geo_union_btn.triggered.connect(self.union)
  2603. self.app.ui.geo_intersection_btn.triggered.connect(self.intersection)
  2604. self.app.ui.geo_subtract_btn.triggered.connect(self.subtract)
  2605. self.app.ui.geo_cutpath_btn.triggered.connect(self.cutpath)
  2606. self.app.ui.geo_delete_btn.triggered.connect(self.on_delete_btn)
  2607. self.app.ui.geo_move_menuitem.triggered.connect(self.on_move)
  2608. self.app.ui.geo_cornersnap_menuitem.triggered.connect(self.on_corner_snap)
  2609. self.transform_complete.connect(self.on_transform_complete)
  2610. # store the status of the editor so the Delete at object level will not work until the edit is finished
  2611. self.editor_active = False
  2612. log.debug("Initialization of the FlatCAM Geometry Editor is finished ...")
  2613. def pool_recreated(self, pool):
  2614. self.shapes.pool = pool
  2615. self.tool_shape.pool = pool
  2616. def on_transform_complete(self):
  2617. self.delete_selected()
  2618. self.replot()
  2619. def activate(self):
  2620. # adjust the status of the menu entries related to the editor
  2621. self.app.ui.menueditedit.setDisabled(True)
  2622. self.app.ui.menueditok.setDisabled(False)
  2623. # adjust the visibility of some of the canvas context menu
  2624. self.app.ui.popmenu_edit.setVisible(False)
  2625. self.app.ui.popmenu_save.setVisible(True)
  2626. self.connect_canvas_event_handlers()
  2627. # initialize working objects
  2628. self.storage = FlatCAMGeoEditor.make_storage()
  2629. self.utility = []
  2630. self.selected = []
  2631. self.shapes.enabled = True
  2632. self.tool_shape.enabled = True
  2633. self.app.app_cursor.enabled = True
  2634. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2635. self.app.ui.corner_snap_btn.setEnabled(True)
  2636. self.app.ui.snap_magnet.setVisible(True)
  2637. self.app.ui.corner_snap_btn.setVisible(True)
  2638. self.app.ui.geo_editor_menu.setDisabled(False)
  2639. self.app.ui.geo_editor_menu.menuAction().setVisible(True)
  2640. self.app.ui.update_obj_btn.setEnabled(True)
  2641. self.app.ui.g_editor_cmenu.setEnabled(True)
  2642. self.app.ui.geo_edit_toolbar.setDisabled(False)
  2643. self.app.ui.geo_edit_toolbar.setVisible(True)
  2644. self.app.ui.snap_toolbar.setDisabled(False)
  2645. self.app.ui.popmenu_disable.setVisible(False)
  2646. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  2647. self.app.ui.popmenu_properties.setVisible(False)
  2648. self.app.ui.g_editor_cmenu.menuAction().setVisible(True)
  2649. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  2650. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2651. for w in sel_tab_widget_list:
  2652. w.setEnabled(False)
  2653. # Tell the App that the editor is active
  2654. self.editor_active = True
  2655. log.debug("Finished activating the Geometry Editor...")
  2656. def deactivate(self):
  2657. try:
  2658. QtGui.QGuiApplication.restoreOverrideCursor()
  2659. except Exception as e:
  2660. pass
  2661. # adjust the status of the menu entries related to the editor
  2662. self.app.ui.menueditedit.setDisabled(False)
  2663. self.app.ui.menueditok.setDisabled(True)
  2664. # adjust the visibility of some of the canvas context menu
  2665. self.app.ui.popmenu_edit.setVisible(True)
  2666. self.app.ui.popmenu_save.setVisible(False)
  2667. self.disconnect_canvas_event_handlers()
  2668. self.clear()
  2669. self.app.ui.geo_edit_toolbar.setDisabled(True)
  2670. settings = QSettings("Open Source", "FlatCAM")
  2671. if settings.contains("layout"):
  2672. layout = settings.value('layout', type=str)
  2673. if layout == 'standard':
  2674. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2675. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2676. self.app.ui.corner_snap_btn.setEnabled(False)
  2677. self.app.ui.snap_magnet.setVisible(False)
  2678. self.app.ui.corner_snap_btn.setVisible(False)
  2679. elif layout == 'compact':
  2680. # self.app.ui.geo_edit_toolbar.setVisible(True)
  2681. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2682. self.app.ui.corner_snap_btn.setEnabled(False)
  2683. else:
  2684. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2685. self.app.ui.snap_magnet.setVisible(False)
  2686. self.app.ui.corner_snap_btn.setVisible(False)
  2687. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2688. self.app.ui.corner_snap_btn.setEnabled(False)
  2689. # set the Editor Toolbar visibility to what was before entering in the Editor
  2690. self.app.ui.geo_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2691. else self.app.ui.geo_edit_toolbar.setVisible(True)
  2692. # Disable visuals
  2693. self.shapes.enabled = False
  2694. self.tool_shape.enabled = False
  2695. self.app.ui.geo_editor_menu.setDisabled(True)
  2696. self.app.ui.geo_editor_menu.menuAction().setVisible(False)
  2697. self.app.ui.update_obj_btn.setEnabled(False)
  2698. self.app.ui.g_editor_cmenu.setEnabled(False)
  2699. self.app.ui.e_editor_cmenu.setEnabled(False)
  2700. # Tell the app that the editor is no longer active
  2701. self.editor_active = False
  2702. self.app.ui.popmenu_disable.setVisible(True)
  2703. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  2704. self.app.ui.popmenu_properties.setVisible(True)
  2705. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2706. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  2707. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2708. try:
  2709. # re-enable all the widgets in the Selected Tab that were disabled after entering in Edit Geometry Mode
  2710. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2711. for w in sel_tab_widget_list:
  2712. w.setEnabled(True)
  2713. except Exception as e:
  2714. log.debug("FlatCAMGeoEditor.deactivate() --> %s" % str(e))
  2715. # Show original geometry
  2716. if self.fcgeometry:
  2717. self.fcgeometry.visible = True
  2718. log.debug("Finished deactivating the Geometry Editor...")
  2719. def connect_canvas_event_handlers(self):
  2720. # Canvas events
  2721. # first connect to new, then disconnect the old handlers
  2722. # don't ask why but if there is nothing connected I've seen issues
  2723. self.mp = self.canvas.graph_event_connect('mouse_press', self.on_canvas_click)
  2724. self.mm = self.canvas.graph_event_connect('mouse_move', self.on_canvas_move)
  2725. self.mr = self.canvas.graph_event_connect('mouse_release', self.on_geo_click_release)
  2726. if self.app.is_legacy is False:
  2727. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2728. # but those from FlatCAMGeoEditor
  2729. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2730. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2731. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2732. self.app.plotcanvas.graph_event_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2733. else:
  2734. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  2735. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  2736. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  2737. self.app.plotcanvas.graph_event_disconnect(self.app.mdc)
  2738. # self.app.collection.view.clicked.disconnect()
  2739. self.app.ui.popmenu_copy.triggered.disconnect()
  2740. self.app.ui.popmenu_delete.triggered.disconnect()
  2741. self.app.ui.popmenu_move.triggered.disconnect()
  2742. self.app.ui.popmenu_copy.triggered.connect(lambda: self.select_tool('copy'))
  2743. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  2744. self.app.ui.popmenu_move.triggered.connect(lambda: self.select_tool('move'))
  2745. # Geometry Editor
  2746. self.app.ui.draw_line.triggered.connect(self.draw_tool_path)
  2747. self.app.ui.draw_rect.triggered.connect(self.draw_tool_rectangle)
  2748. self.app.ui.draw_circle.triggered.connect(lambda: self.select_tool('circle'))
  2749. self.app.ui.draw_poly.triggered.connect(lambda: self.select_tool('polygon'))
  2750. self.app.ui.draw_arc.triggered.connect(lambda: self.select_tool('arc'))
  2751. self.app.ui.draw_text.triggered.connect(lambda: self.select_tool('text'))
  2752. self.app.ui.draw_buffer.triggered.connect(lambda: self.select_tool('buffer'))
  2753. self.app.ui.draw_paint.triggered.connect(lambda: self.select_tool('paint'))
  2754. self.app.ui.draw_eraser.triggered.connect(lambda: self.select_tool('eraser'))
  2755. self.app.ui.draw_union.triggered.connect(self.union)
  2756. self.app.ui.draw_intersect.triggered.connect(self.intersection)
  2757. self.app.ui.draw_substract.triggered.connect(self.subtract)
  2758. self.app.ui.draw_cut.triggered.connect(self.cutpath)
  2759. self.app.ui.draw_transform.triggered.connect(lambda: self.select_tool('transform'))
  2760. self.app.ui.draw_move.triggered.connect(self.on_move)
  2761. def disconnect_canvas_event_handlers(self):
  2762. # we restore the key and mouse control to FlatCAMApp method
  2763. # first connect to new, then disconnect the old handlers
  2764. # don't ask why but if there is nothing connected I've seen issues
  2765. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2766. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2767. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  2768. self.app.on_mouse_click_release_over_plot)
  2769. self.app.mdc = self.app.plotcanvas.graph_event_connect('mouse_double_click',
  2770. self.app.on_double_click_over_plot)
  2771. # self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2772. if self.app.is_legacy is False:
  2773. self.canvas.graph_event_disconnect('mouse_press', self.on_canvas_click)
  2774. self.canvas.graph_event_disconnect('mouse_move', self.on_canvas_move)
  2775. self.canvas.graph_event_disconnect('mouse_release', self.on_geo_click_release)
  2776. else:
  2777. self.canvas.graph_event_disconnect(self.mp)
  2778. self.canvas.graph_event_disconnect(self.mm)
  2779. self.canvas.graph_event_disconnect(self.mr)
  2780. try:
  2781. self.app.ui.popmenu_copy.triggered.disconnect(lambda: self.select_tool('copy'))
  2782. except (TypeError, AttributeError):
  2783. pass
  2784. try:
  2785. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  2786. except (TypeError, AttributeError):
  2787. pass
  2788. try:
  2789. self.app.ui.popmenu_move.triggered.disconnect(lambda: self.select_tool('move'))
  2790. except (TypeError, AttributeError):
  2791. pass
  2792. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_object)
  2793. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  2794. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  2795. # Geometry Editor
  2796. try:
  2797. self.app.ui.draw_line.triggered.disconnect(self.draw_tool_path)
  2798. except (TypeError, AttributeError):
  2799. pass
  2800. try:
  2801. self.app.ui.draw_rect.triggered.disconnect(self.draw_tool_rectangle)
  2802. except (TypeError, AttributeError):
  2803. pass
  2804. try:
  2805. self.app.ui.draw_cut.triggered.disconnect(self.cutpath)
  2806. except (TypeError, AttributeError):
  2807. pass
  2808. try:
  2809. self.app.ui.draw_move.triggered.disconnect(self.on_move)
  2810. except (TypeError, AttributeError):
  2811. pass
  2812. try:
  2813. self.app.ui.draw_circle.triggered.disconnect()
  2814. except (TypeError, AttributeError):
  2815. pass
  2816. try:
  2817. self.app.ui.draw_poly.triggered.disconnect()
  2818. except (TypeError, AttributeError):
  2819. pass
  2820. try:
  2821. self.app.ui.draw_arc.triggered.disconnect()
  2822. except (TypeError, AttributeError):
  2823. pass
  2824. try:
  2825. self.app.ui.draw_text.triggered.disconnect()
  2826. except (TypeError, AttributeError):
  2827. pass
  2828. try:
  2829. self.app.ui.draw_buffer.triggered.disconnect()
  2830. except (TypeError, AttributeError):
  2831. pass
  2832. try:
  2833. self.app.ui.draw_paint.triggered.disconnect()
  2834. except (TypeError, AttributeError):
  2835. pass
  2836. try:
  2837. self.app.ui.draw_eraser.triggered.disconnect()
  2838. except (TypeError, AttributeError):
  2839. pass
  2840. try:
  2841. self.app.ui.draw_union.triggered.disconnect(self.union)
  2842. except (TypeError, AttributeError):
  2843. pass
  2844. try:
  2845. self.app.ui.draw_intersect.triggered.disconnect(self.intersection)
  2846. except (TypeError, AttributeError):
  2847. pass
  2848. try:
  2849. self.app.ui.draw_substract.triggered.disconnect(self.subtract)
  2850. except (TypeError, AttributeError):
  2851. pass
  2852. try:
  2853. self.app.ui.draw_transform.triggered.disconnect()
  2854. except (TypeError, AttributeError):
  2855. pass
  2856. def add_shape(self, shape):
  2857. """
  2858. Adds a shape to the shape storage.
  2859. :param shape: Shape to be added.
  2860. :type shape: DrawToolShape
  2861. :return: None
  2862. """
  2863. if shape is None:
  2864. return
  2865. # List of DrawToolShape?
  2866. if isinstance(shape, list):
  2867. for subshape in shape:
  2868. self.add_shape(subshape)
  2869. return
  2870. assert isinstance(shape, DrawToolShape), \
  2871. "Expected a DrawToolShape, got %s" % type(shape)
  2872. assert shape.geo is not None, \
  2873. "Shape object has empty geometry (None)"
  2874. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  2875. not isinstance(shape.geo, list), "Shape objects has empty geometry ([])"
  2876. if isinstance(shape, DrawToolUtilityShape):
  2877. self.utility.append(shape)
  2878. else:
  2879. self.storage.insert(shape) # TODO: Check performance
  2880. def delete_utility_geometry(self):
  2881. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2882. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2883. for_deletion = [shape for shape in self.utility]
  2884. for shape in for_deletion:
  2885. self.delete_shape(shape)
  2886. self.tool_shape.clear(update=True)
  2887. self.tool_shape.redraw()
  2888. def toolbar_tool_toggle(self, key):
  2889. self.options[key] = self.sender().isChecked()
  2890. return 1 if self.options[key] == True else 0
  2891. def clear(self):
  2892. self.active_tool = None
  2893. # self.shape_buffer = []
  2894. self.selected = []
  2895. self.shapes.clear(update=True)
  2896. self.tool_shape.clear(update=True)
  2897. # self.storage = FlatCAMGeoEditor.make_storage()
  2898. self.replot()
  2899. def edit_fcgeometry(self, fcgeometry, multigeo_tool=None):
  2900. """
  2901. Imports the geometry from the given FlatCAM Geometry object
  2902. into the editor.
  2903. :param fcgeometry: FlatCAMGeometry
  2904. :param multigeo_tool: a tool for the case of multigeo
  2905. :return: None
  2906. """
  2907. assert isinstance(fcgeometry, Geometry), \
  2908. "Expected a Geometry, got %s" % type(fcgeometry)
  2909. self.deactivate()
  2910. self.activate()
  2911. # Hide original geometry
  2912. self.fcgeometry = fcgeometry
  2913. fcgeometry.visible = False
  2914. # Set selection tolerance
  2915. DrawToolShape.tolerance = fcgeometry.drawing_tolerance * 10
  2916. self.select_tool("select")
  2917. # Link shapes into editor.
  2918. if multigeo_tool:
  2919. self.multigeo_tool = multigeo_tool
  2920. geo_to_edit = fcgeometry.flatten(geometry=fcgeometry.tools[self.multigeo_tool]['solid_geometry'])
  2921. self.app.inform.emit('[WARNING_NOTCL] %s: %s %s: %s' %
  2922. (_("Editing MultiGeo Geometry, tool"),
  2923. str(self.multigeo_tool),
  2924. _("with diameter"),
  2925. str(fcgeometry.tools[self.multigeo_tool]['tooldia'])
  2926. )
  2927. )
  2928. else:
  2929. geo_to_edit = fcgeometry.flatten()
  2930. for shape in geo_to_edit:
  2931. if shape is not None: # TODO: Make flatten never create a None
  2932. if type(shape) == Polygon:
  2933. self.add_shape(DrawToolShape(shape.exterior))
  2934. for inter in shape.interiors:
  2935. self.add_shape(DrawToolShape(inter))
  2936. else:
  2937. self.add_shape(DrawToolShape(shape))
  2938. self.replot()
  2939. # start with GRID toolbar activated
  2940. if self.app.ui.grid_snap_btn.isChecked() is False:
  2941. self.app.ui.grid_snap_btn.trigger()
  2942. def on_buffer_tool(self):
  2943. buff_tool = BufferSelectionTool(self.app, self)
  2944. buff_tool.run()
  2945. def on_paint_tool(self):
  2946. paint_tool = PaintOptionsTool(self.app, self)
  2947. paint_tool.run()
  2948. def on_tool_select(self, tool):
  2949. """
  2950. Behavior of the toolbar. Tool initialization.
  2951. :rtype : None
  2952. """
  2953. self.app.log.debug("on_tool_select('%s')" % tool)
  2954. # This is to make the group behave as radio group
  2955. if tool in self.tools:
  2956. if self.tools[tool]["button"].isChecked():
  2957. self.app.log.debug("%s is checked." % tool)
  2958. for t in self.tools:
  2959. if t != tool:
  2960. self.tools[t]["button"].setChecked(False)
  2961. self.active_tool = self.tools[tool]["constructor"](self)
  2962. else:
  2963. self.app.log.debug("%s is NOT checked." % tool)
  2964. for t in self.tools:
  2965. self.tools[t]["button"].setChecked(False)
  2966. self.select_tool('select')
  2967. self.active_tool = FCSelect(self)
  2968. def draw_tool_path(self):
  2969. self.select_tool('path')
  2970. return
  2971. def draw_tool_rectangle(self):
  2972. self.select_tool('rectangle')
  2973. return
  2974. def on_grid_toggled(self):
  2975. self.toolbar_tool_toggle("grid_snap")
  2976. # make sure that the cursor shape is enabled/disabled, too
  2977. if self.options['grid_snap'] is True:
  2978. self.app.app_cursor.enabled = True
  2979. else:
  2980. self.app.app_cursor.enabled = False
  2981. def on_canvas_click(self, event):
  2982. """
  2983. event.x and .y have canvas coordinates
  2984. event.xdaya and .ydata have plot coordinates
  2985. :param event: Event object dispatched by Matplotlib
  2986. :return: None
  2987. """
  2988. if self.app.is_legacy is False:
  2989. event_pos = event.pos
  2990. else:
  2991. event_pos = (event.xdata, event.ydata)
  2992. self.pos = self.canvas.translate_coords(event_pos)
  2993. if self.app.grid_status() == True:
  2994. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  2995. # Update cursor
  2996. self.app.app_cursor.set_data(np.asarray([(self.pos[0], self.pos[1])]), symbol='++', edge_color='black',
  2997. size=20)
  2998. else:
  2999. self.pos = (self.pos[0], self.pos[1])
  3000. if event.button == 1:
  3001. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3002. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  3003. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3004. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3005. if modifiers == QtCore.Qt.ShiftModifier:
  3006. self.app.clipboard.setText(
  3007. self.app.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3008. return
  3009. # Selection with left mouse button
  3010. if self.active_tool is not None and event.button is 1:
  3011. # Dispatch event to active_tool
  3012. self.active_tool.click(self.snap(self.pos[0], self.pos[1]))
  3013. # If it is a shape generating tool
  3014. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  3015. self.on_shape_complete()
  3016. if isinstance(self.active_tool, FCText):
  3017. self.select_tool("select")
  3018. else:
  3019. self.select_tool(self.active_tool.name)
  3020. if isinstance(self.active_tool, FCSelect):
  3021. # self.app.log.debug("Replotting after click.")
  3022. self.replot()
  3023. else:
  3024. self.app.log.debug("No active tool to respond to click!")
  3025. def on_canvas_move(self, event):
  3026. """
  3027. Called on 'mouse_move' event
  3028. event.pos have canvas screen coordinates
  3029. :param event: Event object dispatched by VisPy SceneCavas
  3030. :return: None
  3031. """
  3032. if self.app.is_legacy is False:
  3033. event_pos = event.pos
  3034. event_is_dragging = event.is_dragging
  3035. else:
  3036. event_pos = (event.xdata, event.ydata)
  3037. event_is_dragging = self.app.plotcanvas.is_dragging
  3038. pos = self.canvas.translate_coords(event_pos)
  3039. event.xdata, event.ydata = pos[0], pos[1]
  3040. self.x = event.xdata
  3041. self.y = event.ydata
  3042. self.app.ui.popMenu.mouse_is_panning = False
  3043. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3044. if event.button == 2:
  3045. if event_is_dragging:
  3046. self.app.ui.popMenu.mouse_is_panning = True
  3047. # return
  3048. else:
  3049. self.app.ui.popMenu.mouse_is_panning = False
  3050. if self.active_tool is None:
  3051. return
  3052. try:
  3053. x = float(event.xdata)
  3054. y = float(event.ydata)
  3055. except TypeError:
  3056. return
  3057. # ### Snap coordinates ###
  3058. if self.app.grid_status() == True:
  3059. x, y = self.snap(x, y)
  3060. if self.app.is_legacy is False:
  3061. # Update cursor
  3062. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  3063. self.snap_x = x
  3064. self.snap_y = y
  3065. # update the position label in the infobar since the APP mouse event handlers are disconnected
  3066. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3067. "<b>Y</b>: %.4f" % (x, y))
  3068. if self.pos is None:
  3069. self.pos = (0, 0)
  3070. dx = x - self.pos[0]
  3071. dy = y - self.pos[1]
  3072. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  3073. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3074. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3075. if event.button == 1 and event_is_dragging and isinstance(self.active_tool, FCEraser):
  3076. pass
  3077. else:
  3078. # ### Utility geometry (animated) ###
  3079. geo = self.active_tool.utility_geometry(data=(x, y))
  3080. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  3081. # Remove any previous utility shape
  3082. self.tool_shape.clear(update=True)
  3083. self.draw_utility_geometry(geo=geo)
  3084. # ### Selection area on canvas section ###
  3085. dx = pos[0] - self.pos[0]
  3086. if event_is_dragging and event.button == 1:
  3087. self.app.delete_selection_shape()
  3088. if dx < 0:
  3089. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
  3090. color=self.app.defaults["global_alt_sel_line"],
  3091. face_color=self.app.defaults['global_alt_sel_fill'])
  3092. self.app.selection_type = False
  3093. else:
  3094. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
  3095. self.app.selection_type = True
  3096. else:
  3097. self.app.selection_type = None
  3098. def on_geo_click_release(self, event):
  3099. if self.app.is_legacy is False:
  3100. event_pos = event.pos
  3101. event_is_dragging = event.is_dragging
  3102. else:
  3103. event_pos = (event.xdata, event.ydata)
  3104. event_is_dragging = self.app.plotcanvas.is_dragging
  3105. pos_canvas = self.canvas.translate_coords(event_pos)
  3106. if self.app.grid_status() == True:
  3107. pos = self.snap(pos_canvas[0], pos_canvas[1])
  3108. else:
  3109. pos = (pos_canvas[0], pos_canvas[1])
  3110. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3111. # canvas menu
  3112. try:
  3113. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3114. # selection and then select a type of selection ("enclosing" or "touching")
  3115. if event.button == 1: # left click
  3116. if self.app.selection_type is not None:
  3117. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  3118. self.app.selection_type = None
  3119. elif isinstance(self.active_tool, FCSelect):
  3120. # Dispatch event to active_tool
  3121. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  3122. self.active_tool.click_release((self.pos[0], self.pos[1]))
  3123. # self.app.inform.emit(msg)
  3124. self.replot()
  3125. elif event.button == 2: # right click
  3126. if self.app.ui.popMenu.mouse_is_panning == False:
  3127. if self.in_action is False:
  3128. try:
  3129. QtGui.QGuiApplication.restoreOverrideCursor()
  3130. except Exception as e:
  3131. pass
  3132. if self.active_tool.complete is False and not isinstance(self.active_tool, FCSelect):
  3133. self.active_tool.complete = True
  3134. self.in_action = False
  3135. self.delete_utility_geometry()
  3136. self.app.inform.emit('[success] %s' %
  3137. _("Done."))
  3138. self.select_tool('select')
  3139. else:
  3140. self.app.cursor = QtGui.QCursor()
  3141. self.app.populate_cmenu_grids()
  3142. self.app.ui.popMenu.popup(self.app.cursor.pos())
  3143. else:
  3144. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  3145. # right mouse click will finish the action
  3146. if isinstance(self.active_tool, FCShapeTool):
  3147. self.active_tool.click(self.snap(self.x, self.y))
  3148. self.active_tool.make()
  3149. if self.active_tool.complete:
  3150. self.on_shape_complete()
  3151. self.app.inform.emit('[success] %s' %
  3152. _("Done."))
  3153. self.select_tool(self.active_tool.name)
  3154. except Exception as e:
  3155. log.warning("Error: %s" % str(e))
  3156. return
  3157. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  3158. """
  3159. :param start_pos: mouse position when the selection LMB click was done
  3160. :param end_pos: mouse position when the left mouse button is released
  3161. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3162. :return:
  3163. """
  3164. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3165. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3166. if key_modifier == QtCore.Qt.ShiftModifier:
  3167. mod_key = 'Shift'
  3168. elif key_modifier == QtCore.Qt.ControlModifier:
  3169. mod_key = 'Control'
  3170. else:
  3171. mod_key = None
  3172. self.app.delete_selection_shape()
  3173. sel_objects_list = []
  3174. for obj in self.storage.get_objects():
  3175. if (sel_type is True and poly_selection.contains(obj.geo)) or (sel_type is False and
  3176. poly_selection.intersects(obj.geo)):
  3177. sel_objects_list.append(obj)
  3178. if mod_key == self.app.defaults["global_mselect_key"]:
  3179. for obj in sel_objects_list:
  3180. if obj in self.selected:
  3181. self.selected.remove(obj)
  3182. else:
  3183. # add the object to the selected shapes
  3184. self.selected.append(obj)
  3185. else:
  3186. self.selected = []
  3187. self.selected = sel_objects_list
  3188. self.replot()
  3189. def draw_utility_geometry(self, geo):
  3190. # Add the new utility shape
  3191. try:
  3192. # this case is for the Font Parse
  3193. for el in list(geo.geo):
  3194. if type(el) == MultiPolygon:
  3195. for poly in el:
  3196. self.tool_shape.add(
  3197. shape=poly,
  3198. color=(self.app.defaults["global_draw_color"] + '80'),
  3199. update=False,
  3200. layer=0,
  3201. tolerance=None
  3202. )
  3203. elif type(el) == MultiLineString:
  3204. for linestring in el:
  3205. self.tool_shape.add(
  3206. shape=linestring,
  3207. color=(self.app.defaults["global_draw_color"] + '80'),
  3208. update=False,
  3209. layer=0,
  3210. tolerance=None
  3211. )
  3212. else:
  3213. self.tool_shape.add(
  3214. shape=el,
  3215. color=(self.app.defaults["global_draw_color"] + '80'),
  3216. update=False,
  3217. layer=0,
  3218. tolerance=None
  3219. )
  3220. except TypeError:
  3221. self.tool_shape.add(
  3222. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  3223. update=False, layer=0, tolerance=None)
  3224. self.tool_shape.redraw()
  3225. def on_delete_btn(self):
  3226. self.delete_selected()
  3227. self.replot()
  3228. def delete_selected(self):
  3229. tempref = [s for s in self.selected]
  3230. for shape in tempref:
  3231. self.delete_shape(shape)
  3232. self.selected = []
  3233. def delete_shape(self, shape):
  3234. if shape in self.utility:
  3235. self.utility.remove(shape)
  3236. return
  3237. self.storage.remove(shape)
  3238. if shape in self.selected:
  3239. self.selected.remove(shape) # TODO: Check performance
  3240. def on_move(self):
  3241. # if not self.selected:
  3242. # self.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  3243. # return
  3244. self.app.ui.geo_move_btn.setChecked(True)
  3245. self.on_tool_select('move')
  3246. def on_move_click(self):
  3247. self.on_move()
  3248. self.active_tool.set_origin(self.snap(self.x, self.y))
  3249. def on_copy_click(self):
  3250. if not self.selected:
  3251. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3252. _("Copy cancelled. No shape selected."))
  3253. return
  3254. self.app.ui.geo_copy_btn.setChecked(True)
  3255. self.app.geo_editor.on_tool_select('copy')
  3256. self.app.geo_editor.active_tool.set_origin(self.app.geo_editor.snap(
  3257. self.app.geo_editor.x, self.app.geo_editor.y))
  3258. self.app.inform.emit(_("Click on target point."))
  3259. def on_corner_snap(self):
  3260. self.app.ui.corner_snap_btn.trigger()
  3261. def get_selected(self):
  3262. """
  3263. Returns list of shapes that are selected in the editor.
  3264. :return: List of shapes.
  3265. """
  3266. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3267. return self.selected
  3268. def plot_shape(self, geometry=None, color='black', linewidth=1):
  3269. """
  3270. Plots a geometric object or list of objects without rendering. Plotted objects
  3271. are returned as a list. This allows for efficient/animated rendering.
  3272. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3273. :param color: Shape color
  3274. :param linewidth: Width of lines in # of pixels.
  3275. :return: List of plotted elements.
  3276. """
  3277. plot_elements = []
  3278. if geometry is None:
  3279. geometry = self.active_tool.geometry
  3280. try:
  3281. for geo in geometry:
  3282. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  3283. # Non-iterable
  3284. except TypeError:
  3285. # DrawToolShape
  3286. if isinstance(geometry, DrawToolShape):
  3287. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  3288. # Polygon: Descend into exterior and each interior.
  3289. if type(geometry) == Polygon:
  3290. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  3291. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  3292. if type(geometry) == LineString or type(geometry) == LinearRing:
  3293. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0,
  3294. tolerance=self.fcgeometry.drawing_tolerance))
  3295. if type(geometry) == Point:
  3296. pass
  3297. return plot_elements
  3298. def plot_all(self):
  3299. """
  3300. Plots all shapes in the editor.
  3301. :return: None
  3302. :rtype: None
  3303. """
  3304. # self.app.log.debug("plot_all()")
  3305. self.shapes.clear(update=True)
  3306. for shape in self.storage.get_objects():
  3307. if shape.geo is None: # TODO: This shouldn't have happened
  3308. continue
  3309. if shape in self.selected:
  3310. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  3311. continue
  3312. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  3313. for shape in self.utility:
  3314. self.plot_shape(geometry=shape.geo, linewidth=1)
  3315. continue
  3316. self.shapes.redraw()
  3317. def replot(self):
  3318. self.plot_all()
  3319. def on_shape_complete(self):
  3320. self.app.log.debug("on_shape_complete()")
  3321. # Add shape
  3322. self.add_shape(self.active_tool.geometry)
  3323. # Remove any utility shapes
  3324. self.delete_utility_geometry()
  3325. self.tool_shape.clear(update=True)
  3326. # Replot and reset tool.
  3327. self.replot()
  3328. # self.active_tool = type(self.active_tool)(self)
  3329. @staticmethod
  3330. def make_storage():
  3331. # Shape storage.
  3332. storage = FlatCAMRTreeStorage()
  3333. storage.get_points = DrawToolShape.get_pts
  3334. return storage
  3335. def select_tool(self, toolname):
  3336. """
  3337. Selects a drawing tool. Impacts the object and GUI.
  3338. :param toolname: Name of the tool.
  3339. :return: None
  3340. """
  3341. self.tools[toolname]["button"].setChecked(True)
  3342. self.on_tool_select(toolname)
  3343. def set_selected(self, shape):
  3344. # Remove and add to the end.
  3345. if shape in self.selected:
  3346. self.selected.remove(shape)
  3347. self.selected.append(shape)
  3348. def set_unselected(self, shape):
  3349. if shape in self.selected:
  3350. self.selected.remove(shape)
  3351. def snap(self, x, y):
  3352. """
  3353. Adjusts coordinates to snap settings.
  3354. :param x: Input coordinate X
  3355. :param y: Input coordinate Y
  3356. :return: Snapped (x, y)
  3357. """
  3358. snap_x, snap_y = (x, y)
  3359. snap_distance = Inf
  3360. # # ## Object (corner?) snap
  3361. # # ## No need for the objects, just the coordinates
  3362. # # ## in the index.
  3363. if self.options["corner_snap"]:
  3364. try:
  3365. nearest_pt, shape = self.storage.nearest((x, y))
  3366. nearest_pt_distance = distance((x, y), nearest_pt)
  3367. if nearest_pt_distance <= float(self.options["global_snap_max"]):
  3368. snap_distance = nearest_pt_distance
  3369. snap_x, snap_y = nearest_pt
  3370. except (StopIteration, AssertionError):
  3371. pass
  3372. # # ## Grid snap
  3373. if self.options["grid_snap"]:
  3374. if self.options["global_gridx"] != 0:
  3375. snap_x_ = round(x / self.options["global_gridx"]) * self.options['global_gridx']
  3376. else:
  3377. snap_x_ = x
  3378. # If the Grid_gap_linked on Grid Toolbar is checked then the snap distance on GridY entry will be ignored
  3379. # and it will use the snap distance from GridX entry
  3380. if self.app.ui.grid_gap_link_cb.isChecked():
  3381. if self.options["global_gridx"] != 0:
  3382. snap_y_ = round(y / self.options["global_gridx"]) * self.options['global_gridx']
  3383. else:
  3384. snap_y_ = y
  3385. else:
  3386. if self.options["global_gridy"] != 0:
  3387. snap_y_ = round(y / self.options["global_gridy"]) * self.options['global_gridy']
  3388. else:
  3389. snap_y_ = y
  3390. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  3391. if nearest_grid_distance < snap_distance:
  3392. snap_x, snap_y = (snap_x_, snap_y_)
  3393. return snap_x, snap_y
  3394. def update_fcgeometry(self, fcgeometry):
  3395. """
  3396. Transfers the geometry tool shape buffer to the selected geometry
  3397. object. The geometry already in the object are removed.
  3398. :param fcgeometry: FlatCAMGeometry
  3399. :return: None
  3400. """
  3401. if self.multigeo_tool:
  3402. fcgeometry.tools[self.multigeo_tool]['solid_geometry'] = []
  3403. # for shape in self.shape_buffer:
  3404. for shape in self.storage.get_objects():
  3405. fcgeometry.tools[self.multigeo_tool]['solid_geometry'].append(shape.geo)
  3406. self.multigeo_tool = None
  3407. else:
  3408. fcgeometry.solid_geometry = []
  3409. # for shape in self.shape_buffer:
  3410. for shape in self.storage.get_objects():
  3411. fcgeometry.solid_geometry.append(shape.geo)
  3412. def update_options(self, obj):
  3413. if self.paint_tooldia:
  3414. obj.options['cnctooldia'] = deepcopy(str(self.paint_tooldia))
  3415. self.paint_tooldia = None
  3416. return True
  3417. else:
  3418. return False
  3419. def union(self):
  3420. """
  3421. Makes union of selected polygons. Original polygons
  3422. are deleted.
  3423. :return: None.
  3424. """
  3425. results = unary_union([t.geo for t in self.get_selected()])
  3426. # Delete originals.
  3427. for_deletion = [s for s in self.get_selected()]
  3428. for shape in for_deletion:
  3429. self.delete_shape(shape)
  3430. # Selected geometry is now gone!
  3431. self.selected = []
  3432. self.add_shape(DrawToolShape(results))
  3433. self.replot()
  3434. def intersection_2(self):
  3435. """
  3436. Makes intersection of selected polygons. Original polygons are deleted.
  3437. :return: None
  3438. """
  3439. geo_shapes = self.get_selected()
  3440. try:
  3441. results = geo_shapes[0].geo
  3442. except Exception as e:
  3443. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3444. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3445. _("A selection of at least 2 geo items is required to do Intersection."))
  3446. self.select_tool('select')
  3447. return
  3448. for shape_el in geo_shapes[1:]:
  3449. results = results.intersection(shape_el.geo)
  3450. # Delete originals.
  3451. for_deletion = [s for s in self.get_selected()]
  3452. for shape_el in for_deletion:
  3453. self.delete_shape(shape_el)
  3454. # Selected geometry is now gone!
  3455. self.selected = []
  3456. self.add_shape(DrawToolShape(results))
  3457. self.replot()
  3458. def intersection(self):
  3459. """
  3460. Makes intersection of selected polygons. Original polygons are deleted.
  3461. :return: None
  3462. """
  3463. geo_shapes = self.get_selected()
  3464. results = []
  3465. intact = []
  3466. try:
  3467. intersector = geo_shapes[0].geo
  3468. except Exception as e:
  3469. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3470. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3471. _("A selection of at least 2 geo items is required to do Intersection."))
  3472. self.select_tool('select')
  3473. return
  3474. for shape_el in geo_shapes[1:]:
  3475. if intersector.intersects(shape_el.geo):
  3476. results.append(intersector.intersection(shape_el.geo))
  3477. else:
  3478. intact.append(shape_el)
  3479. if len(results) != 0:
  3480. # Delete originals.
  3481. for_deletion = [s for s in self.get_selected()]
  3482. for shape_el in for_deletion:
  3483. if shape_el not in intact:
  3484. self.delete_shape(shape_el)
  3485. for geo in results:
  3486. self.add_shape(DrawToolShape(geo))
  3487. # Selected geometry is now gone!
  3488. self.selected = []
  3489. self.replot()
  3490. def subtract(self):
  3491. selected = self.get_selected()
  3492. try:
  3493. tools = selected[1:]
  3494. toolgeo = unary_union([shp.geo for shp in tools]).buffer(0.0000001)
  3495. target = selected[0].geo
  3496. target = target.buffer(0.0000001)
  3497. result = target.difference(toolgeo)
  3498. for_deletion = [s for s in self.get_selected()]
  3499. for shape in for_deletion:
  3500. self.delete_shape(shape)
  3501. self.add_shape(DrawToolShape(result))
  3502. self.replot()
  3503. except Exception as e:
  3504. log.debug(str(e))
  3505. def subtract_2(self):
  3506. selected = self.get_selected()
  3507. try:
  3508. tools = selected[1:]
  3509. toolgeo = unary_union([shp.geo for shp in tools])
  3510. result = selected[0].geo.difference(toolgeo)
  3511. self.delete_shape(selected[0])
  3512. self.add_shape(DrawToolShape(result))
  3513. self.replot()
  3514. except Exception as e:
  3515. log.debug(str(e))
  3516. def cutpath(self):
  3517. selected = self.get_selected()
  3518. tools = selected[1:]
  3519. toolgeo = unary_union([shp.geo for shp in tools])
  3520. target = selected[0]
  3521. if type(target.geo) == Polygon:
  3522. for ring in poly2rings(target.geo):
  3523. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  3524. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  3525. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  3526. elif type(target.geo) == MultiLineString:
  3527. try:
  3528. for linestring in target.geo:
  3529. self.add_shape(DrawToolShape(linestring.difference(toolgeo)))
  3530. except Exception as e:
  3531. self.app.log.warning("Current LinearString does not intersect the target. %s" % str(e))
  3532. else:
  3533. self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo)))
  3534. return
  3535. self.delete_shape(target)
  3536. self.replot()
  3537. def buffer(self, buf_distance, join_style):
  3538. selected = self.get_selected()
  3539. if buf_distance < 0:
  3540. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3541. _("Negative buffer value is not accepted. Use Buffer interior to generate an "
  3542. "'inside' shape"))
  3543. # deselect everything
  3544. self.selected = []
  3545. self.replot()
  3546. return 'fail'
  3547. if len(selected) == 0:
  3548. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3549. _("Nothing selected for buffering."))
  3550. return 'fail'
  3551. if not isinstance(buf_distance, float):
  3552. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3553. _("Invalid distance for buffering."))
  3554. # deselect everything
  3555. self.selected = []
  3556. self.replot()
  3557. return 'fail'
  3558. results = []
  3559. for t in selected:
  3560. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3561. results.append((t.geo.exterior).buffer(
  3562. buf_distance - 1e-10,
  3563. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3564. join_style=join_style)
  3565. )
  3566. else:
  3567. results.append(t.geo.buffer(
  3568. buf_distance - 1e-10,
  3569. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3570. join_style=join_style)
  3571. )
  3572. if not results:
  3573. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3574. _("Failed, the result is empty. Choose a different buffer value."))
  3575. # deselect everything
  3576. self.selected = []
  3577. self.replot()
  3578. return 'fail'
  3579. for sha in results:
  3580. self.add_shape(DrawToolShape(sha))
  3581. self.replot()
  3582. self.app.inform.emit('[success] %s' %
  3583. _("Full buffer geometry created."))
  3584. def buffer_int(self, buf_distance, join_style):
  3585. selected = self.get_selected()
  3586. if buf_distance < 0:
  3587. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3588. _("Negative buffer value is not accepted.")
  3589. )
  3590. # deselect everything
  3591. self.selected = []
  3592. self.replot()
  3593. return 'fail'
  3594. if len(selected) == 0:
  3595. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3596. _("Nothing selected for buffering."))
  3597. return 'fail'
  3598. if not isinstance(buf_distance, float):
  3599. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3600. _("Invalid distance for buffering."))
  3601. # deselect everything
  3602. self.selected = []
  3603. self.replot()
  3604. return 'fail'
  3605. results = []
  3606. for t in selected:
  3607. if isinstance(t.geo, LinearRing):
  3608. t.geo = Polygon(t.geo)
  3609. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3610. results.append((t.geo).buffer(
  3611. -buf_distance + 1e-10,
  3612. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3613. join_style=join_style)
  3614. )
  3615. if not results:
  3616. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3617. _("Failed, the result is empty. Choose a smaller buffer value."))
  3618. # deselect everything
  3619. self.selected = []
  3620. self.replot()
  3621. return 'fail'
  3622. for sha in results:
  3623. self.add_shape(DrawToolShape(sha))
  3624. self.replot()
  3625. self.app.inform.emit('[success] %s' %
  3626. _("Interior buffer geometry created."))
  3627. def buffer_ext(self, buf_distance, join_style):
  3628. selected = self.get_selected()
  3629. if buf_distance < 0:
  3630. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3631. _("Negative buffer value is not accepted. Use Buffer interior to generate an "
  3632. "'inside' shape"))
  3633. # deselect everything
  3634. self.selected = []
  3635. self.replot()
  3636. return
  3637. if len(selected) == 0:
  3638. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3639. _("Nothing selected for buffering."))
  3640. return
  3641. if not isinstance(buf_distance, float):
  3642. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3643. _("Invalid distance for buffering."))
  3644. # deselect everything
  3645. self.selected = []
  3646. self.replot()
  3647. return
  3648. results = []
  3649. for t in selected:
  3650. if isinstance(t.geo, LinearRing):
  3651. t.geo = Polygon(t.geo)
  3652. if isinstance(t.geo, Polygon) and not t.geo.is_empty:
  3653. results.append((t.geo).buffer(
  3654. buf_distance,
  3655. resolution=int(int(self.app.defaults["geometry_circle_steps"]) / 4),
  3656. join_style=join_style)
  3657. )
  3658. if not results:
  3659. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3660. _("Failed, the result is empty. Choose a different buffer value."))
  3661. # deselect everything
  3662. self.selected = []
  3663. self.replot()
  3664. return
  3665. for sha in results:
  3666. self.add_shape(DrawToolShape(sha))
  3667. self.replot()
  3668. self.app.inform.emit('[success] %s' %
  3669. _("Exterior buffer geometry created."))
  3670. # def paint(self, tooldia, overlap, margin, method):
  3671. # selected = self.get_selected()
  3672. #
  3673. # if len(selected) == 0:
  3674. # self.app.inform.emit("[WARNING] Nothing selected for painting.")
  3675. # return
  3676. #
  3677. # for param in [tooldia, overlap, margin]:
  3678. # if not isinstance(param, float):
  3679. # param_name = [k for k, v in locals().items() if v is param][0]
  3680. # self.app.inform.emit("[WARNING] Invalid value for {}".format(param))
  3681. #
  3682. # # Todo: Check for valid method.
  3683. #
  3684. # # Todo: This is the 3rd implementation on painting polys... try to consolidate
  3685. #
  3686. # results = []
  3687. #
  3688. # def recurse(geo):
  3689. # try:
  3690. # for subg in geo:
  3691. # for subsubg in recurse(subg):
  3692. # yield subsubg
  3693. # except TypeError:
  3694. # if isinstance(geo, LinearRing):
  3695. # yield geo
  3696. #
  3697. # raise StopIteration
  3698. #
  3699. # for geo in selected:
  3700. # print(type(geo.geo))
  3701. #
  3702. # local_results = []
  3703. # for poly in recurse(geo.geo):
  3704. # if method == "seed":
  3705. # # Type(cp) == FlatCAMRTreeStorage | None
  3706. # cp = Geometry.clear_polygon2(poly.buffer(-margin),
  3707. # tooldia, overlap=overlap)
  3708. #
  3709. # else:
  3710. # # Type(cp) == FlatCAMRTreeStorage | None
  3711. # cp = Geometry.clear_polygon(poly.buffer(-margin),
  3712. # tooldia, overlap=overlap)
  3713. #
  3714. # if cp is not None:
  3715. # local_results += list(cp.get_objects())
  3716. #
  3717. # results.append(cascaded_union(local_results))
  3718. #
  3719. # # This is a dirty patch:
  3720. # for r in results:
  3721. # self.add_shape(DrawToolShape(r))
  3722. #
  3723. # self.replot()
  3724. def paint(self, tooldia, overlap, margin, connect, contour, method):
  3725. self.paint_tooldia = tooldia
  3726. selected = self.get_selected()
  3727. if len(selected) == 0:
  3728. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3729. _("Nothing selected for painting."))
  3730. return
  3731. for param in [tooldia, overlap, margin]:
  3732. if not isinstance(param, float):
  3733. param_name = [k for k, v in locals().items() if v is param][0]
  3734. self.app.inform.emit('[WARNING] %s: %s' %
  3735. (_("Invalid value for"), str(param)))
  3736. results = []
  3737. if overlap >= 1:
  3738. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3739. _("Could not do Paint. Overlap value has to be less than 1.00 (100%%)."))
  3740. return
  3741. def recurse(geometry, reset=True):
  3742. """
  3743. Creates a list of non-iterable linear geometry objects.
  3744. Results are placed in self.flat_geometry
  3745. :param geometry: Shapely type or list or list of list of such.
  3746. :param reset: Clears the contents of self.flat_geometry.
  3747. """
  3748. if geometry is None:
  3749. return
  3750. if reset:
  3751. self.flat_geo = []
  3752. # If iterable, expand recursively.
  3753. try:
  3754. for geo_el in geometry:
  3755. if geo_el is not None:
  3756. recurse(geometry=geo_el, reset=False)
  3757. # Not iterable, do the actual indexing and add.
  3758. except TypeError:
  3759. self.flat_geo.append(geometry)
  3760. return self.flat_geo
  3761. for geo in selected:
  3762. local_results = []
  3763. for geo_obj in recurse(geo.geo):
  3764. try:
  3765. if type(geo_obj) == Polygon:
  3766. poly_buf = geo_obj.buffer(-margin)
  3767. else:
  3768. poly_buf = Polygon(geo_obj).buffer(-margin)
  3769. if method == "seed":
  3770. cp = Geometry.clear_polygon2(poly_buf,
  3771. tooldia, self.app.defaults["geometry_circle_steps"],
  3772. overlap=overlap, contour=contour, connect=connect)
  3773. elif method == "lines":
  3774. cp = Geometry.clear_polygon3(poly_buf,
  3775. tooldia, self.app.defaults["geometry_circle_steps"],
  3776. overlap=overlap, contour=contour, connect=connect)
  3777. else:
  3778. cp = Geometry.clear_polygon(poly_buf,
  3779. tooldia, self.app.defaults["geometry_circle_steps"],
  3780. overlap=overlap, contour=contour, connect=connect)
  3781. if cp is not None:
  3782. local_results += list(cp.get_objects())
  3783. except Exception as e:
  3784. log.debug("Could not Paint the polygons. %s" % str(e))
  3785. self.app.inform.emit('[ERROR] %s\n%s' %
  3786. (_("Could not do Paint. Try a different combination of"
  3787. " parameters. Or a different method of Paint"),
  3788. str(e)
  3789. )
  3790. )
  3791. return
  3792. # add the result to the results list
  3793. results.append(cascaded_union(local_results))
  3794. # This is a dirty patch:
  3795. for r in results:
  3796. self.add_shape(DrawToolShape(r))
  3797. self.app.inform.emit(
  3798. '[success] %s' % _("Paint done."))
  3799. self.replot()
  3800. def distance(pt1, pt2):
  3801. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  3802. def mag(vec):
  3803. return sqrt(vec[0] ** 2 + vec[1] ** 2)
  3804. def poly2rings(poly):
  3805. return [poly.exterior] + [interior for interior in poly.interiors]
  3806. def get_shapely_list_bounds(geometry_list):
  3807. xmin = Inf
  3808. ymin = Inf
  3809. xmax = -Inf
  3810. ymax = -Inf
  3811. for gs in geometry_list:
  3812. try:
  3813. gxmin, gymin, gxmax, gymax = gs.bounds
  3814. xmin = min([xmin, gxmin])
  3815. ymin = min([ymin, gymin])
  3816. xmax = max([xmax, gxmax])
  3817. ymax = max([ymax, gymax])
  3818. except Exception as e:
  3819. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry. --> %s" % str(e))
  3820. return [xmin, ymin, xmax, ymax]