FlatCAMObj.py 233 KB

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