FlatCAMObj.py 224 KB

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