FlatCAMObj.py 223 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323
  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. from io import StringIO
  9. from PyQt5 import QtCore, QtGui
  10. from PyQt5.QtCore import Qt
  11. import copy
  12. import inspect # TODO: For debugging only.
  13. from shapely.geometry.base import JOIN_STYLE
  14. from datetime import datetime
  15. import FlatCAMApp
  16. from ObjectUI import *
  17. from FlatCAMCommon import LoudDict
  18. from FlatCAMEditor import FlatCAMGeoEditor
  19. from camlib import *
  20. from VisPyVisuals import ShapeCollectionVisual
  21. import itertools
  22. # Interrupts plotting process if FlatCAMObj has been deleted
  23. class ObjectDeleted(Exception):
  24. pass
  25. class ValidationError(Exception):
  26. def __init__(self, message, errors):
  27. super().__init__(message)
  28. self.errors = errors
  29. ########################################
  30. ## FlatCAMObj ##
  31. ########################################
  32. class FlatCAMObj(QtCore.QObject):
  33. """
  34. Base type of objects handled in FlatCAM. These become interactive
  35. in the GUI, can be plotted, and their options can be modified
  36. by the user in their respective forms.
  37. """
  38. # Instance of the application to which these are related.
  39. # The app should set this value.
  40. app = None
  41. def __init__(self, name):
  42. """
  43. Constructor.
  44. :param name: Name of the object given by the user.
  45. :return: FlatCAMObj
  46. """
  47. QtCore.QObject.__init__(self)
  48. # View
  49. self.ui = None
  50. self.options = LoudDict(name=name)
  51. self.options.set_change_callback(self.on_options_change)
  52. self.form_fields = {}
  53. self.kind = None # Override with proper name
  54. # self.shapes = ShapeCollection(parent=self.app.plotcanvas.vispy_canvas.view.scene)
  55. self.shapes = self.app.plotcanvas.new_shape_group()
  56. self.item = None # Link with project view item
  57. self.muted_ui = False
  58. self.deleted = False
  59. self._drawing_tolerance = 0.01
  60. # assert isinstance(self.ui, ObjectUI)
  61. # self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  62. # self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  63. # self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  64. def __del__(self):
  65. pass
  66. def __str__(self):
  67. return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
  68. def from_dict(self, d):
  69. """
  70. This supersedes ``from_dict`` in derived classes. Derived classes
  71. must inherit from FlatCAMObj first, then from derivatives of Geometry.
  72. ``self.options`` is only updated, not overwritten. This ensures that
  73. options set by the app do not vanish when reading the objects
  74. from a project file.
  75. :param d: Dictionary with attributes to set.
  76. :return: None
  77. """
  78. for attr in self.ser_attrs:
  79. if attr == 'options':
  80. self.options.update(d[attr])
  81. else:
  82. try:
  83. setattr(self, attr, d[attr])
  84. except KeyError:
  85. log.debug("FlatCAMObj.from_dict() --> KeyError: %s. Means that we are loading an old project that don't"
  86. "have all attributes in the latest FlatCAM." % str(attr))
  87. pass
  88. def on_options_change(self, key):
  89. # Update form on programmatically options change
  90. self.set_form_item(key)
  91. # Set object visibility
  92. if key == 'plot':
  93. self.visible = self.options['plot']
  94. # self.emit(QtCore.SIGNAL("optionChanged"), key)
  95. self.optionChanged.emit(key)
  96. def set_ui(self, ui):
  97. self.ui = ui
  98. self.form_fields = {"name": self.ui.name_entry}
  99. assert isinstance(self.ui, ObjectUI)
  100. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  101. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  102. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  103. self.ui.offsetvector_entry.returnPressed.connect(self.on_offset_button_click)
  104. self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  105. # self.ui.skew_button.clicked.connect(self.on_skew_button_click)
  106. def build_ui(self):
  107. """
  108. Sets up the UI/form for this object. Show the UI
  109. in the App.
  110. :return: None
  111. :rtype: None
  112. """
  113. self.muted_ui = True
  114. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  115. # Remove anything else in the box
  116. # box_children = self.app.ui.notebook.selected_contents.get_children()
  117. # for child in box_children:
  118. # self.app.ui.notebook.selected_contents.remove(child)
  119. # while self.app.ui.selected_layout.count():
  120. # self.app.ui.selected_layout.takeAt(0)
  121. # Put in the UI
  122. # box_selected.pack_start(sw, True, True, 0)
  123. # self.app.ui.notebook.selected_contents.add(self.ui)
  124. # self.app.ui.selected_layout.addWidget(self.ui)
  125. try:
  126. self.app.ui.selected_scroll_area.takeWidget()
  127. except:
  128. self.app.log.debug("Nothing to remove")
  129. self.app.ui.selected_scroll_area.setWidget(self.ui)
  130. self.muted_ui = False
  131. def on_name_activate(self):
  132. old_name = copy.copy(self.options["name"])
  133. new_name = self.ui.name_entry.get_value()
  134. # update the SHELL auto-completer model data
  135. try:
  136. self.app.myKeywords.remove(old_name)
  137. self.app.myKeywords.append(new_name)
  138. self.app.shell._edit.set_model_data(self.app.myKeywords)
  139. except:
  140. log.debug("on_name_activate() --> Could not remove the old object name from auto-completer model list")
  141. self.options["name"] = self.ui.name_entry.get_value()
  142. self.app.inform.emit("[success]Name changed from %s to %s" % (old_name, new_name))
  143. def on_offset_button_click(self):
  144. self.app.report_usage("obj_on_offset_button")
  145. self.read_form()
  146. vect = self.ui.offsetvector_entry.get_value()
  147. self.offset(vect)
  148. self.plot()
  149. self.app.object_changed.emit(self)
  150. def on_scale_button_click(self):
  151. self.app.report_usage("obj_on_scale_button")
  152. self.read_form()
  153. factor = self.ui.scale_entry.get_value()
  154. self.scale(factor)
  155. self.plot()
  156. self.app.object_changed.emit(self)
  157. def on_skew_button_click(self):
  158. self.app.report_usage("obj_on_skew_button")
  159. self.read_form()
  160. xangle = self.ui.xangle_entry.get_value()
  161. yangle = self.ui.yangle_entry.get_value()
  162. self.skew(xangle, yangle)
  163. self.plot()
  164. self.app.object_changed.emit(self)
  165. def to_form(self):
  166. """
  167. Copies options to the UI form.
  168. :return: None
  169. """
  170. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.to_form()")
  171. for option in self.options:
  172. try:
  173. self.set_form_item(option)
  174. except:
  175. self.app.log.warning("Unexpected error:", sys.exc_info())
  176. def read_form(self):
  177. """
  178. Reads form into ``self.options``.
  179. :return: None
  180. :rtype: None
  181. """
  182. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
  183. for option in self.options:
  184. try:
  185. self.read_form_item(option)
  186. except:
  187. self.app.log.warning("Unexpected error:", sys.exc_info())
  188. def set_form_item(self, option):
  189. """
  190. Copies the specified option to the UI form.
  191. :param option: Name of the option (Key in ``self.options``).
  192. :type option: str
  193. :return: None
  194. """
  195. try:
  196. self.form_fields[option].set_value(self.options[option])
  197. except KeyError:
  198. # self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
  199. pass
  200. def read_form_item(self, option):
  201. """
  202. Reads the specified option from the UI form into ``self.options``.
  203. :param option: Name of the option.
  204. :type option: str
  205. :return: None
  206. """
  207. try:
  208. self.options[option] = self.form_fields[option].get_value()
  209. except KeyError:
  210. self.app.log.warning("Failed to read option from field: %s" % option)
  211. def plot(self):
  212. """
  213. Plot this object (Extend this method to implement the actual plotting).
  214. Call this in descendants before doing the plotting.
  215. :return: Whether to continue plotting or not depending on the "plot" option.
  216. :rtype: bool
  217. """
  218. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
  219. if self.deleted:
  220. return False
  221. self.clear()
  222. return True
  223. def serialize(self):
  224. """
  225. Returns a representation of the object as a dictionary so
  226. it can be later exported as JSON. Override this method.
  227. :return: Dictionary representing the object
  228. :rtype: dict
  229. """
  230. return
  231. def deserialize(self, obj_dict):
  232. """
  233. Re-builds an object from its serialized version.
  234. :param obj_dict: Dictionary representing a FlatCAMObj
  235. :type obj_dict: dict
  236. :return: None
  237. """
  238. return
  239. def add_shape(self, **kwargs):
  240. if self.deleted:
  241. raise ObjectDeleted()
  242. else:
  243. key = self.shapes.add(tolerance=self.drawing_tolerance, **kwargs)
  244. return key
  245. @property
  246. def visible(self):
  247. return self.shapes.visible
  248. @visible.setter
  249. def visible(self, value):
  250. self.shapes.visible = value
  251. # Not all object types has annotations
  252. try:
  253. self.annotation.visible = value
  254. except AttributeError:
  255. pass
  256. @property
  257. def drawing_tolerance(self):
  258. return self._drawing_tolerance if self.units == 'MM' or not self.units else self._drawing_tolerance / 25.4
  259. @drawing_tolerance.setter
  260. def drawing_tolerance(self, value):
  261. self._drawing_tolerance = value if self.units == 'MM' or not self.units else value / 25.4
  262. def clear(self, update=False):
  263. self.shapes.clear(update)
  264. # Not all object types has annotations
  265. try:
  266. self.annotation.clear(update)
  267. except AttributeError:
  268. pass
  269. def delete(self):
  270. # Free resources
  271. del self.ui
  272. del self.options
  273. # Set flag
  274. self.deleted = True
  275. class FlatCAMGerber(FlatCAMObj, Gerber):
  276. """
  277. Represents Gerber code.
  278. """
  279. optionChanged = QtCore.pyqtSignal(str)
  280. ui_type = GerberObjectUI
  281. @staticmethod
  282. def merge(grb_list, grb_final):
  283. """
  284. Merges the geometry of objects in geo_list into
  285. the geometry of geo_final.
  286. :param grb_list: List of FlatCAMGerber Objects to join.
  287. :param grb_final: Destination FlatCAMGeometry object.
  288. :return: None
  289. """
  290. if grb_final.solid_geometry is None:
  291. grb_final.solid_geometry = []
  292. grb_final.follow_geometry = []
  293. if type(grb_final.solid_geometry) is not list:
  294. grb_final.solid_geometry = [grb_final.solid_geometry]
  295. grb_final.follow_geometry = [grb_final.follow_geometry]
  296. for grb in grb_list:
  297. for option in grb.options:
  298. if option is not 'name':
  299. try:
  300. grb_final.options[option] = grb.options[option]
  301. except:
  302. log.warning("Failed to copy option.", option)
  303. # Expand lists
  304. if type(grb) is list:
  305. FlatCAMGerber.merge(grb, grb_final)
  306. else: # If not list, just append
  307. for geos in grb.solid_geometry:
  308. grb_final.solid_geometry.append(geos)
  309. grb_final.follow_geometry.append(geos)
  310. grb_final.solid_geometry = MultiPolygon(grb_final.solid_geometry)
  311. grb_final.follow_geometry = MultiPolygon(grb_final.follow_geometry)
  312. def __init__(self, name):
  313. Gerber.__init__(self, steps_per_circle=int(self.app.defaults["gerber_circle_steps"]))
  314. FlatCAMObj.__init__(self, name)
  315. self.kind = "gerber"
  316. # The 'name' is already in self.options from FlatCAMObj
  317. # Automatically updates the UI
  318. self.options.update({
  319. "plot": True,
  320. "multicolored": False,
  321. "solid": False,
  322. "isotooldia": 0.016,
  323. "isopasses": 1,
  324. "isooverlap": 0.15,
  325. "milling_type": "cl",
  326. "combine_passes": True,
  327. "noncoppermargin": 0.0,
  328. "noncopperrounded": False,
  329. "bboxmargin": 0.0,
  330. "bboxrounded": False
  331. })
  332. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  333. self.iso_type = 2
  334. self.multigeo = False
  335. self.follow = False
  336. self.apertures_row = 0
  337. # store the source file here
  338. self.source_file = ""
  339. # assert isinstance(self.ui, GerberObjectUI)
  340. # self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  341. # self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  342. # self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  343. # self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  344. # self.ui.generate_cutout_button.clicked.connect(self.on_generatecutout_button_click)
  345. # self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  346. # self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  347. # Attributes to be included in serialization
  348. # Always append to it because it carries contents
  349. # from predecessors.
  350. self.ser_attrs += ['options', 'kind']
  351. def set_ui(self, ui):
  352. """
  353. Maps options with GUI inputs.
  354. Connects GUI events to methods.
  355. :param ui: GUI object.
  356. :type ui: GerberObjectUI
  357. :return: None
  358. """
  359. FlatCAMObj.set_ui(self, ui)
  360. FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
  361. self.form_fields.update({
  362. "plot": self.ui.plot_cb,
  363. "multicolored": self.ui.multicolored_cb,
  364. "solid": self.ui.solid_cb,
  365. "isotooldia": self.ui.iso_tool_dia_entry,
  366. "isopasses": self.ui.iso_width_entry,
  367. "isooverlap": self.ui.iso_overlap_entry,
  368. "milling_type": self.ui.milling_type_radio,
  369. "combine_passes": self.ui.combine_passes_cb,
  370. "noncoppermargin": self.ui.noncopper_margin_entry,
  371. "noncopperrounded": self.ui.noncopper_rounded_cb,
  372. "bboxmargin": self.ui.bbmargin_entry,
  373. "bboxrounded": self.ui.bbrounded_cb
  374. })
  375. # Fill form fields only on object create
  376. self.to_form()
  377. assert isinstance(self.ui, GerberObjectUI)
  378. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  379. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  380. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  381. self.ui.generate_ext_iso_button.clicked.connect(self.on_ext_iso_button_click)
  382. self.ui.generate_int_iso_button.clicked.connect(self.on_int_iso_button_click)
  383. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  384. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  385. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  386. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  387. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  388. self.ui.aperture_table_visibility_cb.stateChanged.connect(self.on_aperture_table_visibility_change)
  389. self.ui.follow_cb.stateChanged.connect(self.on_follow_cb_click)
  390. # Show/Hide Advanced Options
  391. if self.app.defaults["global_app_level"] == 'b':
  392. self.ui.level.setText('<span style="color:green;"><b>Basic</b></span>')
  393. self.ui.apertures_table_label.hide()
  394. self.ui.aperture_table_visibility_cb.hide()
  395. self.ui.milling_type_label.hide()
  396. self.ui.milling_type_radio.hide()
  397. self.ui.generate_ext_iso_button.hide()
  398. self.ui.generate_int_iso_button.hide()
  399. else:
  400. self.ui.level.setText('<span style="color:red;"><b>Advanced</b></span>')
  401. self.build_ui()
  402. def build_ui(self):
  403. FlatCAMObj.build_ui(self)
  404. try:
  405. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  406. self.ui.apertures_table.itemChanged.disconnect()
  407. except:
  408. pass
  409. n = len(self.apertures) + len(self.aperture_macros)
  410. self.ui.apertures_table.setRowCount(n)
  411. self.apertures_row = 0
  412. aper_no = self.apertures_row + 1
  413. sort = []
  414. for k, v in list(self.apertures.items()):
  415. sort.append(int(k))
  416. sorted_apertures = sorted(sort)
  417. sort = []
  418. for k, v in list(self.aperture_macros.items()):
  419. sort.append(k)
  420. sorted_macros = sorted(sort)
  421. for ap_code in sorted_apertures:
  422. ap_code = str(ap_code)
  423. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  424. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  425. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  426. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  427. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  428. ap_type_item = QtWidgets.QTableWidgetItem(str(self.apertures[ap_code]['type']))
  429. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  430. if str(self.apertures[ap_code]['type']) == 'R' or str(self.apertures[ap_code]['type']) == 'O':
  431. ap_dim_item = QtWidgets.QTableWidgetItem(
  432. '%.4f, %.4f' % (self.apertures[ap_code]['width'] * self.file_units_factor,
  433. self.apertures[ap_code]['height'] * self.file_units_factor
  434. )
  435. )
  436. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  437. elif str(self.apertures[ap_code]['type']) == 'P':
  438. ap_dim_item = QtWidgets.QTableWidgetItem(
  439. '%.4f, %.4f' % (self.apertures[ap_code]['diam'] * self.file_units_factor,
  440. self.apertures[ap_code]['nVertices'] * self.file_units_factor)
  441. )
  442. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  443. else:
  444. ap_dim_item = QtWidgets.QTableWidgetItem('')
  445. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  446. try:
  447. if self.apertures[ap_code]['size'] is not None:
  448. ap_size_item = QtWidgets.QTableWidgetItem('%.4f' %
  449. float(self.apertures[ap_code]['size'] *
  450. self.file_units_factor))
  451. else:
  452. ap_size_item = QtWidgets.QTableWidgetItem('')
  453. except KeyError:
  454. ap_size_item = QtWidgets.QTableWidgetItem('')
  455. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  456. plot_item = FCCheckBox()
  457. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  458. if self.ui.plot_cb.isChecked():
  459. plot_item.setChecked(True)
  460. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  461. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  462. self.ui.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  463. self.ui.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  464. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, plot_item)
  465. self.apertures_row += 1
  466. for ap_code in sorted_macros:
  467. ap_code = str(ap_code)
  468. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  469. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  470. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  471. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  472. ap_type_item = QtWidgets.QTableWidgetItem('AM')
  473. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  474. plot_item = FCCheckBox()
  475. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  476. if self.ui.plot_cb.isChecked():
  477. plot_item.setChecked(True)
  478. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  479. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  480. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, plot_item)
  481. self.apertures_row += 1
  482. self.ui.apertures_table.selectColumn(0)
  483. #
  484. self.ui.apertures_table.resizeColumnsToContents()
  485. self.ui.apertures_table.resizeRowsToContents()
  486. vertical_header = self.ui.apertures_table.verticalHeader()
  487. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  488. vertical_header.hide()
  489. self.ui.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  490. horizontal_header = self.ui.apertures_table.horizontalHeader()
  491. horizontal_header.setMinimumSectionSize(10)
  492. horizontal_header.setDefaultSectionSize(70)
  493. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  494. horizontal_header.resizeSection(0, 20)
  495. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  496. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  497. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  498. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  499. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  500. horizontal_header.resizeSection(5, 17)
  501. self.ui.apertures_table.setColumnWidth(5, 17)
  502. self.ui.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  503. self.ui.apertures_table.setSortingEnabled(False)
  504. self.ui.apertures_table.setMinimumHeight(self.ui.apertures_table.getHeight())
  505. # self.ui_connect()
  506. def on_generatenoncopper_button_click(self, *args):
  507. self.app.report_usage("gerber_on_generatenoncopper_button")
  508. self.read_form()
  509. name = self.options["name"] + "_noncopper"
  510. def geo_init(geo_obj, app_obj):
  511. assert isinstance(geo_obj, FlatCAMGeometry)
  512. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["noncoppermargin"]))
  513. if not self.options["noncopperrounded"]:
  514. bounding_box = bounding_box.envelope
  515. non_copper = bounding_box.difference(self.solid_geometry)
  516. geo_obj.solid_geometry = non_copper
  517. # TODO: Check for None
  518. self.app.new_object("geometry", name, geo_init)
  519. def on_generatebb_button_click(self, *args):
  520. self.app.report_usage("gerber_on_generatebb_button")
  521. self.read_form()
  522. name = self.options["name"] + "_bbox"
  523. def geo_init(geo_obj, app_obj):
  524. assert isinstance(geo_obj, FlatCAMGeometry)
  525. # Bounding box with rounded corners
  526. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["bboxmargin"]))
  527. if not self.options["bboxrounded"]: # Remove rounded corners
  528. bounding_box = bounding_box.envelope
  529. geo_obj.solid_geometry = bounding_box
  530. self.app.new_object("geometry", name, geo_init)
  531. def on_ext_iso_button_click(self, *args):
  532. if self.ui.follow_cb.get_value() == True:
  533. obj = self.app.collection.get_active()
  534. obj.follow()
  535. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  536. obj.ui.plot_cb.toggle()
  537. else:
  538. self.app.report_usage("gerber_on_iso_button")
  539. self.read_form()
  540. self.isolate(iso_type=0)
  541. def on_int_iso_button_click(self, *args):
  542. if self.ui.follow_cb.get_value() is True:
  543. obj = self.app.collection.get_active()
  544. obj.follow()
  545. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  546. obj.ui.plot_cb.toggle()
  547. else:
  548. self.app.report_usage("gerber_on_iso_button")
  549. self.read_form()
  550. self.isolate(iso_type=1)
  551. def on_iso_button_click(self, *args):
  552. if self.ui.follow_cb.get_value() is True:
  553. obj = self.app.collection.get_active()
  554. obj.follow_geo()
  555. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  556. obj.ui.plot_cb.toggle()
  557. else:
  558. self.app.report_usage("gerber_on_iso_button")
  559. self.read_form()
  560. self.isolate()
  561. def follow_geo(self, outname=None):
  562. """
  563. Creates a geometry object "following" the gerber paths.
  564. :return: None
  565. """
  566. # default_name = self.options["name"] + "_follow"
  567. # follow_name = outname or default_name
  568. if outname is None:
  569. follow_name = self.options["name"] + "_follow"
  570. else:
  571. follow_name = outname
  572. def follow_init(follow_obj, app):
  573. # Propagate options
  574. follow_obj.options["cnctooldia"] = float(self.options["isotooldia"])
  575. follow_obj.solid_geometry = self.follow_geometry
  576. # TODO: Do something if this is None. Offer changing name?
  577. try:
  578. self.app.new_object("geometry", follow_name, follow_init)
  579. except Exception as e:
  580. return "Operation failed: %s" % str(e)
  581. def isolate(self, iso_type=None, dia=None, passes=None, overlap=None,
  582. outname=None, combine=None, milling_type=None, follow=None):
  583. """
  584. Creates an isolation routing geometry object in the project.
  585. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  586. :param dia: Tool diameter
  587. :param passes: Number of tool widths to cut
  588. :param overlap: Overlap between passes in fraction of tool diameter
  589. :param outname: Base name of the output object
  590. :return: None
  591. """
  592. if dia is None:
  593. dia = float(self.options["isotooldia"])
  594. if passes is None:
  595. passes = int(self.options["isopasses"])
  596. if overlap is None:
  597. overlap = float(self.options["isooverlap"])
  598. if combine is None:
  599. combine = self.options["combine_passes"]
  600. else:
  601. combine = bool(combine)
  602. if milling_type is None:
  603. milling_type = self.options["milling_type"]
  604. if iso_type is None:
  605. self.iso_type = 2
  606. else:
  607. self.iso_type = iso_type
  608. base_name = self.options["name"] + "_iso"
  609. base_name = outname or base_name
  610. def generate_envelope(offset, invert, envelope_iso_type=2, follow=None):
  611. # isolation_geometry produces an envelope that is going on the left of the geometry
  612. # (the copper features). To leave the least amount of burrs on the features
  613. # the tool needs to travel on the right side of the features (this is called conventional milling)
  614. # the first pass is the one cutting all of the features, so it needs to be reversed
  615. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  616. # to cut on the right side of the left over copper i.e on the left side of the features.
  617. try:
  618. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  619. except Exception as e:
  620. log.debug(str(e))
  621. return 'fail'
  622. if invert:
  623. try:
  624. if type(geom) is MultiPolygon:
  625. pl = []
  626. for p in geom:
  627. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  628. geom = MultiPolygon(pl)
  629. elif type(geom) is Polygon:
  630. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  631. else:
  632. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> Unexpected Geometry")
  633. except Exception as e:
  634. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> %s" % str(e))
  635. return geom
  636. if combine:
  637. if self.iso_type == 0:
  638. iso_name = self.options["name"] + "_ext_iso"
  639. elif self.iso_type == 1:
  640. iso_name = self.options["name"] + "_int_iso"
  641. else:
  642. iso_name = base_name
  643. # TODO: This is ugly. Create way to pass data into init function.
  644. def iso_init(geo_obj, app_obj):
  645. # Propagate options
  646. geo_obj.options["cnctooldia"] = float(self.options["isotooldia"])
  647. geo_obj.solid_geometry = []
  648. for i in range(passes):
  649. iso_offset = (((2 * i + 1) / 2.0) * dia) - (i * overlap * dia)
  650. # if milling type is climb then the move is counter-clockwise around features
  651. if milling_type == 'cl':
  652. # geom = generate_envelope (offset, i == 0)
  653. geom = generate_envelope(iso_offset, 1, envelope_iso_type=self.iso_type, follow=follow)
  654. else:
  655. geom = generate_envelope(iso_offset, 0, envelope_iso_type=self.iso_type, follow=follow)
  656. geo_obj.solid_geometry.append(geom)
  657. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  658. # or just looking in the lists (they are one level depth) and if any is not empty
  659. # proceed with object creation, if there are empty and the number of them is the length
  660. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  661. empty_cnt = 0
  662. if not isinstance(geo_obj.solid_geometry, list):
  663. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  664. for g in geo_obj.solid_geometry:
  665. if g:
  666. app_obj.inform.emit("[success]Isolation geometry created: %s" % geo_obj.options["name"])
  667. break
  668. else:
  669. empty_cnt += 1
  670. if empty_cnt == len(geo_obj.solid_geometry):
  671. raise ValidationError("Empty Geometry", None)
  672. geo_obj.multigeo = False
  673. # TODO: Do something if this is None. Offer changing name?
  674. self.app.new_object("geometry", iso_name, iso_init)
  675. else:
  676. for i in range(passes):
  677. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  678. if passes > 1:
  679. if self.iso_type == 0:
  680. iso_name = self.options["name"] + "_ext_iso" + str(i + 1)
  681. elif self.iso_type == 1:
  682. iso_name = self.options["name"] + "_int_iso" + str(i + 1)
  683. else:
  684. iso_name = base_name + str(i + 1)
  685. else:
  686. if self.iso_type == 0:
  687. iso_name = self.options["name"] + "_ext_iso"
  688. elif self.iso_type == 1:
  689. iso_name = self.options["name"] + "_int_iso"
  690. else:
  691. iso_name = base_name
  692. # TODO: This is ugly. Create way to pass data into init function.
  693. def iso_init(geo_obj, app_obj):
  694. # Propagate options
  695. geo_obj.options["cnctooldia"] = float(self.options["isotooldia"])
  696. # if milling type is climb then the move is counter-clockwise around features
  697. if milling_type == 'cl':
  698. # geo_obj.solid_geometry = generate_envelope(offset, i == 0)
  699. geo_obj.solid_geometry = generate_envelope(offset, 1, envelope_iso_type=self.iso_type,
  700. follow=follow)
  701. else:
  702. geo_obj.solid_geometry = generate_envelope(offset, 0, envelope_iso_type=self.iso_type,
  703. follow=follow)
  704. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  705. # or just looking in the lists (they are one level depth) and if any is not empty
  706. # proceed with object creation, if there are empty and the number of them is the length
  707. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  708. empty_cnt = 0
  709. if not isinstance(geo_obj.solid_geometry, list):
  710. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  711. for g in geo_obj.solid_geometry:
  712. if g:
  713. app_obj.inform.emit("[success]Isolation geometry created: %s" % geo_obj.options["name"])
  714. break
  715. else:
  716. empty_cnt += 1
  717. if empty_cnt == len(geo_obj.solid_geometry):
  718. raise ValidationError("Empty Geometry", None)
  719. geo_obj.multigeo = False
  720. # TODO: Do something if this is None. Offer changing name?
  721. self.app.new_object("geometry", iso_name, iso_init)
  722. def on_plot_cb_click(self, *args):
  723. if self.muted_ui:
  724. return
  725. self.read_form_item('plot')
  726. def on_solid_cb_click(self, *args):
  727. if self.muted_ui:
  728. return
  729. self.read_form_item('solid')
  730. self.plot()
  731. def on_multicolored_cb_click(self, *args):
  732. if self.muted_ui:
  733. return
  734. self.read_form_item('multicolored')
  735. self.plot()
  736. def on_follow_cb_click(self):
  737. if self.muted_ui:
  738. return
  739. self.plot()
  740. def on_aperture_table_visibility_change(self):
  741. if self.ui.aperture_table_visibility_cb.isChecked():
  742. self.ui.apertures_table.setVisible(True)
  743. else:
  744. self.ui.apertures_table.setVisible(False)
  745. def convert_units(self, units):
  746. """
  747. Converts the units of the object by scaling dimensions in all geometry
  748. and options.
  749. :param units: Units to which to convert the object: "IN" or "MM".
  750. :type units: str
  751. :return: None
  752. :rtype: None
  753. """
  754. factor = Gerber.convert_units(self, units)
  755. self.options['isotooldia'] = float(self.options['isotooldia']) * factor
  756. self.options['bboxmargin'] = float(self.options['bboxmargin']) * factor
  757. def plot(self, **kwargs):
  758. """
  759. :param kwargs: color and face_color
  760. :return:
  761. """
  762. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  763. # Does all the required setup and returns False
  764. # if the 'ptint' option is set to False.
  765. if not FlatCAMObj.plot(self):
  766. return
  767. if 'color' in kwargs:
  768. color = kwargs['color']
  769. else:
  770. color = self.app.defaults['global_plot_line']
  771. if 'face_color' in kwargs:
  772. face_color = kwargs['face_color']
  773. else:
  774. face_color = self.app.defaults['global_plot_fill']
  775. # if the Follow Geometry checkbox is checked then plot only the follow geometry
  776. if self.ui.follow_cb.get_value():
  777. geometry = self.follow_geometry
  778. else:
  779. geometry = self.solid_geometry
  780. # Make sure geometry is iterable.
  781. try:
  782. _ = iter(geometry)
  783. except TypeError:
  784. geometry = [geometry]
  785. def random_color():
  786. color = np.random.rand(4)
  787. color[3] = 1
  788. return color
  789. try:
  790. if self.options["solid"]:
  791. for g in geometry:
  792. if type(g) == Polygon or type(g) == LineString:
  793. self.add_shape(shape=g, color=color,
  794. face_color=random_color() if self.options['multicolored']
  795. else face_color, visible=self.options['plot'])
  796. elif type(g) == Point:
  797. pass
  798. else:
  799. for el in g:
  800. self.add_shape(shape=el, color=color,
  801. face_color=random_color() if self.options['multicolored']
  802. else face_color, visible=self.options['plot'])
  803. else:
  804. for g in geometry:
  805. if type(g) == Polygon or type(g) == LineString:
  806. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  807. visible=self.options['plot'])
  808. elif type(g) == Point:
  809. pass
  810. else:
  811. for el in g:
  812. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  813. visible=self.options['plot'])
  814. self.shapes.redraw()
  815. except (ObjectDeleted, AttributeError):
  816. self.shapes.clear(update=True)
  817. # experimental plot() when the solid_geometry is stored in the self.apertures
  818. # def plot_apertures(self, **kwargs):
  819. # """
  820. #
  821. # :param kwargs: color and face_color
  822. # :return:
  823. # """
  824. #
  825. # FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  826. #
  827. # # Does all the required setup and returns False
  828. # # if the 'ptint' option is set to False.
  829. # if not FlatCAMObj.plot(self):
  830. # return
  831. #
  832. # if 'color' in kwargs:
  833. # color = kwargs['color']
  834. # else:
  835. # color = self.app.defaults['global_plot_line']
  836. # if 'face_color' in kwargs:
  837. # face_color = kwargs['face_color']
  838. # else:
  839. # face_color = self.app.defaults['global_plot_fill']
  840. #
  841. # geometry = {}
  842. # for ap in self.apertures:
  843. # geometry[ap] = self.apertures[ap]['solid_geometry']
  844. # try:
  845. # _ = iter(geometry[ap])
  846. # except TypeError:
  847. # geometry[ap] = [geometry[ap]]
  848. #
  849. # def random_color():
  850. # color = np.random.rand(4)
  851. # color[3] = 1
  852. # return color
  853. #
  854. # try:
  855. # if self.options["solid"]:
  856. # for geo in geometry:
  857. # for g in geometry[geo]:
  858. # if type(g) == Polygon or type(g) == LineString:
  859. # self.add_shape(shape=g, color=color,
  860. # face_color=random_color() if self.options['multicolored']
  861. # else face_color, visible=self.options['plot'])
  862. # else:
  863. # for el in g:
  864. # self.add_shape(shape=el, color=color,
  865. # face_color=random_color() if self.options['multicolored']
  866. # else face_color, visible=self.options['plot'])
  867. # else:
  868. # for geo in geometry:
  869. # for g in geometry[geo]:
  870. # if type(g) == Polygon or type(g) == LineString:
  871. # self.add_shape(shape=g,
  872. # color=random_color() if self.options['multicolored'] else 'black',
  873. # visible=self.options['plot'])
  874. # else:
  875. # for el in g:
  876. # self.add_shape(shape=el,
  877. # color=random_color() if self.options['multicolored'] else 'black',
  878. # visible=self.options['plot'])
  879. # self.shapes.redraw()
  880. # except (ObjectDeleted, AttributeError):
  881. # self.shapes.clear(update=True)
  882. def serialize(self):
  883. return {
  884. "options": self.options,
  885. "kind": self.kind
  886. }
  887. class FlatCAMExcellon(FlatCAMObj, Excellon):
  888. """
  889. Represents Excellon/Drill code.
  890. """
  891. ui_type = ExcellonObjectUI
  892. optionChanged = QtCore.pyqtSignal(str)
  893. def __init__(self, name):
  894. Excellon.__init__(self, geo_steps_per_circle=int(self.app.defaults["geometry_circle_steps"]))
  895. FlatCAMObj.__init__(self, name)
  896. self.kind = "excellon"
  897. self.options.update({
  898. "plot": True,
  899. "solid": False,
  900. "drillz": -0.1,
  901. "travelz": 0.1,
  902. "feedrate": 5.0,
  903. "feedrate_rapid": 5.0,
  904. "tooldia": 0.1,
  905. "slot_tooldia": 0.1,
  906. "toolchange": False,
  907. "toolchangez": 1.0,
  908. "toolchangexy": "0.0, 0.0",
  909. "endz": 2.0,
  910. "startz": None,
  911. "spindlespeed": None,
  912. "dwell": True,
  913. "dwelltime": 1000,
  914. "ppname_e": 'defaults',
  915. "z_pdepth": -0.02,
  916. "feedrate_probe": 3.0,
  917. "optimization_type": "R",
  918. "gcode_type": "drills"
  919. })
  920. # TODO: Document this.
  921. self.tool_cbs = {}
  922. # dict to hold the tool number as key and tool offset as value
  923. self.tool_offset ={}
  924. # variable to store the total amount of drills per job
  925. self.tot_drill_cnt = 0
  926. self.tool_row = 0
  927. # variable to store the total amount of slots per job
  928. self.tot_slot_cnt = 0
  929. self.tool_row_slots = 0
  930. # variable to store the distance travelled
  931. self.travel_distance = 0.0
  932. # store the source file here
  933. self.source_file = ""
  934. self.multigeo = True
  935. # Attributes to be included in serialization
  936. # Always append to it because it carries contents
  937. # from predecessors.
  938. self.ser_attrs += ['options', 'kind']
  939. @staticmethod
  940. def merge(exc_list, exc_final):
  941. """
  942. Merge Excellon objects found in exc_list parameter into exc_final object.
  943. Options are always copied from source .
  944. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  945. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  946. tool_name to be used in the final Excellon object, exc_final.
  947. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  948. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  949. :param exc_final: Destination FlatCAMExcellon object.
  950. :return: None
  951. """
  952. # flag to signal that we need to reorder the tools dictionary and drills and slots lists
  953. flag_order = False
  954. try:
  955. flattened_list = list(itertools.chain(*exc_list))
  956. except TypeError:
  957. flattened_list = exc_list
  958. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  959. # values will be list of Shapely Points; for drills
  960. custom_dict_drills = {}
  961. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  962. # values will be list of Shapely Points; for slots
  963. custom_dict_slots = {}
  964. for exc in flattened_list:
  965. # copy options of the current excellon obj to the final excellon obj
  966. for option in exc.options:
  967. if option is not 'name':
  968. try:
  969. exc_final.options[option] = exc.options[option]
  970. except:
  971. exc.app.log.warning("Failed to copy option.", option)
  972. for drill in exc.drills:
  973. exc_tool_dia = float('%.3f' % exc.tools[drill['tool']]['C'])
  974. if exc_tool_dia not in custom_dict_drills:
  975. custom_dict_drills[exc_tool_dia] = [drill['point']]
  976. else:
  977. custom_dict_drills[exc_tool_dia].append(drill['point'])
  978. for slot in exc.slots:
  979. exc_tool_dia = float('%.3f' % exc.tools[slot['tool']]['C'])
  980. if exc_tool_dia not in custom_dict_slots:
  981. custom_dict_slots[exc_tool_dia] = [[slot['start'], slot['stop']]]
  982. else:
  983. custom_dict_slots[exc_tool_dia].append([slot['start'], slot['stop']])
  984. # add the zeros and units to the exc_final object
  985. exc_final.zeros = exc.zeros
  986. exc_final.units = exc.units
  987. # variable to make tool_name for the tools
  988. current_tool = 0
  989. # Here we add data to the exc_final object
  990. # the tools diameter are now the keys in the drill_dia dict and the values are the Shapely Points in case of
  991. # drills
  992. for tool_dia in custom_dict_drills:
  993. # we create a tool name for each key in the drill_dia dict (the key is a unique drill diameter)
  994. current_tool += 1
  995. tool_name = str(current_tool)
  996. spec = {"C": float(tool_dia)}
  997. exc_final.tools[tool_name] = spec
  998. # rebuild the drills list of dict's that belong to the exc_final object
  999. for point in custom_dict_drills[tool_dia]:
  1000. exc_final.drills.append(
  1001. {
  1002. "point": point,
  1003. "tool": str(current_tool)
  1004. }
  1005. )
  1006. # Here we add data to the exc_final object
  1007. # the tools diameter are now the keys in the drill_dia dict and the values are a list ([start, stop])
  1008. # of two Shapely Points in case of slots
  1009. for tool_dia in custom_dict_slots:
  1010. # we create a tool name for each key in the slot_dia dict (the key is a unique slot diameter)
  1011. # but only if there are no drills
  1012. if not exc_final.tools:
  1013. current_tool += 1
  1014. tool_name = str(current_tool)
  1015. spec = {"C": float(tool_dia)}
  1016. exc_final.tools[tool_name] = spec
  1017. else:
  1018. dia_list = []
  1019. for v in exc_final.tools.values():
  1020. dia_list.append(float(v["C"]))
  1021. if tool_dia not in dia_list:
  1022. flag_order = True
  1023. current_tool = len(dia_list) + 1
  1024. tool_name = str(current_tool)
  1025. spec = {"C": float(tool_dia)}
  1026. exc_final.tools[tool_name] = spec
  1027. else:
  1028. for k, v in exc_final.tools.items():
  1029. if v["C"] == tool_dia:
  1030. current_tool = int(k)
  1031. break
  1032. # rebuild the slots list of dict's that belong to the exc_final object
  1033. for point in custom_dict_slots[tool_dia]:
  1034. exc_final.slots.append(
  1035. {
  1036. "start": point[0],
  1037. "stop": point[1],
  1038. "tool": str(current_tool)
  1039. }
  1040. )
  1041. # flag_order == True means that there was an slot diameter not in the tools and we also have drills
  1042. # and the new tool was added to self.tools therefore we need to reorder the tools and drills and slots
  1043. current_tool = 0
  1044. if flag_order is True:
  1045. dia_list = []
  1046. temp_drills = []
  1047. temp_slots = []
  1048. temp_tools = {}
  1049. for v in exc_final.tools.values():
  1050. dia_list.append(float(v["C"]))
  1051. dia_list.sort()
  1052. for ordered_dia in dia_list:
  1053. current_tool += 1
  1054. tool_name_temp = str(current_tool)
  1055. spec_temp = {"C": float(ordered_dia)}
  1056. temp_tools[tool_name_temp] = spec_temp
  1057. for drill in exc_final.drills:
  1058. exc_tool_dia = float('%.3f' % exc_final.tools[drill['tool']]['C'])
  1059. if exc_tool_dia == ordered_dia:
  1060. temp_drills.append(
  1061. {
  1062. "point": drill["point"],
  1063. "tool": str(current_tool)
  1064. }
  1065. )
  1066. for slot in exc_final.slots:
  1067. slot_tool_dia = float('%.3f' % exc_final.tools[slot['tool']]['C'])
  1068. if slot_tool_dia == ordered_dia:
  1069. temp_slots.append(
  1070. {
  1071. "start": slot["start"],
  1072. "stop": slot["stop"],
  1073. "tool": str(current_tool)
  1074. }
  1075. )
  1076. # delete the exc_final tools, drills and slots
  1077. exc_final.tools = dict()
  1078. exc_final.drills[:] = []
  1079. exc_final.slots[:] = []
  1080. # update the exc_final tools, drills and slots with the ordered values
  1081. exc_final.tools = temp_tools
  1082. exc_final.drills[:] = temp_drills
  1083. exc_final.slots[:] = temp_slots
  1084. # create the geometry for the exc_final object
  1085. exc_final.create_geometry()
  1086. def build_ui(self):
  1087. FlatCAMObj.build_ui(self)
  1088. try:
  1089. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1090. self.ui.tools_table.itemChanged.disconnect()
  1091. except:
  1092. pass
  1093. n = len(self.tools)
  1094. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  1095. self.ui.tools_table.setRowCount(n + 2)
  1096. self.tot_drill_cnt = 0
  1097. self.tot_slot_cnt = 0
  1098. self.tool_row = 0
  1099. sort = []
  1100. for k, v in list(self.tools.items()):
  1101. sort.append((k, v.get('C')))
  1102. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1103. tools = [i[0] for i in sorted_tools]
  1104. for tool_no in tools:
  1105. drill_cnt = 0 # variable to store the nr of drills per tool
  1106. slot_cnt = 0 # variable to store the nr of slots per tool
  1107. # Find no of drills for the current tool
  1108. for drill in self.drills:
  1109. if drill['tool'] == tool_no:
  1110. drill_cnt += 1
  1111. self.tot_drill_cnt += drill_cnt
  1112. # Find no of slots for the current tool
  1113. for slot in self.slots:
  1114. if slot['tool'] == tool_no:
  1115. slot_cnt += 1
  1116. self.tot_slot_cnt += slot_cnt
  1117. id = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  1118. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1119. self.ui.tools_table.setItem(self.tool_row, 0, id) # Tool name/id
  1120. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  1121. # There are no drill bits in MM with more than 3 decimals diameter
  1122. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  1123. if self.units == 'MM':
  1124. dia = QtWidgets.QTableWidgetItem('%.2f' % (self.tools[tool_no]['C']))
  1125. else:
  1126. dia = QtWidgets.QTableWidgetItem('%.3f' % (self.tools[tool_no]['C']))
  1127. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  1128. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  1129. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1130. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  1131. if slot_cnt > 0:
  1132. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  1133. else:
  1134. slot_count = QtWidgets.QTableWidgetItem('')
  1135. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1136. try:
  1137. if self.units == 'MM':
  1138. t_offset = self.tool_offset[float('%.2f' % float(self.tools[tool_no]['C']))]
  1139. else:
  1140. t_offset = self.tool_offset[float('%.3f' % float(self.tools[tool_no]['C']))]
  1141. except KeyError:
  1142. t_offset = self.app.defaults['excellon_offset']
  1143. tool_offset_item = QtWidgets.QTableWidgetItem('%s' % str(t_offset))
  1144. plot_item = FCCheckBox()
  1145. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  1146. if self.ui.plot_cb.isChecked():
  1147. plot_item.setChecked(True)
  1148. self.ui.tools_table.setItem(self.tool_row, 1, dia) # Diameter
  1149. self.ui.tools_table.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  1150. self.ui.tools_table.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  1151. self.ui.tools_table.setItem(self.tool_row, 4, tool_offset_item) # Tool offset
  1152. self.ui.tools_table.setCellWidget(self.tool_row, 5, plot_item)
  1153. self.tool_row += 1
  1154. # add a last row with the Total number of drills
  1155. empty = QtWidgets.QTableWidgetItem('')
  1156. empty.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1157. empty_1 = QtWidgets.QTableWidgetItem('')
  1158. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1159. label_tot_drill_count = QtWidgets.QTableWidgetItem('Total Drills')
  1160. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  1161. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1162. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1163. self.ui.tools_table.setItem(self.tool_row, 0, empty)
  1164. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  1165. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  1166. self.ui.tools_table.setItem(self.tool_row, 3, empty_1) # Total number of drills
  1167. font = QtGui.QFont()
  1168. font.setBold(True)
  1169. font.setWeight(75)
  1170. for k in [1, 2]:
  1171. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  1172. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  1173. self.tool_row += 1
  1174. # add a last row with the Total number of slots
  1175. empty_2 = QtWidgets.QTableWidgetItem('')
  1176. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1177. empty_3 = QtWidgets.QTableWidgetItem('')
  1178. empty_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1179. label_tot_slot_count = QtWidgets.QTableWidgetItem('Total Slots')
  1180. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  1181. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1182. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1183. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  1184. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  1185. self.ui.tools_table.setItem(self.tool_row, 2, empty_3)
  1186. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  1187. for kl in [1, 2, 3]:
  1188. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  1189. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  1190. # sort the tool diameter column
  1191. # self.ui.tools_table.sortItems(1)
  1192. # all the tools are selected by default
  1193. self.ui.tools_table.selectColumn(0)
  1194. #
  1195. self.ui.tools_table.resizeColumnsToContents()
  1196. self.ui.tools_table.resizeRowsToContents()
  1197. vertical_header = self.ui.tools_table.verticalHeader()
  1198. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1199. vertical_header.hide()
  1200. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1201. horizontal_header = self.ui.tools_table.horizontalHeader()
  1202. horizontal_header.setMinimumSectionSize(10)
  1203. horizontal_header.setDefaultSectionSize(70)
  1204. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  1205. horizontal_header.resizeSection(0, 20)
  1206. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1207. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1208. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1209. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
  1210. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  1211. horizontal_header.resizeSection(5, 17)
  1212. self.ui.tools_table.setColumnWidth(5, 17)
  1213. # horizontal_header.setStretchLastSection(True)
  1214. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  1215. # horizontal_header.setStretchLastSection(True)
  1216. self.ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1217. self.ui.tools_table.setSortingEnabled(False)
  1218. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  1219. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  1220. if not self.drills:
  1221. self.ui.tdlabel.hide()
  1222. self.ui.tooldia_entry.hide()
  1223. self.ui.generate_milling_button.hide()
  1224. else:
  1225. self.ui.tdlabel.show()
  1226. self.ui.tooldia_entry.show()
  1227. self.ui.generate_milling_button.show()
  1228. if not self.slots:
  1229. self.ui.stdlabel.hide()
  1230. self.ui.slot_tooldia_entry.hide()
  1231. self.ui.generate_milling_slots_button.hide()
  1232. else:
  1233. self.ui.stdlabel.show()
  1234. self.ui.slot_tooldia_entry.show()
  1235. self.ui.generate_milling_slots_button.show()
  1236. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1237. self.ui.tools_table.itemChanged.connect(self.on_tool_offset_edit)
  1238. self.ui_connect()
  1239. def set_ui(self, ui):
  1240. """
  1241. Configures the user interface for this object.
  1242. Connects options to form fields.
  1243. :param ui: User interface object.
  1244. :type ui: ExcellonObjectUI
  1245. :return: None
  1246. """
  1247. FlatCAMObj.set_ui(self, ui)
  1248. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  1249. self.form_fields.update({
  1250. "plot": self.ui.plot_cb,
  1251. "solid": self.ui.solid_cb,
  1252. "drillz": self.ui.cutz_entry,
  1253. "travelz": self.ui.travelz_entry,
  1254. "feedrate": self.ui.feedrate_entry,
  1255. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  1256. "tooldia": self.ui.tooldia_entry,
  1257. "slot_tooldia": self.ui.slot_tooldia_entry,
  1258. "toolchange": self.ui.toolchange_cb,
  1259. "toolchangez": self.ui.toolchangez_entry,
  1260. "spindlespeed": self.ui.spindlespeed_entry,
  1261. "dwell": self.ui.dwell_cb,
  1262. "dwelltime": self.ui.dwelltime_entry,
  1263. "startz": self.ui.estartz_entry,
  1264. "endz": self.ui.eendz_entry,
  1265. "ppname_e": self.ui.pp_excellon_name_cb,
  1266. "z_pdepth": self.ui.pdepth_entry,
  1267. "feedrate_probe": self.ui.feedrate_probe_entry,
  1268. "gcode_type": self.ui.excellon_gcode_type_radio
  1269. })
  1270. for name in list(self.app.postprocessors.keys()):
  1271. # the HPGL postprocessor is only for Geometry not for Excellon job therefore don't add it
  1272. if name == 'hpgl':
  1273. continue
  1274. self.ui.pp_excellon_name_cb.addItem(name)
  1275. # Fill form fields
  1276. self.to_form()
  1277. # initialize the dict that holds the tools offset
  1278. t_default_offset = self.app.defaults["excellon_offset"]
  1279. if not self.tool_offset:
  1280. for value in self.tools.values():
  1281. if self.units == 'MM':
  1282. dia = float('%.2f' % float(value['C']))
  1283. else:
  1284. dia = float('%.3f' % float(value['C']))
  1285. self.tool_offset[dia] = t_default_offset
  1286. # Show/Hide Advanced Options
  1287. if self.app.defaults["global_app_level"] == 'b':
  1288. self.ui.level.setText('<span style="color:green;"><b>Basic</b></span>')
  1289. self.ui.tools_table.setColumnHidden(4, True)
  1290. self.ui.estartz_label.hide()
  1291. self.ui.estartz_entry.hide()
  1292. self.ui.eendz_label.hide()
  1293. self.ui.eendz_entry.hide()
  1294. self.ui.feedrate_rapid_label.hide()
  1295. self.ui.feedrate_rapid_entry.hide()
  1296. self.ui.pdepth_label.hide()
  1297. self.ui.pdepth_entry.hide()
  1298. self.ui.feedrate_probe_label.hide()
  1299. self.ui.feedrate_probe_entry.hide()
  1300. else:
  1301. self.ui.level.setText('<span style="color:red;"><b>Advanced</b></span>')
  1302. assert isinstance(self.ui, ExcellonObjectUI), \
  1303. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  1304. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1305. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  1306. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  1307. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  1308. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  1309. self.ui.pp_excellon_name_cb.activated.connect(self.on_pp_changed)
  1310. def ui_connect(self):
  1311. for row in range(self.ui.tools_table.rowCount() - 2):
  1312. self.ui.tools_table.cellWidget(row, 5).clicked.connect(self.on_plot_cb_click_table)
  1313. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1314. def ui_disconnect(self):
  1315. for row in range(self.ui.tools_table.rowCount()):
  1316. try:
  1317. self.ui.tools_table.cellWidget(row, 5).clicked.disconnect()
  1318. except:
  1319. pass
  1320. try:
  1321. self.ui.plot_cb.stateChanged.disconnect()
  1322. except:
  1323. pass
  1324. def on_tool_offset_edit(self):
  1325. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1326. self.ui.tools_table.itemChanged.disconnect()
  1327. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  1328. self.is_modified = True
  1329. row_of_item_changed = self.ui.tools_table.currentRow()
  1330. if self.units == 'MM':
  1331. dia = float('%.2f' % float(self.ui.tools_table.item(row_of_item_changed, 1).text()))
  1332. else:
  1333. dia = float('%.3f' % float(self.ui.tools_table.item(row_of_item_changed, 1).text()))
  1334. current_table_offset_edited = None
  1335. if self.ui.tools_table.currentItem() is not None:
  1336. try:
  1337. current_table_offset_edited = float(self.ui.tools_table.currentItem().text())
  1338. except ValueError:
  1339. # try to convert comma to decimal point. if it's still not working error message and return
  1340. try:
  1341. current_table_offset_edited = float(self.ui.tools_table.currentItem().text().replace(',', '.'))
  1342. self.ui.tools_table.currentItem().setText(
  1343. self.ui.tools_table.currentItem().text().replace(',', '.'))
  1344. except ValueError:
  1345. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  1346. "use a number.")
  1347. self.ui.tools_table.currentItem().setText(str(self.tool_offset[dia]))
  1348. return
  1349. self.tool_offset[dia] = current_table_offset_edited
  1350. # we reactivate the signals after the after the tool editing
  1351. self.ui.tools_table.itemChanged.connect(self.on_tool_offset_edit)
  1352. def get_selected_tools_list(self):
  1353. """
  1354. Returns the keys to the self.tools dictionary corresponding
  1355. to the selections on the tool list in the GUI.
  1356. :return: List of tools.
  1357. :rtype: list
  1358. """
  1359. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  1360. def get_selected_tools_table_items(self):
  1361. """
  1362. Returns a list of lists, each list in the list is made out of row elements
  1363. :return: List of table_tools items.
  1364. :rtype: list
  1365. """
  1366. table_tools_items = []
  1367. for x in self.ui.tools_table.selectedItems():
  1368. # from the columnCount we subtract a value of 1 which represent the last column (plot column)
  1369. # which does not have text
  1370. table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  1371. for column in range(0, self.ui.tools_table.columnCount() - 1)])
  1372. for item in table_tools_items:
  1373. item[0] = str(item[0])
  1374. return table_tools_items
  1375. def export_excellon(self, whole, fract, e_zeros=None, form='dec', factor=1):
  1376. """
  1377. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  1378. :return: has_slots and Excellon_code
  1379. """
  1380. excellon_code = ''
  1381. # store here if the file has slots, return 1 if any slots, 0 if only drills
  1382. has_slots = 0
  1383. # drills processing
  1384. try:
  1385. if self.drills:
  1386. length = whole + fract
  1387. for tool in self.tools:
  1388. excellon_code += 'T0%s\n' % str(tool) if int(tool) < 10 else 'T%s\n' % str(tool)
  1389. for drill in self.drills:
  1390. if form == 'dec' and tool == drill['tool']:
  1391. drill_x = drill['point'].x * factor
  1392. drill_y = drill['point'].y * factor
  1393. excellon_code += "X{:.{dec}f}Y{:.{dec}f}\n".format(drill_x, drill_y, dec=fract)
  1394. elif e_zeros == 'LZ' and tool == drill['tool']:
  1395. drill_x = drill['point'].x * factor
  1396. drill_y = drill['point'].y * factor
  1397. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract)
  1398. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract)
  1399. # extract whole part and decimal part
  1400. exc_x_formatted = exc_x_formatted.partition('.')
  1401. exc_y_formatted = exc_y_formatted.partition('.')
  1402. # left padd the 'whole' part with zeros
  1403. x_whole = exc_x_formatted[0].rjust(whole, '0')
  1404. y_whole = exc_y_formatted[0].rjust(whole, '0')
  1405. # restore the coordinate padded in the left with 0 and added the decimal part
  1406. # without the decinal dot
  1407. exc_x_formatted = x_whole + exc_x_formatted[2]
  1408. exc_y_formatted = y_whole + exc_y_formatted[2]
  1409. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  1410. yform=exc_y_formatted)
  1411. elif tool == drill['tool']:
  1412. drill_x = drill['point'].x * factor
  1413. drill_y = drill['point'].y * factor
  1414. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract).replace('.', '')
  1415. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract).replace('.', '')
  1416. # pad with rear zeros
  1417. exc_x_formatted.ljust(length, '0')
  1418. exc_y_formatted.ljust(length, '0')
  1419. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  1420. yform=exc_y_formatted)
  1421. except Exception as e:
  1422. log.debug(str(e))
  1423. # slots processing
  1424. try:
  1425. if self.slots:
  1426. has_slots = 1
  1427. for tool in self.tools:
  1428. if int(tool) < 10:
  1429. excellon_code += 'T0' + str(tool) + '\n'
  1430. else:
  1431. excellon_code += 'T' + str(tool) + '\n'
  1432. for slot in self.slots:
  1433. if form == 'dec' and tool == slot['tool']:
  1434. start_slot_x = slot['start'].x * factor
  1435. start_slot_y = slot['start'].y * factor
  1436. stop_slot_x = slot['stop'].x * factor
  1437. stop_slot_y = slot['stop'].y * factor
  1438. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM15\n".format(start_slot_x,
  1439. start_slot_y,
  1440. dec=fract)
  1441. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM16\n".format(stop_slot_x,
  1442. stop_slot_y,
  1443. dec=fract)
  1444. elif e_zeros == 'LZ' and tool == slot['tool']:
  1445. start_slot_x = slot['start'].x * factor
  1446. start_slot_y = slot['start'].y * factor
  1447. stop_slot_x = slot['stop'].x * factor
  1448. stop_slot_y = slot['stop'].y * factor
  1449. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  1450. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  1451. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  1452. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  1453. # extract whole part and decimal part
  1454. start_slot_x_formatted = start_slot_x_formatted.partition('.')
  1455. start_slot_y_formatted = start_slot_y_formatted.partition('.')
  1456. stop_slot_x_formatted = stop_slot_x_formatted.partition('.')
  1457. stop_slot_y_formatted = stop_slot_y_formatted.partition('.')
  1458. # left padd the 'whole' part with zeros
  1459. start_x_whole = start_slot_x_formatted[0].rjust(whole, '0')
  1460. start_y_whole = start_slot_y_formatted[0].rjust(whole, '0')
  1461. stop_x_whole = stop_slot_x_formatted[0].rjust(whole, '0')
  1462. stop_y_whole = stop_slot_y_formatted[0].rjust(whole, '0')
  1463. # restore the coordinate padded in the left with 0 and added the decimal part
  1464. # without the decinal dot
  1465. start_slot_x_formatted = start_x_whole + start_slot_x_formatted[2]
  1466. start_slot_y_formatted = start_y_whole + start_slot_y_formatted[2]
  1467. stop_slot_x_formatted = stop_x_whole + stop_slot_x_formatted[2]
  1468. stop_slot_y_formatted = stop_y_whole + stop_slot_y_formatted[2]
  1469. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  1470. ystart=start_slot_y_formatted)
  1471. excellon_code += "G00X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  1472. ystop=stop_slot_y_formatted)
  1473. elif tool == slot['tool']:
  1474. start_slot_x = slot['start'].x * factor
  1475. start_slot_y = slot['start'].y * factor
  1476. stop_slot_x = slot['stop'].x * factor
  1477. stop_slot_y = slot['stop'].y * factor
  1478. length = whole + fract
  1479. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  1480. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  1481. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  1482. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  1483. # pad with rear zeros
  1484. start_slot_x_formatted.ljust(length, '0')
  1485. start_slot_y_formatted.ljust(length, '0')
  1486. stop_slot_x_formatted.ljust(length, '0')
  1487. stop_slot_y_formatted.ljust(length, '0')
  1488. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  1489. ystart=start_slot_y_formatted)
  1490. excellon_code += "G00X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  1491. ystop=stop_slot_y_formatted)
  1492. except Exception as e:
  1493. log.debug(str(e))
  1494. if not self.drills and not self.slots:
  1495. log.debug("FlatCAMObj.FlatCAMExcellon.export_excellon() --> Excellon Object is empty: no drills, no slots.")
  1496. return 'fail'
  1497. return has_slots, excellon_code
  1498. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1499. """
  1500. Note: This method is a good template for generic operations as
  1501. it takes it's options from parameters or otherwise from the
  1502. object's options and returns a (success, msg) tuple as feedback
  1503. for shell operations.
  1504. :return: Success/failure condition tuple (bool, str).
  1505. :rtype: tuple
  1506. """
  1507. # Get the tools from the list. These are keys
  1508. # to self.tools
  1509. if tools is None:
  1510. tools = self.get_selected_tools_list()
  1511. if outname is None:
  1512. outname = self.options["name"] + "_mill"
  1513. if tooldia is None:
  1514. tooldia = float(self.options["tooldia"])
  1515. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1516. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1517. sort = []
  1518. for k, v in self.tools.items():
  1519. sort.append((k, v.get('C')))
  1520. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1521. if tools == "all":
  1522. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1523. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1524. if len(tools) == 0:
  1525. self.app.inform.emit("[ERROR_NOTCL]Please select one or more tools from the list and try again.")
  1526. return False, "Error: No tools."
  1527. for tool in tools:
  1528. if tooldia > self.tools[tool]["C"]:
  1529. self.app.inform.emit("[ERROR_NOTCL] Milling tool for DRILLS is larger than hole size. Cancelled.")
  1530. return False, "Error: Milling tool is larger than hole."
  1531. def geo_init(geo_obj, app_obj):
  1532. assert isinstance(geo_obj, FlatCAMGeometry), \
  1533. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1534. app_obj.progress.emit(20)
  1535. ### Add properties to the object
  1536. # get the tool_table items in a list of row items
  1537. tool_table_items = self.get_selected_tools_table_items()
  1538. # insert an information only element in the front
  1539. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1540. geo_obj.options['Tools_in_use'] = tool_table_items
  1541. geo_obj.options['type'] = 'Excellon Geometry'
  1542. geo_obj.solid_geometry = []
  1543. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1544. # for FlatCAM is 6 decimals,
  1545. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1546. for hole in self.drills:
  1547. if hole['tool'] in tools:
  1548. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  1549. if buffer_value == 0:
  1550. geo_obj.solid_geometry.append(
  1551. Point(hole['point']).buffer(0.0000001).exterior)
  1552. else:
  1553. geo_obj.solid_geometry.append(
  1554. Point(hole['point']).buffer(buffer_value).exterior)
  1555. if use_thread:
  1556. def geo_thread(app_obj):
  1557. app_obj.new_object("geometry", outname, geo_init)
  1558. app_obj.progress.emit(100)
  1559. # Create a promise with the new name
  1560. self.app.collection.promise(outname)
  1561. # Send to worker
  1562. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1563. else:
  1564. self.app.new_object("geometry", outname, geo_init)
  1565. return True, ""
  1566. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1567. """
  1568. Note: This method is a good template for generic operations as
  1569. it takes it's options from parameters or otherwise from the
  1570. object's options and returns a (success, msg) tuple as feedback
  1571. for shell operations.
  1572. :return: Success/failure condition tuple (bool, str).
  1573. :rtype: tuple
  1574. """
  1575. # Get the tools from the list. These are keys
  1576. # to self.tools
  1577. if tools is None:
  1578. tools = self.get_selected_tools_list()
  1579. if outname is None:
  1580. outname = self.options["name"] + "_mill"
  1581. if tooldia is None:
  1582. tooldia = float(self.options["slot_tooldia"])
  1583. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1584. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1585. sort = []
  1586. for k, v in self.tools.items():
  1587. sort.append((k, v.get('C')))
  1588. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1589. if tools == "all":
  1590. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1591. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1592. if len(tools) == 0:
  1593. self.app.inform.emit("[ERROR_NOTCL]Please select one or more tools from the list and try again.")
  1594. return False, "Error: No tools."
  1595. for tool in tools:
  1596. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  1597. adj_toolstable_tooldia = float('%.4f' % float(tooldia))
  1598. adj_file_tooldia = float('%.4f' % float(self.tools[tool]["C"]))
  1599. if adj_toolstable_tooldia > adj_file_tooldia + 0.0001:
  1600. self.app.inform.emit("[ERROR_NOTCL] Milling tool for SLOTS is larger than hole size. Cancelled.")
  1601. return False, "Error: Milling tool is larger than hole."
  1602. def geo_init(geo_obj, app_obj):
  1603. assert isinstance(geo_obj, FlatCAMGeometry), \
  1604. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1605. app_obj.progress.emit(20)
  1606. ### Add properties to the object
  1607. # get the tool_table items in a list of row items
  1608. tool_table_items = self.get_selected_tools_table_items()
  1609. # insert an information only element in the front
  1610. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1611. geo_obj.options['Tools_in_use'] = tool_table_items
  1612. geo_obj.options['type'] = 'Excellon Geometry'
  1613. geo_obj.solid_geometry = []
  1614. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1615. # for FlatCAM is 6 decimals,
  1616. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1617. for slot in self.slots:
  1618. if slot['tool'] in tools:
  1619. toolstable_tool = float('%.4f' % float(tooldia))
  1620. file_tool = float('%.4f' % float(self.tools[tool]["C"]))
  1621. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  1622. # for the file_tool (tooldia actually)
  1623. buffer_value = float(file_tool / 2) - float(toolstable_tool / 2) + 0.0001
  1624. if buffer_value == 0:
  1625. start = slot['start']
  1626. stop = slot['stop']
  1627. lines_string = LineString([start, stop])
  1628. poly = lines_string.buffer(0.0000001, int(self.geo_steps_per_circle)).exterior
  1629. geo_obj.solid_geometry.append(poly)
  1630. else:
  1631. start = slot['start']
  1632. stop = slot['stop']
  1633. lines_string = LineString([start, stop])
  1634. poly = lines_string.buffer(buffer_value, int(self.geo_steps_per_circle)).exterior
  1635. geo_obj.solid_geometry.append(poly)
  1636. if use_thread:
  1637. def geo_thread(app_obj):
  1638. app_obj.new_object("geometry", outname + '_slot', geo_init)
  1639. app_obj.progress.emit(100)
  1640. # Create a promise with the new name
  1641. self.app.collection.promise(outname)
  1642. # Send to worker
  1643. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1644. else:
  1645. self.app.new_object("geometry", outname + '_slot', geo_init)
  1646. return True, ""
  1647. def on_generate_milling_button_click(self, *args):
  1648. self.app.report_usage("excellon_on_create_milling_drills button")
  1649. self.read_form()
  1650. self.generate_milling_drills(use_thread=False)
  1651. def on_generate_milling_slots_button_click(self, *args):
  1652. self.app.report_usage("excellon_on_create_milling_slots_button")
  1653. self.read_form()
  1654. self.generate_milling_slots(use_thread=False)
  1655. def on_pp_changed(self):
  1656. current_pp = self.ui.pp_excellon_name_cb.get_value()
  1657. if "toolchange_probe" in current_pp.lower():
  1658. self.ui.pdepth_entry.setVisible(True)
  1659. self.ui.pdepth_label.show()
  1660. self.ui.feedrate_probe_entry.setVisible(True)
  1661. self.ui.feedrate_probe_label.show()
  1662. else:
  1663. self.ui.pdepth_entry.setVisible(False)
  1664. self.ui.pdepth_label.hide()
  1665. self.ui.feedrate_probe_entry.setVisible(False)
  1666. self.ui.feedrate_probe_label.hide()
  1667. def on_create_cncjob_button_click(self, *args):
  1668. self.app.report_usage("excellon_on_create_cncjob_button")
  1669. self.read_form()
  1670. # Get the tools from the list
  1671. tools = self.get_selected_tools_list()
  1672. if len(tools) == 0:
  1673. # if there is a single tool in the table (remember that the last 2 rows are for totals and do not count in
  1674. # tool number) it means that there are 3 rows (1 tool and 2 totals).
  1675. # in this case regardless of the selection status of that tool, use it.
  1676. if self.ui.tools_table.rowCount() == 3:
  1677. tools.append(self.ui.tools_table.item(0, 0).text())
  1678. else:
  1679. self.app.inform.emit("[ERROR_NOTCL]Please select one or more tools from the list and try again.")
  1680. return
  1681. xmin = self.options['xmin']
  1682. ymin = self.options['ymin']
  1683. xmax = self.options['xmax']
  1684. ymax = self.options['ymax']
  1685. job_name = self.options["name"] + "_cnc"
  1686. pp_excellon_name = self.options["ppname_e"]
  1687. # Object initialization function for app.new_object()
  1688. def job_init(job_obj, app_obj):
  1689. assert isinstance(job_obj, FlatCAMCNCjob), \
  1690. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  1691. # get the tool_table items in a list of row items
  1692. tool_table_items = self.get_selected_tools_table_items()
  1693. # insert an information only element in the front
  1694. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1695. ### Add properties to the object
  1696. job_obj.options['Tools_in_use'] = tool_table_items
  1697. job_obj.options['type'] = 'Excellon'
  1698. job_obj.options['ppname_e'] = pp_excellon_name
  1699. app_obj.progress.emit(20)
  1700. job_obj.z_cut = float(self.options["drillz"])
  1701. job_obj.tool_offset = self.tool_offset
  1702. job_obj.z_move = float(self.options["travelz"])
  1703. job_obj.feedrate = float(self.options["feedrate"])
  1704. job_obj.feedrate_rapid = float(self.options["feedrate_rapid"])
  1705. job_obj.spindlespeed = float(self.options["spindlespeed"]) if self.options["spindlespeed"] else None
  1706. job_obj.dwell = self.options["dwell"]
  1707. job_obj.dwelltime = float(self.options["dwelltime"])
  1708. job_obj.pp_excellon_name = pp_excellon_name
  1709. job_obj.toolchange_xy_type = "excellon"
  1710. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  1711. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  1712. job_obj.options['xmin'] = xmin
  1713. job_obj.options['ymin'] = ymin
  1714. job_obj.options['xmax'] = xmax
  1715. job_obj.options['ymax'] = ymax
  1716. try:
  1717. job_obj.z_pdepth = float(self.options["z_pdepth"])
  1718. except ValueError:
  1719. # try to convert comma to decimal point. if it's still not working error message and return
  1720. try:
  1721. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  1722. except ValueError:
  1723. self.app.inform.emit(
  1724. '[ERROR_NOTCL]Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]')
  1725. try:
  1726. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  1727. except ValueError:
  1728. # try to convert comma to decimal point. if it's still not working error message and return
  1729. try:
  1730. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  1731. except ValueError:
  1732. self.app.inform.emit(
  1733. '[ERROR_NOTCL]Wrong value format for self.defaults["feedrate_probe"] '
  1734. 'or self.options["feedrate_probe"]')
  1735. # There could be more than one drill size...
  1736. # job_obj.tooldia = # TODO: duplicate variable!
  1737. # job_obj.options["tooldia"] =
  1738. tools_csv = ','.join(tools)
  1739. ret_val = job_obj.generate_from_excellon_by_tool(self, tools_csv,
  1740. drillz=float(self.options['drillz']),
  1741. toolchange=float(self.options["toolchange"]),
  1742. toolchangexy=self.app.defaults["excellon_toolchangexy"],
  1743. toolchangez=float(self.options["toolchangez"]),
  1744. startz=float(self.options["startz"]) if
  1745. self.options["startz"] else None,
  1746. endz=float(self.options["endz"]),
  1747. excellon_optimization_type=self.app.defaults[
  1748. "excellon_optimization_type"])
  1749. if ret_val == 'fail':
  1750. return 'fail'
  1751. app_obj.progress.emit(50)
  1752. job_obj.gcode_parse()
  1753. app_obj.progress.emit(60)
  1754. job_obj.create_geometry()
  1755. app_obj.progress.emit(80)
  1756. # To be run in separate thread
  1757. def job_thread(app_obj):
  1758. with self.app.proc_container.new("Generating CNC Code"):
  1759. app_obj.new_object("cncjob", job_name, job_init)
  1760. app_obj.progress.emit(100)
  1761. # Create promise for the new name.
  1762. self.app.collection.promise(job_name)
  1763. # Send to worker
  1764. # self.app.worker.add_task(job_thread, [self.app])
  1765. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1766. def convert_units(self, units):
  1767. factor = Excellon.convert_units(self, units)
  1768. self.options['drillz'] = float(self.options['drillz']) * factor
  1769. self.options['travelz'] = float(self.options['travelz']) * factor
  1770. self.options['feedrate'] = float(self.options['feedrate']) * factor
  1771. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  1772. self.options['toolchangez'] = float(self.options['toolchangez']) * factor
  1773. if self.app.defaults["excellon_toolchangexy"] == '':
  1774. self.options['toolchangexy'] = "0.0, 0.0"
  1775. else:
  1776. coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  1777. if len(coords_xy) < 2:
  1778. self.app.inform.emit("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  1779. "in the format (x, y) \nbut now there is only one value, not two. ")
  1780. return 'fail'
  1781. coords_xy[0] *= factor
  1782. coords_xy[1] *= factor
  1783. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  1784. if self.options['startz'] is not None:
  1785. self.options['startz'] = float(self.options['startz']) * factor
  1786. self.options['endz'] = float(self.options['endz']) * factor
  1787. def on_solid_cb_click(self, *args):
  1788. if self.muted_ui:
  1789. return
  1790. self.read_form_item('solid')
  1791. self.plot()
  1792. def on_plot_cb_click(self, *args):
  1793. if self.muted_ui:
  1794. return
  1795. self.plot()
  1796. self.read_form_item('plot')
  1797. self.ui_disconnect()
  1798. cb_flag = self.ui.plot_cb.isChecked()
  1799. for row in range(self.ui.tools_table.rowCount() - 2):
  1800. table_cb = self.ui.tools_table.cellWidget(row, 5)
  1801. if cb_flag:
  1802. table_cb.setChecked(True)
  1803. else:
  1804. table_cb.setChecked(False)
  1805. self.ui_connect()
  1806. def on_plot_cb_click_table(self):
  1807. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  1808. self.ui_disconnect()
  1809. # cw = self.sender()
  1810. # cw_index = self.ui.tools_table.indexAt(cw.pos())
  1811. # cw_row = cw_index.row()
  1812. check_row = 0
  1813. self.shapes.clear(update=True)
  1814. for tool_key in self.tools:
  1815. solid_geometry = self.tools[tool_key]['solid_geometry']
  1816. # find the geo_tool_table row associated with the tool_key
  1817. for row in range(self.ui.tools_table.rowCount()):
  1818. tool_item = int(self.ui.tools_table.item(row, 0).text())
  1819. if tool_item == int(tool_key):
  1820. check_row = row
  1821. break
  1822. if self.ui.tools_table.cellWidget(check_row, 5).isChecked():
  1823. self.options['plot'] = True
  1824. # self.plot_element(element=solid_geometry, visible=True)
  1825. # Plot excellon (All polygons?)
  1826. if self.options["solid"]:
  1827. for geo in solid_geometry:
  1828. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  1829. visible=self.options['plot'],
  1830. layer=2)
  1831. else:
  1832. for geo in solid_geometry:
  1833. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1834. for ints in geo.interiors:
  1835. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1836. self.shapes.redraw()
  1837. # make sure that the general plot is disabled if one of the row plot's are disabled and
  1838. # if all the row plot's are enabled also enable the general plot checkbox
  1839. cb_cnt = 0
  1840. total_row = self.ui.tools_table.rowCount()
  1841. for row in range(total_row - 2):
  1842. if self.ui.tools_table.cellWidget(row, 5).isChecked():
  1843. cb_cnt += 1
  1844. else:
  1845. cb_cnt -= 1
  1846. if cb_cnt < total_row - 2:
  1847. self.ui.plot_cb.setChecked(False)
  1848. else:
  1849. self.ui.plot_cb.setChecked(True)
  1850. self.ui_connect()
  1851. # def plot_element(self, element, color='red', visible=None, layer=None):
  1852. #
  1853. # visible = visible if visible else self.options['plot']
  1854. #
  1855. # try:
  1856. # for sub_el in element:
  1857. # self.plot_element(sub_el)
  1858. #
  1859. # except TypeError: # Element is not iterable...
  1860. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  1861. def plot(self):
  1862. # Does all the required setup and returns False
  1863. # if the 'ptint' option is set to False.
  1864. if not FlatCAMObj.plot(self):
  1865. return
  1866. try:
  1867. # Plot excellon (All polygons?)
  1868. if self.options["solid"]:
  1869. for tool in self.tools:
  1870. for geo in self.tools[tool]['solid_geometry']:
  1871. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  1872. visible=self.options['plot'],
  1873. layer=2)
  1874. else:
  1875. for tool in self.tools:
  1876. for geo in self.tools[tool]['solid_geometry']:
  1877. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1878. for ints in geo.interiors:
  1879. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1880. self.shapes.redraw()
  1881. return
  1882. except (ObjectDeleted, AttributeError, KeyError):
  1883. self.shapes.clear(update=True)
  1884. # this stays for compatibility reasons, in case we try to open old projects
  1885. try:
  1886. _ = iter(self.solid_geometry)
  1887. except TypeError:
  1888. self.solid_geometry = [self.solid_geometry]
  1889. try:
  1890. # Plot excellon (All polygons?)
  1891. if self.options["solid"]:
  1892. for geo in self.solid_geometry:
  1893. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF', visible=self.options['plot'],
  1894. layer=2)
  1895. else:
  1896. for geo in self.solid_geometry:
  1897. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1898. for ints in geo.interiors:
  1899. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1900. self.shapes.redraw()
  1901. except (ObjectDeleted, AttributeError):
  1902. self.shapes.clear(update=True)
  1903. # try:
  1904. # # Plot excellon (All polygons?)
  1905. # if self.options["solid"]:
  1906. # for geo_type in self.solid_geometry:
  1907. # if geo_type is not None:
  1908. # if type(geo_type) is dict:
  1909. # for tooldia in geo_type:
  1910. # geo_list = geo_type[tooldia]
  1911. # for geo in geo_list:
  1912. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  1913. # visible=self.options['plot'],
  1914. # layer=2)
  1915. # else:
  1916. # self.add_shape(shape=geo_type, color='#750000BF', face_color='#C40000BF',
  1917. # visible=self.options['plot'],
  1918. # layer=2)
  1919. # else:
  1920. # for geo_type in self.solid_geometry:
  1921. # if geo_type is not None:
  1922. # if type(geo_type) is dict:
  1923. # for tooldia in geo_type:
  1924. # geo_list = geo_type[tooldia]
  1925. # for geo in geo_list:
  1926. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1927. # for ints in geo.interiors:
  1928. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1929. # else:
  1930. # self.add_shape(shape=geo_type.exterior, color='red', visible=self.options['plot'])
  1931. # for ints in geo_type.interiors:
  1932. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1933. # self.shapes.redraw()
  1934. # except (ObjectDeleted, AttributeError):
  1935. # self.shapes.clear(update=True)
  1936. class FlatCAMGeometry(FlatCAMObj, Geometry):
  1937. """
  1938. Geometric object not associated with a specific
  1939. format.
  1940. """
  1941. optionChanged = QtCore.pyqtSignal(str)
  1942. ui_type = GeometryObjectUI
  1943. @staticmethod
  1944. def merge(geo_list, geo_final, multigeo=None):
  1945. """
  1946. Merges the geometry of objects in grb_list into
  1947. the geometry of geo_final.
  1948. :param geo_list: List of FlatCAMGerber Objects to join.
  1949. :param geo_final: Destination FlatCAMGerber object.
  1950. :return: None
  1951. """
  1952. if geo_final.solid_geometry is None:
  1953. geo_final.solid_geometry = []
  1954. if type(geo_final.solid_geometry) is not list:
  1955. geo_final.solid_geometry = [geo_final.solid_geometry]
  1956. for geo in geo_list:
  1957. for option in geo.options:
  1958. if option is not 'name':
  1959. try:
  1960. geo_final.options[option] = geo.options[option]
  1961. except:
  1962. log.warning("Failed to copy option.", option)
  1963. # Expand lists
  1964. if type(geo) is list:
  1965. FlatCAMGeometry.merge(geo, geo_final)
  1966. # If not list, just append
  1967. else:
  1968. # merge solid_geometry, useful for singletool geometry, for multitool each is empty
  1969. if multigeo is None or multigeo == False:
  1970. geo_final.multigeo = False
  1971. try:
  1972. geo_final.solid_geometry.append(geo.solid_geometry)
  1973. except Exception as e:
  1974. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  1975. else:
  1976. geo_final.multigeo = True
  1977. # if multigeo the solid_geometry is empty in the object attributes because it now lives in the
  1978. # tools object attribute, as a key value
  1979. geo_final.solid_geometry = []
  1980. # find the tool_uid maximum value in the geo_final
  1981. geo_final_uid_list = []
  1982. for key in geo_final.tools:
  1983. geo_final_uid_list.append(int(key))
  1984. try:
  1985. max_uid = max(geo_final_uid_list, key=int)
  1986. except ValueError:
  1987. max_uid = 0
  1988. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  1989. # to merge the obj.tools as it is likely there is none to merge.
  1990. if not isinstance(geo, FlatCAMGerber) and not isinstance(geo, FlatCAMExcellon):
  1991. for tool_uid in geo.tools:
  1992. max_uid += 1
  1993. geo_final.tools[max_uid] = copy.deepcopy(geo.tools[tool_uid])
  1994. @staticmethod
  1995. def get_pts(o):
  1996. """
  1997. Returns a list of all points in the object, where
  1998. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  1999. of such. Search is done recursively.
  2000. :param: geometric object
  2001. :return: List of points
  2002. :rtype: list
  2003. """
  2004. pts = []
  2005. ## Iterable: descend into each item.
  2006. try:
  2007. for subo in o:
  2008. pts += FlatCAMGeometry.get_pts(subo)
  2009. ## Non-iterable
  2010. except TypeError:
  2011. if o is not None:
  2012. if type(o) == MultiPolygon:
  2013. for poly in o:
  2014. pts += FlatCAMGeometry.get_pts(poly)
  2015. ## Descend into .exerior and .interiors
  2016. elif type(o) == Polygon:
  2017. pts += FlatCAMGeometry.get_pts(o.exterior)
  2018. for i in o.interiors:
  2019. pts += FlatCAMGeometry.get_pts(i)
  2020. elif type(o) == MultiLineString:
  2021. for line in o:
  2022. pts += FlatCAMGeometry.get_pts(line)
  2023. ## Has .coords: list them.
  2024. else:
  2025. pts += list(o.coords)
  2026. else:
  2027. return
  2028. return pts
  2029. def __init__(self, name):
  2030. FlatCAMObj.__init__(self, name)
  2031. Geometry.__init__(self, geo_steps_per_circle=int(self.app.defaults["geometry_circle_steps"]))
  2032. self.kind = "geometry"
  2033. self.options.update({
  2034. "plot": True,
  2035. "cutz": -0.002,
  2036. "vtipdia": 0.1,
  2037. "vtipangle": 30,
  2038. "travelz": 0.1,
  2039. "feedrate": 5.0,
  2040. "feedrate_z": 5.0,
  2041. "feedrate_rapid": 5.0,
  2042. "spindlespeed": None,
  2043. "dwell": True,
  2044. "dwelltime": 1000,
  2045. "multidepth": False,
  2046. "depthperpass": 0.002,
  2047. "extracut": False,
  2048. "endz": 2.0,
  2049. "toolchange": False,
  2050. "toolchangez": 1.0,
  2051. "toolchangexy": "0.0, 0.0",
  2052. "startz": None,
  2053. "ppname_g": 'default',
  2054. "z_pdepth": -0.02,
  2055. "feedrate_probe": 3.0,
  2056. })
  2057. if "cnctooldia" not in self.options:
  2058. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  2059. self.options["startz"] = self.app.defaults["geometry_startz"]
  2060. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  2061. self.tooluid = 0
  2062. '''
  2063. self.tools = {}
  2064. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  2065. tool_id of the tools and the value is another dict that will hold the data under the following form:
  2066. {tooluid: {
  2067. 'tooldia': 1,
  2068. 'offset': 'Path',
  2069. 'offset_value': 0.0
  2070. 'type': 'Rough',
  2071. 'tool_type': 'C1',
  2072. 'data': self.default_tool_data
  2073. 'solid_geometry': []
  2074. }
  2075. }
  2076. '''
  2077. self.tools = {}
  2078. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  2079. # those elements are the ones used for generating GCode
  2080. self.sel_tools = {}
  2081. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  2082. self.type_item_options = ["Iso", "Rough", "Finish"]
  2083. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  2084. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  2085. self.v_tool_type = None
  2086. # flag to store if the Geometry is type 'multi-geometry' meaning that each tool has it's own geometry
  2087. # the default value is False
  2088. self.multigeo = False
  2089. # flag to store if the geometry is part of a special group of geometries that can't be processed by the default
  2090. # engine of FlatCAM. Most likely are generated by some of tools and are special cases of geometries.
  2091. self. special_group = None
  2092. # Attributes to be included in serialization
  2093. # Always append to it because it carries contents
  2094. # from predecessors.
  2095. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  2096. def build_ui(self):
  2097. self.ui_disconnect()
  2098. FlatCAMObj.build_ui(self)
  2099. offset = 0
  2100. tool_idx = 0
  2101. n = len(self.tools)
  2102. self.ui.geo_tools_table.setRowCount(n)
  2103. for tooluid_key, tooluid_value in self.tools.items():
  2104. tool_idx += 1
  2105. row_no = tool_idx - 1
  2106. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  2107. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2108. self.ui.geo_tools_table.setItem(row_no, 0, id) # Tool name/id
  2109. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  2110. # There are no tool bits in MM with more than 3 decimals diameter.
  2111. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  2112. if self.units == 'MM':
  2113. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(tooluid_value['tooldia']))
  2114. else:
  2115. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(tooluid_value['tooldia']))
  2116. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2117. offset_item = QtWidgets.QComboBox()
  2118. for item in self.offset_item_options:
  2119. offset_item.addItem(item)
  2120. offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  2121. idx = offset_item.findText(tooluid_value['offset'])
  2122. offset_item.setCurrentIndex(idx)
  2123. type_item = QtWidgets.QComboBox()
  2124. for item in self.type_item_options:
  2125. type_item.addItem(item)
  2126. type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2127. idx = type_item.findText(tooluid_value['type'])
  2128. type_item.setCurrentIndex(idx)
  2129. tool_type_item = QtWidgets.QComboBox()
  2130. for item in self.tool_type_item_options:
  2131. tool_type_item.addItem(item)
  2132. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2133. idx = tool_type_item.findText(tooluid_value['tool_type'])
  2134. tool_type_item.setCurrentIndex(idx)
  2135. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  2136. plot_item = FCCheckBox()
  2137. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  2138. if self.ui.plot_cb.isChecked():
  2139. plot_item.setChecked(True)
  2140. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  2141. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  2142. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  2143. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  2144. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  2145. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  2146. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  2147. try:
  2148. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  2149. except:
  2150. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools")
  2151. # make the diameter column editable
  2152. for row in range(tool_idx):
  2153. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  2154. QtCore.Qt.ItemIsEditable |
  2155. QtCore.Qt.ItemIsEnabled)
  2156. # sort the tool diameter column
  2157. # self.ui.geo_tools_table.sortItems(1)
  2158. # all the tools are selected by default
  2159. # self.ui.geo_tools_table.selectColumn(0)
  2160. self.ui.geo_tools_table.resizeColumnsToContents()
  2161. self.ui.geo_tools_table.resizeRowsToContents()
  2162. vertical_header = self.ui.geo_tools_table.verticalHeader()
  2163. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  2164. vertical_header.hide()
  2165. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2166. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  2167. horizontal_header.setMinimumSectionSize(10)
  2168. horizontal_header.setDefaultSectionSize(70)
  2169. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  2170. horizontal_header.resizeSection(0, 20)
  2171. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  2172. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  2173. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  2174. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  2175. horizontal_header.resizeSection(4, 40)
  2176. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  2177. horizontal_header.resizeSection(4, 17)
  2178. # horizontal_header.setStretchLastSection(True)
  2179. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2180. self.ui.geo_tools_table.setColumnWidth(0, 20)
  2181. self.ui.geo_tools_table.setColumnWidth(4, 40)
  2182. self.ui.geo_tools_table.setColumnWidth(6, 17)
  2183. # self.ui.geo_tools_table.setSortingEnabled(True)
  2184. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  2185. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  2186. # update UI for all rows - useful after units conversion but only if there is at least one row
  2187. row_cnt = self.ui.geo_tools_table.rowCount()
  2188. if row_cnt > 0:
  2189. for r in range(row_cnt):
  2190. self.update_ui(r)
  2191. # select only the first tool / row
  2192. selected_row = 0
  2193. try:
  2194. self.select_tools_table_row(selected_row, clearsel=True)
  2195. # update the Geometry UI
  2196. self.update_ui()
  2197. except Exception as e:
  2198. # when the tools table is empty there will be this error but once the table is populated it will go away
  2199. log.debug(str(e))
  2200. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  2201. # and can create some problems
  2202. if self.multigeo is False:
  2203. self.ui.geo_tools_table.setColumnHidden(6, True)
  2204. else:
  2205. self.ui.geo_tools_table.setColumnHidden(6, False)
  2206. self.set_tool_offset_visibility(selected_row)
  2207. self.ui_connect()
  2208. def set_ui(self, ui):
  2209. FlatCAMObj.set_ui(self, ui)
  2210. log.debug("FlatCAMGeometry.set_ui()")
  2211. assert isinstance(self.ui, GeometryObjectUI), \
  2212. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  2213. # populate postprocessor names in the combobox
  2214. for name in list(self.app.postprocessors.keys()):
  2215. self.ui.pp_geometry_name_cb.addItem(name)
  2216. self.form_fields.update({
  2217. "plot": self.ui.plot_cb,
  2218. "cutz": self.ui.cutz_entry,
  2219. "vtipdia": self.ui.tipdia_entry,
  2220. "vtipangle": self.ui.tipangle_entry,
  2221. "travelz": self.ui.travelz_entry,
  2222. "feedrate": self.ui.cncfeedrate_entry,
  2223. "feedrate_z": self.ui.cncplunge_entry,
  2224. "feedrate_rapid": self.ui.cncfeedrate_rapid_entry,
  2225. "spindlespeed": self.ui.cncspindlespeed_entry,
  2226. "dwell": self.ui.dwell_cb,
  2227. "dwelltime": self.ui.dwelltime_entry,
  2228. "multidepth": self.ui.mpass_cb,
  2229. "ppname_g": self.ui.pp_geometry_name_cb,
  2230. "z_pdepth": self.ui.pdepth_entry,
  2231. "feedrate_probe": self.ui.feedrate_probe_entry,
  2232. "depthperpass": self.ui.maxdepth_entry,
  2233. "extracut": self.ui.extracut_cb,
  2234. "toolchange": self.ui.toolchangeg_cb,
  2235. "toolchangez": self.ui.toolchangez_entry,
  2236. "endz": self.ui.gendz_entry,
  2237. })
  2238. # Fill form fields only on object create
  2239. self.to_form()
  2240. self.ui.tipdialabel.hide()
  2241. self.ui.tipdia_entry.hide()
  2242. self.ui.tipanglelabel.hide()
  2243. self.ui.tipangle_entry.hide()
  2244. self.ui.cutz_entry.setDisabled(False)
  2245. # store here the default data for Geometry Data
  2246. self.default_data = {}
  2247. self.default_data.update({
  2248. "name": None,
  2249. "plot": None,
  2250. "cutz": None,
  2251. "vtipdia": None,
  2252. "vtipangle": None,
  2253. "travelz": None,
  2254. "feedrate": None,
  2255. "feedrate_z": None,
  2256. "feedrate_rapid": None,
  2257. "dwell": None,
  2258. "dwelltime": None,
  2259. "multidepth": None,
  2260. "ppname_g": None,
  2261. "depthperpass": None,
  2262. "extracut": None,
  2263. "toolchange": None,
  2264. "toolchangez": None,
  2265. "endz": None,
  2266. "spindlespeed": None,
  2267. "toolchangexy": None,
  2268. "startz": None
  2269. })
  2270. # fill in self.default_data values from self.options
  2271. for def_key in self.default_data:
  2272. for opt_key, opt_val in self.options.items():
  2273. if def_key == opt_key:
  2274. self.default_data[def_key] = opt_val
  2275. self.tooluid += 1
  2276. if not self.tools:
  2277. self.tools.update({
  2278. self.tooluid: {
  2279. 'tooldia': float(self.options["cnctooldia"]),
  2280. 'offset': 'Path',
  2281. 'offset_value': 0.0,
  2282. 'type': 'Rough',
  2283. 'tool_type': 'C1',
  2284. 'data': self.default_data,
  2285. 'solid_geometry': self.solid_geometry
  2286. }
  2287. })
  2288. else:
  2289. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  2290. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  2291. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  2292. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  2293. # following convoluted way of changing the keys from string to float type
  2294. temp_tools = {}
  2295. new_key = 0.0
  2296. for tooluid_key in self.tools:
  2297. val = copy.deepcopy(self.tools[tooluid_key])
  2298. new_key = copy.deepcopy(int(tooluid_key))
  2299. temp_tools[new_key] = val
  2300. self.tools.clear()
  2301. self.tools = copy.deepcopy(temp_tools)
  2302. self.ui.tool_offset_entry.hide()
  2303. self.ui.tool_offset_lbl.hide()
  2304. # used to store the state of the mpass_cb if the selected postproc for geometry is hpgl
  2305. self.old_pp_state = self.default_data['multidepth']
  2306. self.old_toolchangeg_state = self.default_data['toolchange']
  2307. if not isinstance(self.ui, GeometryObjectUI):
  2308. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  2309. return
  2310. self.ui.geo_tools_table.setupContextMenu()
  2311. self.ui.geo_tools_table.addContextMenu(
  2312. "Copy", self.on_tool_copy, icon=QtGui.QIcon("share/copy16.png"))
  2313. self.ui.geo_tools_table.addContextMenu(
  2314. "Delete", lambda: self.on_tool_delete(all=None), icon=QtGui.QIcon("share/delete32.png"))
  2315. # Show/Hide Advanced Options
  2316. if self.app.defaults["global_app_level"] == 'b':
  2317. self.ui.level.setText('<span style="color:green;"><b>Basic</b></span>')
  2318. self.ui.geo_tools_table.setColumnHidden(2, True)
  2319. self.ui.geo_tools_table.setColumnHidden(3, True)
  2320. self.ui.geo_tools_table.setColumnHidden(4, True)
  2321. self.ui.addtool_entry_lbl.hide()
  2322. self.ui.addtool_entry.hide()
  2323. self.ui.addtool_btn.hide()
  2324. self.ui.copytool_btn.hide()
  2325. self.ui.deltool_btn.hide()
  2326. self.ui.endzlabel.hide()
  2327. self.ui.gendz_entry.hide()
  2328. self.ui.fr_rapidlabel.hide()
  2329. self.ui.cncfeedrate_rapid_entry.hide()
  2330. self.ui.extracut_cb.hide()
  2331. self.ui.pdepth_label.hide()
  2332. self.ui.pdepth_entry.hide()
  2333. self.ui.feedrate_probe_label.hide()
  2334. self.ui.feedrate_probe_entry.hide()
  2335. else:
  2336. self.ui.level.setText('<span style="color:red;"><b>Advanced</b></span>')
  2337. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2338. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  2339. self.ui.paint_tool_button.clicked.connect(self.app.paint_tool.run)
  2340. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  2341. def set_tool_offset_visibility(self, current_row):
  2342. if current_row is None:
  2343. return
  2344. try:
  2345. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  2346. if tool_offset is not None:
  2347. tool_offset_txt = tool_offset.currentText()
  2348. if tool_offset_txt == 'Custom':
  2349. self.ui.tool_offset_entry.show()
  2350. self.ui.tool_offset_lbl.show()
  2351. else:
  2352. self.ui.tool_offset_entry.hide()
  2353. self.ui.tool_offset_lbl.hide()
  2354. except Exception as e:
  2355. log.debug("set_tool_offset_visibility() --> " + str(e))
  2356. return
  2357. def on_offset_value_edited(self):
  2358. '''
  2359. This will save the offset_value into self.tools storage whenever the oofset value is edited
  2360. :return:
  2361. '''
  2362. for current_row in self.ui.geo_tools_table.selectedItems():
  2363. # sometime the header get selected and it has row number -1
  2364. # we don't want to do anything with the header :)
  2365. if current_row.row() < 0:
  2366. continue
  2367. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2368. self.set_tool_offset_visibility(current_row.row())
  2369. for tooluid_key, tooluid_value in self.tools.items():
  2370. if int(tooluid_key) == tool_uid:
  2371. try:
  2372. tooluid_value['offset_value'] = float(self.ui.tool_offset_entry.get_value())
  2373. except ValueError:
  2374. # try to convert comma to decimal point. if it's still not working error message and return
  2375. try:
  2376. tooluid_value['offset_value'] = float(
  2377. self.ui.tool_offset_entry.get_value().replace(',', '.')
  2378. )
  2379. except ValueError:
  2380. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2381. "use a number.")
  2382. return
  2383. def ui_connect(self):
  2384. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  2385. # changes in geometry UI
  2386. for i in range(self.ui.grid3.count()):
  2387. try:
  2388. # works for CheckBoxes
  2389. self.ui.grid3.itemAt(i).widget().stateChanged.connect(self.gui_form_to_storage)
  2390. except:
  2391. # works for ComboBoxes
  2392. try:
  2393. self.ui.grid3.itemAt(i).widget().currentIndexChanged.connect(self.gui_form_to_storage)
  2394. except:
  2395. # works for Entry
  2396. try:
  2397. self.ui.grid3.itemAt(i).widget().editingFinished.connect(self.gui_form_to_storage)
  2398. except:
  2399. pass
  2400. for row in range(self.ui.geo_tools_table.rowCount()):
  2401. for col in [2, 3, 4]:
  2402. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  2403. self.on_tooltable_cellwidget_change)
  2404. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  2405. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  2406. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  2407. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  2408. self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  2409. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  2410. self.ui.tool_offset_entry.editingFinished.connect(self.on_offset_value_edited)
  2411. for row in range(self.ui.geo_tools_table.rowCount()):
  2412. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  2413. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2414. def ui_disconnect(self):
  2415. try:
  2416. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  2417. # changes in geometry UI
  2418. for i in range(self.ui.grid3.count()):
  2419. if isinstance(self.ui.grid3.itemAt(i).widget(), FCCheckBox):
  2420. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect()
  2421. if isinstance(self.ui.grid3.itemAt(i).widget(), FCComboBox):
  2422. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect()
  2423. if isinstance(self.ui.grid3.itemAt(i).widget(), LengthEntry) or \
  2424. isinstance(self.ui.grid3.itemAt(i).widget(), IntEntry) or \
  2425. isinstance(self.ui.grid3.itemAt(i).widget(), FCEntry):
  2426. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect()
  2427. except:
  2428. pass
  2429. try:
  2430. for row in range(self.ui.geo_tools_table.rowCount()):
  2431. for col in [2, 3, 4]:
  2432. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  2433. except:
  2434. pass
  2435. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  2436. try:
  2437. self.ui.addtool_btn.clicked.disconnect()
  2438. except:
  2439. pass
  2440. try:
  2441. self.ui.copytool_btn.clicked.disconnect()
  2442. except:
  2443. pass
  2444. try:
  2445. self.ui.deltool_btn.clicked.disconnect()
  2446. except:
  2447. pass
  2448. try:
  2449. self.ui.geo_tools_table.currentItemChanged.disconnect()
  2450. except:
  2451. pass
  2452. try:
  2453. self.ui.geo_tools_table.itemChanged.disconnect()
  2454. except:
  2455. pass
  2456. try:
  2457. self.ui.tool_offset_entry.editingFinished.disconnect()
  2458. except:
  2459. pass
  2460. for row in range(self.ui.geo_tools_table.rowCount()):
  2461. try:
  2462. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  2463. except:
  2464. pass
  2465. try:
  2466. self.ui.plot_cb.stateChanged.disconnect()
  2467. except:
  2468. pass
  2469. def on_tool_add(self, dia=None):
  2470. self.ui_disconnect()
  2471. last_offset = None
  2472. last_offset_value = None
  2473. last_type = None
  2474. last_tool_type = None
  2475. last_data = None
  2476. last_solid_geometry = []
  2477. # if a Tool diameter entered is a char instead a number the final message of Tool adding is changed
  2478. # because the Default value for Tool is used.
  2479. change_message = False
  2480. if dia is not None:
  2481. tooldia = dia
  2482. else:
  2483. try:
  2484. tooldia = float(self.ui.addtool_entry.get_value())
  2485. except ValueError:
  2486. # try to convert comma to decimal point. if it's still not working error message and return
  2487. try:
  2488. tooldia = float(self.ui.addtool_entry.get_value().replace(',', '.'))
  2489. except ValueError:
  2490. change_message = True
  2491. tooldia = float(self.app.defaults["geometry_cnctooldia"])
  2492. if tooldia is None:
  2493. self.build_ui()
  2494. self.app.inform.emit("[ERROR_NOTCL] Please enter the desired tool diameter in Float format.")
  2495. return
  2496. # construct a list of all 'tooluid' in the self.tools
  2497. tool_uid_list = []
  2498. for tooluid_key in self.tools:
  2499. tool_uid_item = int(tooluid_key)
  2500. tool_uid_list.append(tool_uid_item)
  2501. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2502. if not tool_uid_list:
  2503. max_uid = 0
  2504. else:
  2505. max_uid = max(tool_uid_list)
  2506. self.tooluid = max_uid + 1
  2507. if self.units == 'IN':
  2508. tooldia = float('%.4f' % tooldia)
  2509. else:
  2510. tooldia = float('%.2f' % tooldia)
  2511. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  2512. # otherwise we add a tool with data copied from last tool
  2513. if not self.tools:
  2514. self.tools.update({
  2515. self.tooluid: {
  2516. 'tooldia': tooldia,
  2517. 'offset': 'Path',
  2518. 'offset_value': 0.0,
  2519. 'type': 'Rough',
  2520. 'tool_type': 'C1',
  2521. 'data': copy.deepcopy(self.default_data),
  2522. 'solid_geometry': self.solid_geometry
  2523. }
  2524. })
  2525. else:
  2526. # print("LAST", self.tools[maxuid])
  2527. last_data = self.tools[max_uid]['data']
  2528. last_offset = self.tools[max_uid]['offset']
  2529. last_offset_value = self.tools[max_uid]['offset_value']
  2530. last_type = self.tools[max_uid]['type']
  2531. last_tool_type = self.tools[max_uid]['tool_type']
  2532. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  2533. # if previous geometry was empty (it may happen for the first tool added)
  2534. # then copy the object.solid_geometry
  2535. if not last_solid_geometry:
  2536. last_solid_geometry = self.solid_geometry
  2537. self.tools.update({
  2538. self.tooluid: {
  2539. 'tooldia': tooldia,
  2540. 'offset': last_offset,
  2541. 'offset_value': last_offset_value,
  2542. 'type': last_type,
  2543. 'tool_type': last_tool_type,
  2544. 'data': copy.deepcopy(last_data),
  2545. 'solid_geometry': copy.deepcopy(last_solid_geometry)
  2546. }
  2547. })
  2548. # print("CURRENT", self.tools[-1])
  2549. self.ui.tool_offset_entry.hide()
  2550. self.ui.tool_offset_lbl.hide()
  2551. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2552. try:
  2553. self.ser_attrs.remove('tools')
  2554. except:
  2555. pass
  2556. self.ser_attrs.append('tools')
  2557. if change_message is False:
  2558. self.app.inform.emit("[success] Tool added in Tool Table.")
  2559. else:
  2560. change_message = False
  2561. self.app.inform.emit("[ERROR_NOTCL]Default Tool added. Wrong value format entered.")
  2562. self.build_ui()
  2563. def on_tool_copy(self, all=None):
  2564. self.ui_disconnect()
  2565. # find the tool_uid maximum value in the self.tools
  2566. uid_list = []
  2567. for key in self.tools:
  2568. uid_list.append(int(key))
  2569. try:
  2570. max_uid = max(uid_list, key=int)
  2571. except ValueError:
  2572. max_uid = 0
  2573. if all is None:
  2574. if self.ui.geo_tools_table.selectedItems():
  2575. for current_row in self.ui.geo_tools_table.selectedItems():
  2576. # sometime the header get selected and it has row number -1
  2577. # we don't want to do anything with the header :)
  2578. if current_row.row() < 0:
  2579. continue
  2580. try:
  2581. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2582. self.set_tool_offset_visibility(current_row.row())
  2583. max_uid += 1
  2584. self.tools[int(max_uid)] = copy.deepcopy(self.tools[tooluid_copy])
  2585. except AttributeError:
  2586. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to copy.")
  2587. self.build_ui()
  2588. return
  2589. except Exception as e:
  2590. log.debug("on_tool_copy() --> " + str(e))
  2591. # deselect the table
  2592. # self.ui.geo_tools_table.clearSelection()
  2593. else:
  2594. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to copy.")
  2595. self.build_ui()
  2596. return
  2597. else:
  2598. # we copy all tools in geo_tools_table
  2599. try:
  2600. temp_tools = copy.deepcopy(self.tools)
  2601. max_uid += 1
  2602. for tooluid in temp_tools:
  2603. self.tools[int(max_uid)] = copy.deepcopy(temp_tools[tooluid])
  2604. temp_tools.clear()
  2605. except Exception as e:
  2606. log.debug("on_tool_copy() --> " + str(e))
  2607. # if there are no more tools in geo tools table then hide the tool offset
  2608. if not self.tools:
  2609. self.ui.tool_offset_entry.hide()
  2610. self.ui.tool_offset_lbl.hide()
  2611. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2612. try:
  2613. self.ser_attrs.remove('tools')
  2614. except:
  2615. pass
  2616. self.ser_attrs.append('tools')
  2617. self.build_ui()
  2618. self.app.inform.emit("[success] Tool was copied in Tool Table.")
  2619. def on_tool_edit(self, current_item):
  2620. self.ui_disconnect()
  2621. current_row = current_item.row()
  2622. try:
  2623. d = float(self.ui.geo_tools_table.item(current_row, 1).text())
  2624. except ValueError:
  2625. # try to convert comma to decimal point. if it's still not working error message and return
  2626. try:
  2627. d = float(self.ui.geo_tools_table.item(current_row, 1).text().replace(',', '.'))
  2628. except ValueError:
  2629. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2630. "use a number.")
  2631. return
  2632. tool_dia = float('%.4f' % d)
  2633. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2634. self.tools[tooluid]['tooldia'] = tool_dia
  2635. try:
  2636. self.ser_attrs.remove('tools')
  2637. self.ser_attrs.append('tools')
  2638. except:
  2639. pass
  2640. self.app.inform.emit("[success] Tool was edited in Tool Table.")
  2641. self.build_ui()
  2642. def on_tool_delete(self, all=None):
  2643. self.ui_disconnect()
  2644. if all is None:
  2645. if self.ui.geo_tools_table.selectedItems():
  2646. for current_row in self.ui.geo_tools_table.selectedItems():
  2647. # sometime the header get selected and it has row number -1
  2648. # we don't want to do anything with the header :)
  2649. if current_row.row() < 0:
  2650. continue
  2651. try:
  2652. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2653. self.set_tool_offset_visibility(current_row.row())
  2654. temp_tools = copy.deepcopy(self.tools)
  2655. for tooluid_key in self.tools:
  2656. if int(tooluid_key) == tooluid_del:
  2657. # if the self.tools has only one tool and we delete it then we move the solid_geometry
  2658. # as a property of the object otherwise there will be nothing to hold it
  2659. if len(self.tools) == 1:
  2660. self.solid_geometry = copy.deepcopy(self.tools[tooluid_key]['solid_geometry'])
  2661. temp_tools.pop(tooluid_del, None)
  2662. self.tools = copy.deepcopy(temp_tools)
  2663. temp_tools.clear()
  2664. except AttributeError:
  2665. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to delete.")
  2666. self.build_ui()
  2667. return
  2668. except Exception as e:
  2669. log.debug("on_tool_delete() --> " + str(e))
  2670. # deselect the table
  2671. # self.ui.geo_tools_table.clearSelection()
  2672. else:
  2673. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to delete.")
  2674. self.build_ui()
  2675. return
  2676. else:
  2677. # we delete all tools in geo_tools_table
  2678. self.tools.clear()
  2679. self.app.plot_all()
  2680. # if there are no more tools in geo tools table then hide the tool offset
  2681. if not self.tools:
  2682. self.ui.tool_offset_entry.hide()
  2683. self.ui.tool_offset_lbl.hide()
  2684. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2685. try:
  2686. self.ser_attrs.remove('tools')
  2687. except:
  2688. pass
  2689. self.ser_attrs.append('tools')
  2690. self.build_ui()
  2691. self.app.inform.emit("[success] Tool was deleted in Tool Table.")
  2692. obj_active = self.app.collection.get_active()
  2693. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  2694. # we make it back SingleGeo
  2695. if self.ui.geo_tools_table.rowCount() <= 0:
  2696. obj_active.multigeo = False
  2697. obj_active.options['xmin'] = 0
  2698. obj_active.options['ymin'] = 0
  2699. obj_active.options['xmax'] = 0
  2700. obj_active.options['ymax'] = 0
  2701. if obj_active.multigeo is True:
  2702. try:
  2703. xmin, ymin, xmax, ymax = obj_active.bounds()
  2704. obj_active.options['xmin'] = xmin
  2705. obj_active.options['ymin'] = ymin
  2706. obj_active.options['xmax'] = xmax
  2707. obj_active.options['ymax'] = ymax
  2708. except:
  2709. obj_active.options['xmin'] = 0
  2710. obj_active.options['ymin'] = 0
  2711. obj_active.options['xmax'] = 0
  2712. obj_active.options['ymax'] = 0
  2713. def on_row_selection_change(self):
  2714. self.update_ui()
  2715. def update_ui(self, row=None):
  2716. self.ui_disconnect()
  2717. if row is None:
  2718. try:
  2719. current_row = self.ui.geo_tools_table.currentRow()
  2720. except:
  2721. current_row = 0
  2722. else:
  2723. current_row = row
  2724. if current_row < 0:
  2725. current_row = 0
  2726. self.set_tool_offset_visibility(current_row)
  2727. # populate the form with the data from the tool associated with the row parameter
  2728. try:
  2729. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2730. except Exception as e:
  2731. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2732. return
  2733. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  2734. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  2735. try:
  2736. tool_type_txt = self.ui.geo_tools_table.cellWidget(current_row, 4).currentText()
  2737. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  2738. except Exception as e:
  2739. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2740. return
  2741. try:
  2742. # set the form with data from the newly selected tool
  2743. for tooluid_key, tooluid_value in self.tools.items():
  2744. if int(tooluid_key) == tooluid:
  2745. for key, value in tooluid_value.items():
  2746. if key == 'data':
  2747. form_value_storage = tooluid_value[key]
  2748. self.update_form(form_value_storage)
  2749. if key == 'offset_value':
  2750. # update the offset value in the entry even if the entry is hidden
  2751. self.ui.tool_offset_entry.set_value(tooluid_value[key])
  2752. if key == 'tool_type' and value == 'V':
  2753. self.update_cutz()
  2754. except Exception as e:
  2755. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  2756. self.ui_connect()
  2757. def ui_update_v_shape(self, tool_type_txt):
  2758. if tool_type_txt == 'V':
  2759. self.ui.tipdialabel.show()
  2760. self.ui.tipdia_entry.show()
  2761. self.ui.tipanglelabel.show()
  2762. self.ui.tipangle_entry.show()
  2763. self.ui.cutz_entry.setDisabled(True)
  2764. self.update_cutz()
  2765. else:
  2766. self.ui.tipdialabel.hide()
  2767. self.ui.tipdia_entry.hide()
  2768. self.ui.tipanglelabel.hide()
  2769. self.ui.tipangle_entry.hide()
  2770. self.ui.cutz_entry.setDisabled(False)
  2771. def update_cutz(self):
  2772. try:
  2773. vdia = float(self.ui.tipdia_entry.get_value())
  2774. except ValueError:
  2775. # try to convert comma to decimal point. if it's still not working error message and return
  2776. try:
  2777. vdia = float(self.ui.tipdia_entry.get_value().replace(',', '.'))
  2778. except ValueError:
  2779. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2780. "use a number.")
  2781. return
  2782. try:
  2783. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  2784. except ValueError:
  2785. # try to convert comma to decimal point. if it's still not working error message and return
  2786. try:
  2787. half_vangle = float(self.ui.tipangle_entry.get_value().replace(',', '.')) / 2
  2788. except ValueError:
  2789. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2790. "use a number.")
  2791. return
  2792. row = self.ui.geo_tools_table.currentRow()
  2793. tool_uid = int(self.ui.geo_tools_table.item(row, 5).text())
  2794. tooldia = float(self.ui.geo_tools_table.item(row, 1).text())
  2795. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  2796. new_cutz = float('%.4f' % -new_cutz)
  2797. self.ui.cutz_entry.set_value(new_cutz)
  2798. # store the new CutZ value into storage (self.tools)
  2799. for tooluid_key, tooluid_value in self.tools.items():
  2800. if int(tooluid_key) == tool_uid:
  2801. tooluid_value['data']['cutz'] = new_cutz
  2802. def on_tooltable_cellwidget_change(self):
  2803. cw = self.sender()
  2804. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  2805. cw_row = cw_index.row()
  2806. cw_col = cw_index.column()
  2807. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  2808. # store the text of the cellWidget that changed it's index in the self.tools
  2809. for tooluid_key, tooluid_value in self.tools.items():
  2810. if int(tooluid_key) == current_uid:
  2811. cb_txt = cw.currentText()
  2812. if cw_col == 2:
  2813. tooluid_value['offset'] = cb_txt
  2814. if cb_txt == 'Custom':
  2815. self.ui.tool_offset_entry.show()
  2816. self.ui.tool_offset_lbl.show()
  2817. else:
  2818. self.ui.tool_offset_entry.hide()
  2819. self.ui.tool_offset_lbl.hide()
  2820. # reset the offset_value in storage self.tools
  2821. tooluid_value['offset_value'] = 0.0
  2822. elif cw_col == 3:
  2823. # force toolpath type as 'Iso' if the tool type is V-Shape
  2824. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  2825. tooluid_value['type'] = 'Iso'
  2826. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2827. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2828. else:
  2829. tooluid_value['type'] = cb_txt
  2830. elif cw_col == 4:
  2831. tooluid_value['tool_type'] = cb_txt
  2832. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  2833. if cb_txt == 'V':
  2834. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2835. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2836. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  2837. def update_form(self, dict_storage):
  2838. for form_key in self.form_fields:
  2839. for storage_key in dict_storage:
  2840. if form_key == storage_key:
  2841. try:
  2842. self.form_fields[form_key].set_value(dict_storage[form_key])
  2843. except Exception as e:
  2844. log.debug(str(e))
  2845. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  2846. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  2847. self.ui.ois_dwell_geo.on_cb_change()
  2848. self.ui.ois_mpass_geo.on_cb_change()
  2849. self.ui.ois_tcz_geo.on_cb_change()
  2850. def gui_form_to_storage(self):
  2851. self.ui_disconnect()
  2852. widget_changed = self.sender()
  2853. try:
  2854. widget_idx = self.ui.grid3.indexOf(widget_changed)
  2855. except:
  2856. return
  2857. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  2858. if widget_idx == 1 or widget_idx == 3:
  2859. self.update_cutz()
  2860. # the original connect() function of the OptionalInpuSelection is no longer working because of the
  2861. # ui_diconnect() so I use this 'hack'
  2862. if isinstance(widget_changed, FCCheckBox):
  2863. if widget_changed.text() == 'Multi-Depth:':
  2864. self.ui.ois_mpass_geo.on_cb_change()
  2865. if widget_changed.text() == 'Tool change':
  2866. self.ui.ois_tcz_geo.on_cb_change()
  2867. if widget_changed.text() == 'Dwell:':
  2868. self.ui.ois_dwell_geo.on_cb_change()
  2869. row = self.ui.geo_tools_table.currentRow()
  2870. if row < 0:
  2871. row = 0
  2872. # store all the data associated with the row parameter to the self.tools storage
  2873. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  2874. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  2875. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  2876. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  2877. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  2878. try:
  2879. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  2880. except ValueError:
  2881. # try to convert comma to decimal point. if it's still not working error message and return
  2882. try:
  2883. offset_value_item = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  2884. )
  2885. except ValueError:
  2886. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2887. "use a number.")
  2888. return
  2889. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  2890. temp_tools = {}
  2891. temp_dia = {}
  2892. temp_data = {}
  2893. for tooluid_key, tooluid_value in self.tools.items():
  2894. if int(tooluid_key) == tooluid_item:
  2895. for key, value in tooluid_value.items():
  2896. if key == 'tooldia':
  2897. temp_dia[key] = tooldia_item
  2898. # update the 'offset', 'type' and 'tool_type' sections
  2899. if key == 'offset':
  2900. temp_dia[key] = offset_item
  2901. if key == 'type':
  2902. temp_dia[key] = type_item
  2903. if key == 'tool_type':
  2904. temp_dia[key] = tool_type_item
  2905. if key == 'offset_value':
  2906. temp_dia[key] = offset_value_item
  2907. if key == 'data':
  2908. # update the 'data' section
  2909. for data_key in tooluid_value[key].keys():
  2910. for form_key, form_value in self.form_fields.items():
  2911. if form_key == data_key:
  2912. temp_data[data_key] = form_value.get_value()
  2913. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  2914. # updated from self.app.defaults
  2915. if data_key not in self.form_fields:
  2916. temp_data[data_key] = value[data_key]
  2917. temp_dia[key] = copy.deepcopy(temp_data)
  2918. temp_data.clear()
  2919. if key == 'solid_geometry':
  2920. temp_dia[key] = copy.deepcopy(self.tools[tooluid_key]['solid_geometry'])
  2921. temp_tools[tooluid_key] = copy.deepcopy(temp_dia)
  2922. else:
  2923. temp_tools[tooluid_key] = copy.deepcopy(tooluid_value)
  2924. self.tools.clear()
  2925. self.tools = copy.deepcopy(temp_tools)
  2926. temp_tools.clear()
  2927. self.ui_connect()
  2928. def select_tools_table_row(self, row, clearsel=None):
  2929. if clearsel:
  2930. self.ui.geo_tools_table.clearSelection()
  2931. if self.ui.geo_tools_table.rowCount() > 0:
  2932. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  2933. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  2934. def export_dxf(self):
  2935. units = self.app.ui.general_options_form.general_app_group.units_radio.get_value().upper()
  2936. dwg = None
  2937. try:
  2938. dwg = ezdxf.new('R2010')
  2939. msp = dwg.modelspace()
  2940. def g2dxf(dxf_space, geo):
  2941. if isinstance(geo, MultiPolygon):
  2942. for poly in geo:
  2943. ext_points = list(poly.exterior.coords)
  2944. dxf_space.add_lwpolyline(ext_points)
  2945. for interior in poly.interiors:
  2946. dxf_space.add_lwpolyline(list(interior.coords))
  2947. if isinstance(geo, Polygon):
  2948. ext_points = list(geo.exterior.coords)
  2949. dxf_space.add_lwpolyline(ext_points)
  2950. for interior in geo.interiors:
  2951. dxf_space.add_lwpolyline(list(interior.coords))
  2952. if isinstance(geo, MultiLineString):
  2953. for line in geo:
  2954. dxf_space.add_lwpolyline(list(line.coords))
  2955. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  2956. dxf_space.add_lwpolyline(list(geo.coords))
  2957. multigeo_solid_geometry = []
  2958. if self.multigeo:
  2959. for tool in self.tools:
  2960. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  2961. else:
  2962. multigeo_solid_geometry = self.solid_geometry
  2963. for geo in multigeo_solid_geometry:
  2964. if type(geo) == list:
  2965. for g in geo:
  2966. g2dxf(msp, g)
  2967. else:
  2968. g2dxf(msp, geo)
  2969. # points = FlatCAMGeometry.get_pts(geo)
  2970. # msp.add_lwpolyline(points)
  2971. except Exception as e:
  2972. log.debug(str(e))
  2973. return dwg
  2974. def get_selected_tools_table_items(self):
  2975. """
  2976. Returns a list of lists, each list in the list is made out of row elements
  2977. :return: List of table_tools items.
  2978. :rtype: list
  2979. """
  2980. table_tools_items = []
  2981. if self.multigeo:
  2982. for x in self.ui.geo_tools_table.selectedItems():
  2983. table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  2984. for column in range(0, self.ui.geo_tools_table.columnCount())])
  2985. else:
  2986. for x in self.ui.geo_tools_table.selectedItems():
  2987. r = []
  2988. # the last 2 columns for single-geo geometry are irrelevant and create problems reading
  2989. # so we don't read them
  2990. for column in range(0, self.ui.geo_tools_table.columnCount() - 2):
  2991. # the columns have items that have text but also have items that are widgets
  2992. # for which the text they hold has to be read differently
  2993. try:
  2994. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  2995. except AttributeError:
  2996. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  2997. except:
  2998. pass
  2999. r.append(txt)
  3000. table_tools_items.append(r)
  3001. for item in table_tools_items:
  3002. item[0] = str(item[0])
  3003. return table_tools_items
  3004. def on_pp_changed(self):
  3005. current_pp = self.ui.pp_geometry_name_cb.get_value()
  3006. if current_pp == 'hpgl':
  3007. self.old_pp_state = self.ui.mpass_cb.get_value()
  3008. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  3009. self.ui.mpass_cb.set_value(False)
  3010. self.ui.mpass_cb.setDisabled(True)
  3011. self.ui.toolchangeg_cb.set_value(True)
  3012. self.ui.toolchangeg_cb.setDisabled(True)
  3013. else:
  3014. self.ui.mpass_cb.set_value(self.old_pp_state)
  3015. self.ui.mpass_cb.setDisabled(False)
  3016. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  3017. self.ui.toolchangeg_cb.setDisabled(False)
  3018. if "toolchange_probe" in current_pp.lower():
  3019. self.ui.pdepth_entry.setVisible(True)
  3020. self.ui.pdepth_label.show()
  3021. self.ui.feedrate_probe_entry.setVisible(True)
  3022. self.ui.feedrate_probe_label.show()
  3023. else:
  3024. self.ui.pdepth_entry.setVisible(False)
  3025. self.ui.pdepth_label.hide()
  3026. self.ui.feedrate_probe_entry.setVisible(False)
  3027. self.ui.feedrate_probe_label.hide()
  3028. def on_generatecnc_button_click(self, *args):
  3029. self.app.report_usage("geometry_on_generatecnc_button")
  3030. self.read_form()
  3031. self.sel_tools = {}
  3032. try:
  3033. if self.special_group:
  3034. self.app.inform.emit("[WARNING_NOTCL]This Geometry can't be processed because it is %s geometry." %
  3035. str(self.special_group))
  3036. return
  3037. except AttributeError:
  3038. pass
  3039. # test to see if we have tools available in the tool table
  3040. if self.ui.geo_tools_table.selectedItems():
  3041. for x in self.ui.geo_tools_table.selectedItems():
  3042. try:
  3043. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  3044. except ValueError:
  3045. # try to convert comma to decimal point. if it's still not working error message and return
  3046. try:
  3047. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text().replace(',', '.'))
  3048. except ValueError:
  3049. self.app.inform.emit("[ERROR_NOTCL]Wrong Tool Dia value format entered, "
  3050. "use a number.")
  3051. return
  3052. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  3053. for tooluid_key, tooluid_value in self.tools.items():
  3054. if int(tooluid_key) == tooluid:
  3055. self.sel_tools.update({
  3056. tooluid: copy.deepcopy(tooluid_value)
  3057. })
  3058. self.mtool_gen_cncjob()
  3059. self.ui.geo_tools_table.clearSelection()
  3060. elif self.ui.geo_tools_table.rowCount() == 1:
  3061. tooluid = int(self.ui.geo_tools_table.item(0, 5).text())
  3062. for tooluid_key, tooluid_value in self.tools.items():
  3063. if int(tooluid_key) == tooluid:
  3064. self.sel_tools.update({
  3065. tooluid: copy.deepcopy(tooluid_value)
  3066. })
  3067. self.mtool_gen_cncjob()
  3068. self.ui.geo_tools_table.clearSelection()
  3069. else:
  3070. self.app.inform.emit("[ERROR_NOTCL] Failed. No tool selected in the tool table ...")
  3071. def mtool_gen_cncjob(self, segx=None, segy=None, use_thread=True):
  3072. """
  3073. Creates a multi-tool CNCJob out of this Geometry object.
  3074. The actual work is done by the target FlatCAMCNCjob object's
  3075. `generate_from_geometry_2()` method.
  3076. :param z_cut: Cut depth (negative)
  3077. :param z_move: Hight of the tool when travelling (not cutting)
  3078. :param feedrate: Feed rate while cutting on X - Y plane
  3079. :param feedrate_z: Feed rate while cutting on Z plane
  3080. :param feedrate_rapid: Feed rate while moving with rapids
  3081. :param tooldia: Tool diameter
  3082. :param outname: Name of the new object
  3083. :param spindlespeed: Spindle speed (RPM)
  3084. :param ppname_g Name of the postprocessor
  3085. :return: None
  3086. """
  3087. offset_str = ''
  3088. multitool_gcode = ''
  3089. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  3090. outname = "%s_%s" % (self.options["name"], 'cnc')
  3091. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  3092. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  3093. try:
  3094. xmin = self.options['xmin']
  3095. ymin = self.options['ymin']
  3096. xmax = self.options['xmax']
  3097. ymax = self.options['ymax']
  3098. except Exception as e:
  3099. log.debug("FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s\n" % str(e))
  3100. msg = "[ERROR] An internal error has ocurred. See shell.\n"
  3101. msg += 'FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s' % str(e)
  3102. msg += traceback.format_exc()
  3103. self.app.inform.emit(msg)
  3104. return
  3105. # Object initialization function for app.new_object()
  3106. # RUNNING ON SEPARATE THREAD!
  3107. def job_init_single_geometry(job_obj, app_obj):
  3108. assert isinstance(job_obj, FlatCAMCNCjob), \
  3109. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3110. # count the tools
  3111. tool_cnt = 0
  3112. dia_cnc_dict = {}
  3113. # this turn on the FlatCAMCNCJob plot for multiple tools
  3114. job_obj.multitool = True
  3115. job_obj.multigeo = False
  3116. job_obj.cnc_tools.clear()
  3117. # job_obj.create_geometry()
  3118. job_obj.options['Tools_in_use'] = self.get_selected_tools_table_items()
  3119. job_obj.segx = segx
  3120. job_obj.segy = segy
  3121. try:
  3122. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3123. except ValueError:
  3124. # try to convert comma to decimal point. if it's still not working error message and return
  3125. try:
  3126. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3127. except ValueError:
  3128. self.app.inform.emit(
  3129. '[ERROR_NOTCL]Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]')
  3130. try:
  3131. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3132. except ValueError:
  3133. # try to convert comma to decimal point. if it's still not working error message and return
  3134. try:
  3135. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3136. except ValueError:
  3137. self.app.inform.emit(
  3138. '[ERROR_NOTCL]Wrong value format for self.defaults["feedrate_probe"] '
  3139. 'or self.options["feedrate_probe"]')
  3140. for tooluid_key in self.sel_tools:
  3141. tool_cnt += 1
  3142. app_obj.progress.emit(20)
  3143. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3144. if diadict_key == 'tooldia':
  3145. tooldia_val = float('%.4f' % float(diadict_value))
  3146. dia_cnc_dict.update({
  3147. diadict_key: tooldia_val
  3148. })
  3149. if diadict_key == 'offset':
  3150. o_val = diadict_value.lower()
  3151. dia_cnc_dict.update({
  3152. diadict_key: o_val
  3153. })
  3154. if diadict_key == 'type':
  3155. t_val = diadict_value
  3156. dia_cnc_dict.update({
  3157. diadict_key: t_val
  3158. })
  3159. if diadict_key == 'tool_type':
  3160. tt_val = diadict_value
  3161. dia_cnc_dict.update({
  3162. diadict_key: tt_val
  3163. })
  3164. if diadict_key == 'data':
  3165. for data_key, data_value in diadict_value.items():
  3166. if data_key == "multidepth":
  3167. multidepth = data_value
  3168. if data_key == "depthperpass":
  3169. depthpercut = data_value
  3170. if data_key == "extracut":
  3171. extracut = data_value
  3172. if data_key == "startz":
  3173. startz = data_value
  3174. if data_key == "endz":
  3175. endz = data_value
  3176. if data_key == "toolchangez":
  3177. toolchangez =data_value
  3178. if data_key == "toolchangexy":
  3179. toolchangexy = data_value
  3180. if data_key == "toolchange":
  3181. toolchange = data_value
  3182. if data_key == "cutz":
  3183. z_cut = data_value
  3184. if data_key == "travelz":
  3185. z_move = data_value
  3186. if data_key == "feedrate":
  3187. feedrate = data_value
  3188. if data_key == "feedrate_z":
  3189. feedrate_z = data_value
  3190. if data_key == "feedrate_rapid":
  3191. feedrate_rapid = data_value
  3192. if data_key == "ppname_g":
  3193. pp_geometry_name = data_value
  3194. if data_key == "spindlespeed":
  3195. spindlespeed = data_value
  3196. if data_key == "dwell":
  3197. dwell = data_value
  3198. if data_key == "dwelltime":
  3199. dwelltime = data_value
  3200. datadict = copy.deepcopy(diadict_value)
  3201. dia_cnc_dict.update({
  3202. diadict_key: datadict
  3203. })
  3204. if dia_cnc_dict['offset'] == 'in':
  3205. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3206. offset_str = 'inside'
  3207. elif dia_cnc_dict['offset'].lower() == 'out':
  3208. tool_offset = dia_cnc_dict['tooldia'] / 2
  3209. offset_str = 'outside'
  3210. elif dia_cnc_dict['offset'].lower() == 'path':
  3211. offset_str = 'onpath'
  3212. tool_offset = 0.0
  3213. else:
  3214. offset_str = 'custom'
  3215. try:
  3216. offset_value = float(self.ui.tool_offset_entry.get_value())
  3217. except ValueError:
  3218. # try to convert comma to decimal point. if it's still not working error message and return
  3219. try:
  3220. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3221. )
  3222. except ValueError:
  3223. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  3224. "use a number.")
  3225. return
  3226. if offset_value:
  3227. tool_offset = float(offset_value)
  3228. else:
  3229. self.app.inform.emit(
  3230. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3231. "Add a Tool Offset or change the Offset Type."
  3232. )
  3233. return
  3234. dia_cnc_dict.update({
  3235. 'offset_value': tool_offset
  3236. })
  3237. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3238. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3239. # Propagate options
  3240. job_obj.options["tooldia"] = tooldia_val
  3241. job_obj.options['type'] = 'Geometry'
  3242. job_obj.options['tool_dia'] = tooldia_val
  3243. job_obj.options['xmin'] = xmin
  3244. job_obj.options['ymin'] = ymin
  3245. job_obj.options['xmax'] = xmax
  3246. job_obj.options['ymax'] = ymax
  3247. app_obj.progress.emit(40)
  3248. res = job_obj.generate_from_geometry_2(
  3249. self, tooldia=tooldia_val, offset=tool_offset, tolerance=0.0005,
  3250. z_cut=z_cut, z_move=z_move,
  3251. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3252. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  3253. multidepth=multidepth, depthpercut=depthpercut,
  3254. extracut=extracut, startz=startz, endz=endz,
  3255. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3256. pp_geometry_name=pp_geometry_name,
  3257. tool_no=tool_cnt)
  3258. if res == 'fail':
  3259. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3260. return 'fail'
  3261. else:
  3262. dia_cnc_dict['gcode'] = res
  3263. app_obj.progress.emit(50)
  3264. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3265. # object is the source of gcode
  3266. job_obj.toolchange_xy_type = "geometry"
  3267. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3268. # TODO this serve for bounding box creation only; should be optimized
  3269. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3270. app_obj.progress.emit(80)
  3271. job_obj.cnc_tools.update({
  3272. tooluid_key: copy.deepcopy(dia_cnc_dict)
  3273. })
  3274. dia_cnc_dict.clear()
  3275. # Object initialization function for app.new_object()
  3276. # RUNNING ON SEPARATE THREAD!
  3277. def job_init_multi_geometry(job_obj, app_obj):
  3278. assert isinstance(job_obj, FlatCAMCNCjob), \
  3279. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3280. # count the tools
  3281. tool_cnt = 0
  3282. dia_cnc_dict = {}
  3283. current_uid = int(1)
  3284. # this turn on the FlatCAMCNCJob plot for multiple tools
  3285. job_obj.multitool = True
  3286. job_obj.multigeo = True
  3287. job_obj.cnc_tools.clear()
  3288. job_obj.options['xmin'] = xmin
  3289. job_obj.options['ymin'] = ymin
  3290. job_obj.options['xmax'] = xmax
  3291. job_obj.options['ymax'] = ymax
  3292. try:
  3293. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3294. except ValueError:
  3295. # try to convert comma to decimal point. if it's still not working error message and return
  3296. try:
  3297. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3298. except ValueError:
  3299. self.app.inform.emit(
  3300. '[ERROR_NOTCL]Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]')
  3301. try:
  3302. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3303. except ValueError:
  3304. # try to convert comma to decimal point. if it's still not working error message and return
  3305. try:
  3306. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3307. except ValueError:
  3308. self.app.inform.emit(
  3309. '[ERROR_NOTCL]Wrong value format for self.defaults["feedrate_probe"] '
  3310. 'or self.options["feedrate_probe"]')
  3311. # make sure that trying to make a CNCJob from an empty file is not creating an app crash
  3312. if not self.solid_geometry:
  3313. a = 0
  3314. for tooluid_key in self.tools:
  3315. if self.tools[tooluid_key]['solid_geometry'] is None:
  3316. a += 1
  3317. if a == len(self.tools):
  3318. self.app.inform.emit('[ERROR_NOTCL]Cancelled. Empty file, it has no geometry...')
  3319. return 'fail'
  3320. for tooluid_key in self.sel_tools:
  3321. tool_cnt += 1
  3322. app_obj.progress.emit(20)
  3323. # find the tool_dia associated with the tooluid_key
  3324. sel_tool_dia = self.sel_tools[tooluid_key]['tooldia']
  3325. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  3326. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  3327. for k, v in self.tools.items():
  3328. if float('%.4f' % float(v['tooldia'])) == float('%.4f' % float(sel_tool_dia)):
  3329. current_uid = int(k)
  3330. break
  3331. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3332. if diadict_key == 'tooldia':
  3333. tooldia_val = float('%.4f' % float(diadict_value))
  3334. dia_cnc_dict.update({
  3335. diadict_key: tooldia_val
  3336. })
  3337. if diadict_key == 'offset':
  3338. o_val = diadict_value.lower()
  3339. dia_cnc_dict.update({
  3340. diadict_key: o_val
  3341. })
  3342. if diadict_key == 'type':
  3343. t_val = diadict_value
  3344. dia_cnc_dict.update({
  3345. diadict_key: t_val
  3346. })
  3347. if diadict_key == 'tool_type':
  3348. tt_val = diadict_value
  3349. dia_cnc_dict.update({
  3350. diadict_key: tt_val
  3351. })
  3352. if diadict_key == 'data':
  3353. for data_key, data_value in diadict_value.items():
  3354. if data_key == "multidepth":
  3355. multidepth = data_value
  3356. if data_key == "depthperpass":
  3357. depthpercut = data_value
  3358. if data_key == "extracut":
  3359. extracut = data_value
  3360. if data_key == "startz":
  3361. startz = data_value
  3362. if data_key == "endz":
  3363. endz = data_value
  3364. if data_key == "toolchangez":
  3365. toolchangez =data_value
  3366. if data_key == "toolchangexy":
  3367. toolchangexy = data_value
  3368. if data_key == "toolchange":
  3369. toolchange = data_value
  3370. if data_key == "cutz":
  3371. z_cut = data_value
  3372. if data_key == "travelz":
  3373. z_move = data_value
  3374. if data_key == "feedrate":
  3375. feedrate = data_value
  3376. if data_key == "feedrate_z":
  3377. feedrate_z = data_value
  3378. if data_key == "feedrate_rapid":
  3379. feedrate_rapid = data_value
  3380. if data_key == "ppname_g":
  3381. pp_geometry_name = data_value
  3382. if data_key == "spindlespeed":
  3383. spindlespeed = data_value
  3384. if data_key == "dwell":
  3385. dwell = data_value
  3386. if data_key == "dwelltime":
  3387. dwelltime = data_value
  3388. datadict = copy.deepcopy(diadict_value)
  3389. dia_cnc_dict.update({
  3390. diadict_key: datadict
  3391. })
  3392. if dia_cnc_dict['offset'] == 'in':
  3393. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3394. offset_str = 'inside'
  3395. elif dia_cnc_dict['offset'].lower() == 'out':
  3396. tool_offset = dia_cnc_dict['tooldia'] / 2
  3397. offset_str = 'outside'
  3398. elif dia_cnc_dict['offset'].lower() == 'path':
  3399. offset_str = 'onpath'
  3400. tool_offset = 0.0
  3401. else:
  3402. offset_str = 'custom'
  3403. try:
  3404. offset_value = float(self.ui.tool_offset_entry.get_value())
  3405. except ValueError:
  3406. # try to convert comma to decimal point. if it's still not working error message and return
  3407. try:
  3408. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3409. )
  3410. except ValueError:
  3411. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  3412. "use a number.")
  3413. return
  3414. if offset_value:
  3415. tool_offset = float(offset_value)
  3416. else:
  3417. self.app.inform.emit(
  3418. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3419. "Add a Tool Offset or change the Offset Type."
  3420. )
  3421. return
  3422. dia_cnc_dict.update({
  3423. 'offset_value': tool_offset
  3424. })
  3425. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3426. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3427. # Propagate options
  3428. job_obj.options["tooldia"] = tooldia_val
  3429. job_obj.options['type'] = 'Geometry'
  3430. job_obj.options['tool_dia'] = tooldia_val
  3431. app_obj.progress.emit(40)
  3432. tool_solid_geometry = self.tools[current_uid]['solid_geometry']
  3433. res = job_obj.generate_from_multitool_geometry(
  3434. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  3435. tolerance=0.0005, z_cut=z_cut, z_move=z_move,
  3436. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3437. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  3438. multidepth=multidepth, depthpercut=depthpercut,
  3439. extracut=extracut, startz=startz, endz=endz,
  3440. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3441. pp_geometry_name=pp_geometry_name,
  3442. tool_no=tool_cnt)
  3443. if res == 'fail':
  3444. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3445. return 'fail'
  3446. else:
  3447. dia_cnc_dict['gcode'] = res
  3448. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3449. # TODO this serve for bounding box creation only; should be optimized
  3450. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3451. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3452. # object is the source of gcode
  3453. job_obj.toolchange_xy_type = "geometry"
  3454. app_obj.progress.emit(80)
  3455. job_obj.cnc_tools.update({
  3456. tooluid_key: copy.deepcopy(dia_cnc_dict)
  3457. })
  3458. dia_cnc_dict.clear()
  3459. if use_thread:
  3460. # To be run in separate thread
  3461. # The idea is that if there is a solid_geometry in the file "root" then most likely thare are no
  3462. # separate solid_geometry in the self.tools dictionary
  3463. def job_thread(app_obj):
  3464. if self.solid_geometry:
  3465. with self.app.proc_container.new("Generating CNC Code"):
  3466. if app_obj.new_object("cncjob", outname, job_init_single_geometry) != 'fail':
  3467. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  3468. app_obj.progress.emit(100)
  3469. else:
  3470. with self.app.proc_container.new("Generating CNC Code"):
  3471. if app_obj.new_object("cncjob", outname, job_init_multi_geometry) != 'fail':
  3472. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  3473. app_obj.progress.emit(100)
  3474. # Create a promise with the name
  3475. self.app.collection.promise(outname)
  3476. # Send to worker
  3477. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3478. else:
  3479. if self.solid_geometry:
  3480. self.app.new_object("cncjob", outname, job_init_single_geometry)
  3481. else:
  3482. self.app.new_object("cncjob", outname, job_init_multi_geometry)
  3483. def generatecncjob(self, outname=None,
  3484. tooldia=None, offset=None,
  3485. z_cut=None, z_move=None,
  3486. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  3487. spindlespeed=None, dwell=None, dwelltime=None,
  3488. multidepth=None, depthperpass=None,
  3489. toolchange=None, toolchangez=None, toolchangexy=None,
  3490. extracut=None, startz=None, endz=None,
  3491. ppname_g=None,
  3492. segx=None,
  3493. segy=None,
  3494. use_thread=True):
  3495. """
  3496. Only used for TCL Command.
  3497. Creates a CNCJob out of this Geometry object. The actual
  3498. work is done by the target FlatCAMCNCjob object's
  3499. `generate_from_geometry_2()` method.
  3500. :param z_cut: Cut depth (negative)
  3501. :param z_move: Hight of the tool when travelling (not cutting)
  3502. :param feedrate: Feed rate while cutting on X - Y plane
  3503. :param feedrate_z: Feed rate while cutting on Z plane
  3504. :param feedrate_rapid: Feed rate while moving with rapids
  3505. :param tooldia: Tool diameter
  3506. :param outname: Name of the new object
  3507. :param spindlespeed: Spindle speed (RPM)
  3508. :param ppname_g Name of the postprocessor
  3509. :return: None
  3510. """
  3511. tooldia = tooldia if tooldia else float(self.options["cnctooldia"])
  3512. outname = outname if outname is not None else self.options["name"]
  3513. z_cut = z_cut if z_cut is not None else float(self.options["cutz"])
  3514. z_move = z_move if z_move is not None else float(self.options["travelz"])
  3515. feedrate = feedrate if feedrate is not None else float(self.options["feedrate"])
  3516. feedrate_z = feedrate_z if feedrate_z is not None else float(self.options["feedrate_z"])
  3517. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else float(self.options["feedrate_rapid"])
  3518. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  3519. depthperpass = depthperpass if depthperpass is not None else float(self.options["depthperpass"])
  3520. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  3521. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  3522. extracut = extracut if extracut is not None else float(self.options["extracut"])
  3523. startz = startz if startz is not None else self.options["startz"]
  3524. endz = endz if endz is not None else float(self.options["endz"])
  3525. toolchangez = toolchangez if toolchangez else float(self.options["toolchangez"])
  3526. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  3527. toolchange = toolchange if toolchange else self.options["toolchange"]
  3528. offset = offset if offset else 0.0
  3529. # int or None.
  3530. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  3531. dwell = dwell if dwell else self.options["dwell"]
  3532. dwelltime = dwelltime if dwelltime else float(self.options["dwelltime"])
  3533. ppname_g = ppname_g if ppname_g else self.options["ppname_g"]
  3534. # Object initialization function for app.new_object()
  3535. # RUNNING ON SEPARATE THREAD!
  3536. def job_init(job_obj, app_obj):
  3537. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3538. # Propagate options
  3539. job_obj.options["tooldia"] = tooldia
  3540. app_obj.progress.emit(20)
  3541. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3542. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3543. app_obj.progress.emit(40)
  3544. job_obj.options['type'] = 'Geometry'
  3545. job_obj.options['tool_dia'] = tooldia
  3546. job_obj.segx = segx
  3547. job_obj.segy = segy
  3548. try:
  3549. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3550. except ValueError:
  3551. # try to convert comma to decimal point. if it's still not working error message and return
  3552. try:
  3553. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3554. except ValueError:
  3555. self.app.inform.emit(
  3556. '[ERROR_NOTCL]Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]')
  3557. try:
  3558. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3559. except ValueError:
  3560. # try to convert comma to decimal point. if it's still not working error message and return
  3561. try:
  3562. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3563. except ValueError:
  3564. self.app.inform.emit(
  3565. '[ERROR_NOTCL]Wrong value format for self.defaults["feedrate_probe"] '
  3566. 'or self.options["feedrate_probe"]')
  3567. # TODO: The tolerance should not be hard coded. Just for testing.
  3568. job_obj.generate_from_geometry_2(self, tooldia=tooldia, offset=offset, tolerance=0.0005,
  3569. z_cut=z_cut, z_move=z_move,
  3570. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3571. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  3572. multidepth=multidepth, depthpercut=depthperpass,
  3573. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3574. extracut=extracut, startz=startz, endz=endz,
  3575. pp_geometry_name=ppname_g
  3576. )
  3577. app_obj.progress.emit(50)
  3578. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  3579. # source of gcode
  3580. job_obj.toolchange_xy_type = "geometry"
  3581. job_obj.gcode_parse()
  3582. app_obj.progress.emit(80)
  3583. if use_thread:
  3584. # To be run in separate thread
  3585. def job_thread(app_obj):
  3586. with self.app.proc_container.new("Generating CNC Code"):
  3587. app_obj.new_object("cncjob", outname, job_init)
  3588. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  3589. app_obj.progress.emit(100)
  3590. # Create a promise with the name
  3591. self.app.collection.promise(outname)
  3592. # Send to worker
  3593. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3594. else:
  3595. self.app.new_object("cncjob", outname, job_init)
  3596. # def on_plot_cb_click(self, *args): # TODO: args not needed
  3597. # if self.muted_ui:
  3598. # return
  3599. # self.read_form_item('plot')
  3600. def scale(self, xfactor, yfactor=None, point=None):
  3601. """
  3602. Scales all geometry by a given factor.
  3603. :param xfactor: Factor by which to scale the object's geometry/
  3604. :type xfactor: float
  3605. :param yfactor: Factor by which to scale the object's geometry/
  3606. :type yfactor: float
  3607. :return: None
  3608. :rtype: None
  3609. """
  3610. try:
  3611. xfactor = float(xfactor)
  3612. except:
  3613. self.app.inform.emit("[ERROR_NOTCL] Scale factor has to be a number: integer or float.")
  3614. return
  3615. if yfactor is None:
  3616. yfactor = xfactor
  3617. else:
  3618. try:
  3619. yfactor = float(yfactor)
  3620. except:
  3621. self.app.inform.emit("[ERROR_NOTCL] Scale factor has to be a number: integer or float.")
  3622. return
  3623. if point is None:
  3624. px = 0
  3625. py = 0
  3626. else:
  3627. px, py = point
  3628. # if type(self.solid_geometry) == list:
  3629. # geo_list = self.flatten(self.solid_geometry)
  3630. # self.solid_geometry = []
  3631. # # for g in geo_list:
  3632. # # self.solid_geometry.append(affinity.scale(g, xfactor, yfactor, origin=(px, py)))
  3633. # self.solid_geometry = [affinity.scale(g, xfactor, yfactor, origin=(px, py))
  3634. # for g in geo_list]
  3635. # else:
  3636. # self.solid_geometry = affinity.scale(self.solid_geometry, xfactor, yfactor,
  3637. # origin=(px, py))
  3638. # self.app.inform.emit("[success]Geometry Scale done.")
  3639. def scale_recursion(geom):
  3640. if type(geom) == list:
  3641. geoms=list()
  3642. for local_geom in geom:
  3643. geoms.append(scale_recursion(local_geom))
  3644. return geoms
  3645. else:
  3646. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  3647. if self.multigeo is True:
  3648. for tool in self.tools:
  3649. self.tools[tool]['solid_geometry'] = scale_recursion(self.tools[tool]['solid_geometry'])
  3650. else:
  3651. self.solid_geometry=scale_recursion(self.solid_geometry)
  3652. self.app.inform.emit("[success]Geometry Scale done.")
  3653. def offset(self, vect):
  3654. """
  3655. Offsets all geometry by a given vector/
  3656. :param vect: (x, y) vector by which to offset the object's geometry.
  3657. :type vect: tuple
  3658. :return: None
  3659. :rtype: None
  3660. """
  3661. try:
  3662. dx, dy = vect
  3663. except TypeError:
  3664. self.app.inform.emit("[ERROR_NOTCL]An (x,y) pair of values are needed. "
  3665. "Probable you entered only one value in the Offset field.")
  3666. return
  3667. def translate_recursion(geom):
  3668. if type(geom) == list:
  3669. geoms=list()
  3670. for local_geom in geom:
  3671. geoms.append(translate_recursion(local_geom))
  3672. return geoms
  3673. else:
  3674. return affinity.translate(geom, xoff=dx, yoff=dy)
  3675. if self.multigeo is True:
  3676. for tool in self.tools:
  3677. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  3678. else:
  3679. self.solid_geometry=translate_recursion(self.solid_geometry)
  3680. self.app.inform.emit("[success]Geometry Offset done.")
  3681. def convert_units(self, units):
  3682. self.ui_disconnect()
  3683. factor = Geometry.convert_units(self, units)
  3684. self.options['cutz'] = float(self.options['cutz']) * factor
  3685. self.options['depthperpass'] = float(self.options['depthperpass']) * factor
  3686. self.options['travelz'] = float(self.options['travelz']) * factor
  3687. self.options['feedrate'] = float(self.options['feedrate']) * factor
  3688. self.options['feedrate_z'] = float(self.options['feedrate_z']) * factor
  3689. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  3690. self.options['endz'] = float(self.options['endz']) * factor
  3691. # self.options['cnctooldia'] *= factor
  3692. # self.options['painttooldia'] *= factor
  3693. # self.options['paintmargin'] *= factor
  3694. # self.options['paintoverlap'] *= factor
  3695. self.options["toolchangez"] = float(self.options["toolchangez"]) * factor
  3696. if self.app.defaults["geometry_toolchangexy"] == '':
  3697. self.options['toolchangexy'] = "0.0, 0.0"
  3698. else:
  3699. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  3700. if len(coords_xy) < 2:
  3701. self.app.inform.emit("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  3702. "in the format (x, y) \nbut now there is only one value, not two. ")
  3703. return 'fail'
  3704. coords_xy[0] *= factor
  3705. coords_xy[1] *= factor
  3706. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3707. if self.options['startz'] is not None:
  3708. self.options['startz'] = float(self.options['startz']) * factor
  3709. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  3710. 'endz', 'toolchangez']
  3711. if isinstance(self, FlatCAMGeometry):
  3712. temp_tools_dict = {}
  3713. tool_dia_copy = {}
  3714. data_copy = {}
  3715. for tooluid_key, tooluid_value in self.tools.items():
  3716. for dia_key, dia_value in tooluid_value.items():
  3717. if dia_key == 'tooldia':
  3718. dia_value *= factor
  3719. dia_value = float('%.4f' % dia_value)
  3720. tool_dia_copy[dia_key] = dia_value
  3721. if dia_key == 'offset':
  3722. tool_dia_copy[dia_key] = dia_value
  3723. if dia_key == 'offset_value':
  3724. dia_value *= factor
  3725. tool_dia_copy[dia_key] = dia_value
  3726. # convert the value in the Custom Tool Offset entry in UI
  3727. custom_offset = None
  3728. try:
  3729. custom_offset = float(self.ui.tool_offset_entry.get_value())
  3730. except ValueError:
  3731. # try to convert comma to decimal point. if it's still not working error message and return
  3732. try:
  3733. custom_offset = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3734. )
  3735. except ValueError:
  3736. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  3737. "use a number.")
  3738. return
  3739. except TypeError:
  3740. pass
  3741. if custom_offset:
  3742. custom_offset *= factor
  3743. self.ui.tool_offset_entry.set_value(custom_offset)
  3744. if dia_key == 'type':
  3745. tool_dia_copy[dia_key] = dia_value
  3746. if dia_key == 'tool_type':
  3747. tool_dia_copy[dia_key] = dia_value
  3748. if dia_key == 'data':
  3749. for data_key, data_value in dia_value.items():
  3750. # convert the form fields that are convertible
  3751. for param in param_list:
  3752. if data_key == param and data_value is not None:
  3753. data_copy[data_key] = data_value * factor
  3754. # copy the other dict entries that are not convertible
  3755. if data_key not in param_list:
  3756. data_copy[data_key] = data_value
  3757. tool_dia_copy[dia_key] = copy.deepcopy(data_copy)
  3758. data_copy.clear()
  3759. temp_tools_dict.update({
  3760. tooluid_key: copy.deepcopy(tool_dia_copy)
  3761. })
  3762. tool_dia_copy.clear()
  3763. self.tools.clear()
  3764. self.tools = copy.deepcopy(temp_tools_dict)
  3765. # if there is a value in the new tool field then convert that one too
  3766. tooldia = self.ui.addtool_entry.get_value()
  3767. if tooldia:
  3768. tooldia *= factor
  3769. # limit the decimals to 2 for METRIC and 3 for INCH
  3770. if units.lower() == 'in':
  3771. tooldia = float('%.4f' % tooldia)
  3772. else:
  3773. tooldia = float('%.2f' % tooldia)
  3774. self.ui.addtool_entry.set_value(tooldia)
  3775. return factor
  3776. def plot_element(self, element, color='red', visible=None):
  3777. visible = visible if visible else self.options['plot']
  3778. try:
  3779. for sub_el in element:
  3780. self.plot_element(sub_el)
  3781. except TypeError: # Element is not iterable...
  3782. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  3783. def plot(self, visible=None):
  3784. """
  3785. Adds the object into collection.
  3786. :return: None
  3787. """
  3788. # Does all the required setup and returns False
  3789. # if the 'ptint' option is set to False.
  3790. if not FlatCAMObj.plot(self):
  3791. return
  3792. try:
  3793. # plot solid geometries found as members of self.tools attribute dict
  3794. # for MultiGeo
  3795. if self.multigeo == True: # geo multi tool usage
  3796. for tooluid_key in self.tools:
  3797. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  3798. self.plot_element(solid_geometry, visible=visible)
  3799. # plot solid geometry that may be an direct attribute of the geometry object
  3800. # for SingleGeo
  3801. if self.solid_geometry:
  3802. self.plot_element(self.solid_geometry, visible=visible)
  3803. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  3804. self.shapes.redraw()
  3805. except (ObjectDeleted, AttributeError):
  3806. self.shapes.clear(update=True)
  3807. def on_plot_cb_click(self, *args):
  3808. if self.muted_ui:
  3809. return
  3810. self.plot()
  3811. self.read_form_item('plot')
  3812. self.ui_disconnect()
  3813. cb_flag = self.ui.plot_cb.isChecked()
  3814. for row in range(self.ui.geo_tools_table.rowCount()):
  3815. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  3816. if cb_flag:
  3817. table_cb.setChecked(True)
  3818. else:
  3819. table_cb.setChecked(False)
  3820. self.ui_connect()
  3821. def on_plot_cb_click_table(self):
  3822. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  3823. self.ui_disconnect()
  3824. cw = self.sender()
  3825. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  3826. cw_row = cw_index.row()
  3827. check_row = 0
  3828. self.shapes.clear(update=True)
  3829. for tooluid_key in self.tools:
  3830. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  3831. # find the geo_tool_table row associated with the tooluid_key
  3832. for row in range(self.ui.geo_tools_table.rowCount()):
  3833. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  3834. if tooluid_item == int(tooluid_key):
  3835. check_row = row
  3836. break
  3837. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  3838. self.plot_element(element=solid_geometry, visible=True)
  3839. self.shapes.redraw()
  3840. # make sure that the general plot is disabled if one of the row plot's are disabled and
  3841. # if all the row plot's are enabled also enable the general plot checkbox
  3842. cb_cnt = 0
  3843. total_row = self.ui.geo_tools_table.rowCount()
  3844. for row in range(total_row):
  3845. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  3846. cb_cnt += 1
  3847. else:
  3848. cb_cnt -= 1
  3849. if cb_cnt < total_row:
  3850. self.ui.plot_cb.setChecked(False)
  3851. else:
  3852. self.ui.plot_cb.setChecked(True)
  3853. self.ui_connect()
  3854. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  3855. """
  3856. Represents G-Code.
  3857. """
  3858. optionChanged = QtCore.pyqtSignal(str)
  3859. ui_type = CNCObjectUI
  3860. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  3861. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  3862. spindlespeed=None):
  3863. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  3864. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  3865. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  3866. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  3867. FlatCAMObj.__init__(self, name)
  3868. self.kind = "cncjob"
  3869. self.options.update({
  3870. "plot": True,
  3871. "tooldia": 0.03937, # 0.4mm in inches
  3872. "append": "",
  3873. "prepend": "",
  3874. "dwell": False,
  3875. "dwelltime": 1,
  3876. "type": 'Geometry'
  3877. })
  3878. '''
  3879. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  3880. diameter of the tools and the value is another dict that will hold the data under the following form:
  3881. {tooldia: {
  3882. 'tooluid': 1,
  3883. 'offset': 'Path',
  3884. 'type_item': 'Rough',
  3885. 'tool_type': 'C1',
  3886. 'data': {} # a dict to hold the parameters
  3887. 'gcode': "" # a string with the actual GCODE
  3888. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  3889. 'solid_geometry': []
  3890. },
  3891. ...
  3892. }
  3893. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  3894. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  3895. '''
  3896. self.cnc_tools = {}
  3897. '''
  3898. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  3899. diameter of the tools and the value is another dict that will hold the data under the following form:
  3900. {tooldia: {
  3901. 'tool': int,
  3902. 'nr_drills': int,
  3903. 'nr_slots': int,
  3904. 'offset': float,
  3905. 'data': {} # a dict to hold the parameters
  3906. 'gcode': "" # a string with the actual GCODE
  3907. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  3908. 'solid_geometry': []
  3909. },
  3910. ...
  3911. }
  3912. It is populated in the FlatCAMExcellon.on_create_cncjob_click() but actually
  3913. it's done in camlib.Excellon.generate_from_excellon_by_tool()
  3914. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  3915. '''
  3916. self.exc_cnc_tools = {}
  3917. # flag to store if the CNCJob is part of a special group of CNCJob objects that can't be processed by the
  3918. # default engine of FlatCAM. They generated by some of tools and are special cases of CNCJob objects.
  3919. self. special_group = None
  3920. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  3921. # (like the one in the TCL Command), False
  3922. self.multitool = False
  3923. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  3924. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  3925. self.g_x_re = re.compile(gcodex_re_string)
  3926. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  3927. self.g_y_re = re.compile(gcodey_re_string)
  3928. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  3929. self.g_z_re = re.compile(gcodez_re_string)
  3930. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  3931. self.g_f_re = re.compile(gcodef_re_string)
  3932. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  3933. self.g_t_re = re.compile(gcodet_re_string)
  3934. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  3935. self.g_nr_re = re.compile(gcodenr_re_string)
  3936. # Attributes to be included in serialization
  3937. # Always append to it because it carries contents
  3938. # from predecessors.
  3939. self.ser_attrs += ['options', 'kind', 'cnc_tools', 'multitool']
  3940. self.annotation = self.app.plotcanvas.new_text_group()
  3941. def build_ui(self):
  3942. self.ui_disconnect()
  3943. FlatCAMObj.build_ui(self)
  3944. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  3945. if self.cnc_tools:
  3946. self.ui.cnc_tools_table.show()
  3947. else:
  3948. self.ui.cnc_tools_table.hide()
  3949. offset = 0
  3950. tool_idx = 0
  3951. n = len(self.cnc_tools)
  3952. self.ui.cnc_tools_table.setRowCount(n)
  3953. for dia_key, dia_value in self.cnc_tools.items():
  3954. tool_idx += 1
  3955. row_no = tool_idx - 1
  3956. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  3957. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  3958. self.ui.cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  3959. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  3960. # There are no tool bits in MM with more than 2 decimals diameter.
  3961. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  3962. if self.units == 'MM':
  3963. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(dia_value['tooldia']))
  3964. else:
  3965. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(dia_value['tooldia']))
  3966. offset_txt = list(str(dia_value['offset']))
  3967. offset_txt[0] = offset_txt[0].upper()
  3968. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  3969. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  3970. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  3971. id.setFlags(QtCore.Qt.ItemIsEnabled)
  3972. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3973. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3974. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3975. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3976. # hack so the checkbox stay centered in the table cell
  3977. # used this:
  3978. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  3979. # plot_item = QtWidgets.QWidget()
  3980. # checkbox = FCCheckBox()
  3981. # checkbox.setCheckState(QtCore.Qt.Checked)
  3982. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  3983. # qhboxlayout.addWidget(checkbox)
  3984. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  3985. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  3986. plot_item = FCCheckBox()
  3987. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  3988. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  3989. if self.ui.plot_cb.isChecked():
  3990. plot_item.setChecked(True)
  3991. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  3992. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  3993. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  3994. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  3995. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  3996. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  3997. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  3998. # make the diameter column editable
  3999. # for row in range(tool_idx):
  4000. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  4001. # QtCore.Qt.ItemIsEnabled)
  4002. for row in range(tool_idx):
  4003. self.ui.cnc_tools_table.item(row, 0).setFlags(
  4004. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  4005. self.ui.cnc_tools_table.resizeColumnsToContents()
  4006. self.ui.cnc_tools_table.resizeRowsToContents()
  4007. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  4008. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  4009. vertical_header.hide()
  4010. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4011. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  4012. horizontal_header.setMinimumSectionSize(10)
  4013. horizontal_header.setDefaultSectionSize(70)
  4014. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  4015. horizontal_header.resizeSection(0, 20)
  4016. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  4017. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  4018. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  4019. horizontal_header.resizeSection(4, 40)
  4020. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  4021. horizontal_header.resizeSection(4, 17)
  4022. # horizontal_header.setStretchLastSection(True)
  4023. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4024. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  4025. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  4026. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  4027. # self.ui.geo_tools_table.setSortingEnabled(True)
  4028. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  4029. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  4030. self.ui_connect()
  4031. def set_ui(self, ui):
  4032. FlatCAMObj.set_ui(self, ui)
  4033. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  4034. assert isinstance(self.ui, CNCObjectUI), \
  4035. "Expected a CNCObjectUI, got %s" % type(self.ui)
  4036. self.form_fields.update({
  4037. "plot": self.ui.plot_cb,
  4038. # "tooldia": self.ui.tooldia_entry,
  4039. "append": self.ui.append_text,
  4040. "prepend": self.ui.prepend_text,
  4041. })
  4042. # Fill form fields only on object create
  4043. self.to_form()
  4044. # this means that the object that created this CNCJob was an Excellon
  4045. try:
  4046. if self.travel_distance:
  4047. self.ui.t_distance_label.show()
  4048. self.ui.t_distance_entry.setVisible(True)
  4049. self.ui.t_distance_entry.setDisabled(True)
  4050. self.ui.t_distance_entry.set_value('%.4f' % float(self.travel_distance))
  4051. self.ui.units_label.setText(str(self.units).lower())
  4052. self.ui.units_label.setDisabled(True)
  4053. except AttributeError:
  4054. pass
  4055. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  4056. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  4057. # Show/Hide Advanced Options
  4058. if self.app.defaults["global_app_level"] == 'b':
  4059. self.ui.level.setText('<span style="color:green;"><b>Basic</b></span>')
  4060. else:
  4061. self.ui.level.setText('<span style="color:red;"><b>Advanced</b></span>')
  4062. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  4063. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  4064. self.ui.modify_gcode_button.clicked.connect(self.on_modifygcode_button_click)
  4065. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  4066. def ui_connect(self):
  4067. for row in range(self.ui.cnc_tools_table.rowCount()):
  4068. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  4069. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  4070. def ui_disconnect(self):
  4071. for row in range(self.ui.cnc_tools_table.rowCount()):
  4072. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  4073. try:
  4074. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  4075. except:
  4076. pass
  4077. def on_updateplot_button_click(self, *args):
  4078. """
  4079. Callback for the "Updata Plot" button. Reads the form for updates
  4080. and plots the object.
  4081. """
  4082. self.read_form()
  4083. self.plot()
  4084. def on_plot_kind_change(self):
  4085. kind = self.ui.cncplot_method_combo.get_value()
  4086. self.plot(kind=kind)
  4087. def on_exportgcode_button_click(self, *args):
  4088. self.app.report_usage("cncjob_on_exportgcode_button")
  4089. self.read_form()
  4090. name = self.app.collection.get_active().options['name']
  4091. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4092. _filter_ = "RML1 Files (*.rol);;" \
  4093. "All Files (*.*)"
  4094. elif 'hpgl' in self.pp_geometry_name:
  4095. _filter_ = "HPGL Files (*.plt);;" \
  4096. "All Files (*.*)"
  4097. else:
  4098. _filter_ = "G-Code Files (*.nc);;G-Code Files (*.txt);;G-Code Files (*.tap);;G-Code Files (*.cnc);;" \
  4099. "G-Code Files (*.g-code);;All Files (*.*)"
  4100. try:
  4101. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  4102. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4103. caption="Export Machine Code ...",
  4104. directory=dir_file_to_save,
  4105. filter=_filter_
  4106. )
  4107. except TypeError:
  4108. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Machine Code ...", filter=_filter_)
  4109. filename = str(filename)
  4110. if filename == '':
  4111. self.app.inform.emit("[WARNING_NOTCL]Export Machine Code cancelled ...")
  4112. return
  4113. preamble = str(self.ui.prepend_text.get_value())
  4114. postamble = str(self.ui.append_text.get_value())
  4115. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  4116. if gc == 'fail':
  4117. return
  4118. self.app.file_saved.emit("gcode", filename)
  4119. self.app.inform.emit("[success] Machine Code file saved to: %s" % filename)
  4120. def on_modifygcode_button_click(self, *args):
  4121. preamble = str(self.ui.prepend_text.get_value())
  4122. postamble = str(self.ui.append_text.get_value())
  4123. gc = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  4124. if gc == 'fail':
  4125. return
  4126. else:
  4127. self.app.gcode_edited = gc
  4128. # add the tab if it was closed
  4129. self.app.ui.plot_tab_area.addTab(self.app.ui.cncjob_tab, "Code Editor")
  4130. # delete the absolute and relative position and messages in the infobar
  4131. self.app.ui.position_label.setText("")
  4132. self.app.ui.rel_position_label.setText("")
  4133. # Switch plot_area to CNCJob tab
  4134. self.app.ui.plot_tab_area.setCurrentWidget(self.app.ui.cncjob_tab)
  4135. # first clear previous text in text editor (if any)
  4136. self.app.ui.code_editor.clear()
  4137. # then append the text from GCode to the text editor
  4138. try:
  4139. for line in self.app.gcode_edited:
  4140. proc_line = str(line).strip('\n')
  4141. self.app.ui.code_editor.append(proc_line)
  4142. except Exception as e:
  4143. log.debug('FlatCAMCNNJob.on_modifygcode_button_click() -->%s' % str(e))
  4144. self.app.inform.emit('[ERROR]FlatCAMCNNJob.on_modifygcode_button_click() -->%s' % str(e))
  4145. return
  4146. self.app.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4147. self.app.handleTextChanged()
  4148. self.app.ui.show()
  4149. def gcode_header(self):
  4150. log.debug("FlatCAMCNCJob.gcode_header()")
  4151. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4152. marlin = False
  4153. hpgl = False
  4154. probe_pp = False
  4155. try:
  4156. for key in self.cnc_tools:
  4157. ppg = self.cnc_tools[key]['data']['ppname_g']
  4158. if ppg == 'marlin' or ppg == 'Repetier':
  4159. marlin = True
  4160. break
  4161. if ppg == 'hpgl':
  4162. hpgl = True
  4163. break
  4164. if "toolchange_probe" in ppg.lower():
  4165. probe_pp = True
  4166. break
  4167. except Exception as e:
  4168. log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  4169. try:
  4170. if self.options['ppname_e'] == 'marlin' or self.options['ppname_e'] == 'Repetier':
  4171. marlin = True
  4172. except Exception as e:
  4173. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4174. try:
  4175. if "toolchange_probe" in self.options['ppname_e'].lower():
  4176. probe_pp = True
  4177. except Exception as e:
  4178. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4179. if marlin is True:
  4180. gcode = ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4181. (str(self.app.version), str(self.app.version_date)) + '\n'
  4182. gcode += ';Name: ' + str(self.options['name']) + '\n'
  4183. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  4184. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4185. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4186. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  4187. gcode += ';Created on ' + time_str + '\n' + '\n'
  4188. elif hpgl is True:
  4189. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  4190. (str(self.app.version), str(self.app.version_date)) + '";\n'
  4191. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  4192. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  4193. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4194. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4195. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  4196. gcode += 'CO "Created on ' + time_str + '";\n'
  4197. elif probe_pp is True:
  4198. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4199. (str(self.app.version), str(self.app.version_date)) + '\n'
  4200. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  4201. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  4202. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  4203. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  4204. 'Then zero the Z axis.)\n' + '\n'
  4205. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4206. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4207. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4208. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4209. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4210. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4211. else:
  4212. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4213. (str(self.app.version), str(self.app.version_date)) + '\n'
  4214. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4215. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4216. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4217. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4218. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4219. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4220. return gcode
  4221. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  4222. gcode = ''
  4223. roland = False
  4224. hpgl = False
  4225. try:
  4226. if self.special_group:
  4227. self.app.inform.emit("[WARNING_NOTCL]This CNCJob object can't be processed because "
  4228. "it is a %s CNCJob object." % str(self.special_group))
  4229. return 'fail'
  4230. except AttributeError:
  4231. pass
  4232. # detect if using Roland postprocessor
  4233. try:
  4234. for key in self.cnc_tools:
  4235. if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  4236. roland = True
  4237. break
  4238. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  4239. hpgl = True
  4240. break
  4241. except:
  4242. try:
  4243. for key in self.cnc_tools:
  4244. if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  4245. roland = True
  4246. break
  4247. except:
  4248. pass
  4249. # do not add gcode_header when using the Roland postprocessor, add it for every other postprocessor
  4250. if roland is False and hpgl is False:
  4251. gcode = self.gcode_header()
  4252. # detect if using multi-tool and make the Gcode summation correctly for each case
  4253. if self.multitool is True:
  4254. for tooluid_key in self.cnc_tools:
  4255. for key, value in self.cnc_tools[tooluid_key].items():
  4256. if key == 'gcode':
  4257. gcode += value
  4258. break
  4259. else:
  4260. gcode += self.gcode
  4261. if roland is True:
  4262. g = preamble + gcode + postamble
  4263. elif hpgl is True:
  4264. g = self.gcode_header() + preamble + gcode + postamble
  4265. else:
  4266. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  4267. g_idx = gcode.rfind('G20')
  4268. # if it did not find 'G20' then search for 'G21'
  4269. if g_idx == -1:
  4270. g_idx = gcode.rfind('G21')
  4271. # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  4272. if g_idx == -1:
  4273. self.app.inform.emit("[ERROR_NOTCL] G-code does not have a units code: either G20 or G21")
  4274. return
  4275. g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble
  4276. # lines = StringIO(self.gcode)
  4277. lines = StringIO(g)
  4278. ## Write
  4279. if filename is not None:
  4280. try:
  4281. with open(filename, 'w') as f:
  4282. for line in lines:
  4283. f.write(line)
  4284. except FileNotFoundError:
  4285. self.app.inform.emit("[WARNING_NOTCL] No such file or directory")
  4286. return
  4287. elif to_file is False:
  4288. # Just for adding it to the recent files list.
  4289. self.app.file_opened.emit("cncjob", filename)
  4290. self.app.file_saved.emit("cncjob", filename)
  4291. self.app.inform.emit("[success] Saved to: " + filename)
  4292. else:
  4293. return lines
  4294. def get_gcode(self, preamble='', postamble=''):
  4295. #we need this to be able get_gcode separatelly for shell command export_gcode
  4296. return preamble + '\n' + self.gcode + "\n" + postamble
  4297. def get_svg(self):
  4298. # we need this to be able get_svg separately for shell command export_svg
  4299. pass
  4300. def on_plot_cb_click(self, *args):
  4301. if self.muted_ui:
  4302. return
  4303. kind = self.ui.cncplot_method_combo.get_value()
  4304. self.plot(kind=kind)
  4305. self.read_form_item('plot')
  4306. self.ui_disconnect()
  4307. cb_flag = self.ui.plot_cb.isChecked()
  4308. for row in range(self.ui.cnc_tools_table.rowCount()):
  4309. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  4310. if cb_flag:
  4311. table_cb.setChecked(True)
  4312. else:
  4313. table_cb.setChecked(False)
  4314. self.ui_connect()
  4315. def on_plot_cb_click_table(self):
  4316. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  4317. self.ui_disconnect()
  4318. cw = self.sender()
  4319. cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  4320. cw_row = cw_index.row()
  4321. kind = self.ui.cncplot_method_combo.get_value()
  4322. self.shapes.clear(update=True)
  4323. for tooluid_key in self.cnc_tools:
  4324. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4325. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4326. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  4327. for r in range(self.ui.cnc_tools_table.rowCount()):
  4328. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  4329. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  4330. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  4331. self.shapes.redraw()
  4332. # make sure that the general plot is disabled if one of the row plot's are disabled and
  4333. # if all the row plot's are enabled also enable the general plot checkbox
  4334. cb_cnt = 0
  4335. total_row = self.ui.cnc_tools_table.rowCount()
  4336. for row in range(total_row):
  4337. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  4338. cb_cnt += 1
  4339. else:
  4340. cb_cnt -= 1
  4341. if cb_cnt < total_row:
  4342. self.ui.plot_cb.setChecked(False)
  4343. else:
  4344. self.ui.plot_cb.setChecked(True)
  4345. self.ui_connect()
  4346. def plot(self, visible=None, kind='all'):
  4347. # Does all the required setup and returns False
  4348. # if the 'ptint' option is set to False.
  4349. if not FlatCAMObj.plot(self):
  4350. return
  4351. visible = visible if visible else self.options['plot']
  4352. try:
  4353. if self.multitool is False: # single tool usage
  4354. self.plot2(tooldia=float(self.options["tooldia"]), obj=self, visible=visible, kind=kind)
  4355. else:
  4356. # multiple tools usage
  4357. for tooluid_key in self.cnc_tools:
  4358. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4359. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4360. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  4361. self.shapes.redraw()
  4362. except (ObjectDeleted, AttributeError):
  4363. self.shapes.clear(update=True)
  4364. self.annotation.clear(update=True)
  4365. def convert_units(self, units):
  4366. factor = CNCjob.convert_units(self, units)
  4367. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  4368. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  4369. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  4370. 'endz', 'toolchangez']
  4371. temp_tools_dict = {}
  4372. tool_dia_copy = {}
  4373. data_copy = {}
  4374. for tooluid_key, tooluid_value in self.cnc_tools.items():
  4375. for dia_key, dia_value in tooluid_value.items():
  4376. if dia_key == 'tooldia':
  4377. dia_value *= factor
  4378. dia_value = float('%.4f' % dia_value)
  4379. tool_dia_copy[dia_key] = dia_value
  4380. if dia_key == 'offset':
  4381. tool_dia_copy[dia_key] = dia_value
  4382. if dia_key == 'offset_value':
  4383. dia_value *= factor
  4384. tool_dia_copy[dia_key] = dia_value
  4385. if dia_key == 'type':
  4386. tool_dia_copy[dia_key] = dia_value
  4387. if dia_key == 'tool_type':
  4388. tool_dia_copy[dia_key] = dia_value
  4389. if dia_key == 'data':
  4390. for data_key, data_value in dia_value.items():
  4391. # convert the form fields that are convertible
  4392. for param in param_list:
  4393. if data_key == param and data_value is not None:
  4394. data_copy[data_key] = data_value * factor
  4395. # copy the other dict entries that are not convertible
  4396. if data_key not in param_list:
  4397. data_copy[data_key] = data_value
  4398. tool_dia_copy[dia_key] = copy.deepcopy(data_copy)
  4399. data_copy.clear()
  4400. if dia_key == 'gcode':
  4401. tool_dia_copy[dia_key] = dia_value
  4402. if dia_key == 'gcode_parsed':
  4403. tool_dia_copy[dia_key] = dia_value
  4404. if dia_key == 'solid_geometry':
  4405. tool_dia_copy[dia_key] = dia_value
  4406. # if dia_key == 'solid_geometry':
  4407. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  4408. # if dia_key == 'gcode_parsed':
  4409. # for g in dia_value:
  4410. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  4411. #
  4412. # tool_dia_copy['gcode_parsed'] = copy.deepcopy(dia_value)
  4413. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  4414. temp_tools_dict.update({
  4415. tooluid_key: copy.deepcopy(tool_dia_copy)
  4416. })
  4417. tool_dia_copy.clear()
  4418. self.cnc_tools.clear()
  4419. self.cnc_tools = copy.deepcopy(temp_tools_dict)
  4420. # end of file