FlatCAMObj.py 252 KB

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