FlatCAMObj.py 259 KB

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