FlatCAMObj.py 240 KB

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