FlatCAMObj.py 258 KB

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