FlatCAMObj.py 354 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245
  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. # ##########################################################
  9. # File modified by: Marius Stanciu #
  10. # ##########################################################
  11. from shapely.geometry import Point, Polygon, MultiPolygon, MultiLineString, LineString, LinearRing
  12. from shapely.ops import cascaded_union
  13. import shapely.affinity as affinity
  14. from copy import deepcopy
  15. # from copy import copy
  16. from io import StringIO
  17. import traceback
  18. import inspect # TODO: For debugging only.
  19. from datetime import datetime
  20. from flatcamEditors.FlatCAMTextEditor import TextEditor
  21. from flatcamGUI.ObjectUI import *
  22. from flatcamGUI.GUIElements import FCFileSaveDialog
  23. from FlatCAMCommon import LoudDict
  24. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  25. from flatcamParsers.ParseExcellon import Excellon
  26. from flatcamParsers.ParseGerber import Gerber
  27. from camlib import Geometry, CNCjob
  28. # from flatcamGUI.VisPyVisuals import ShapeCollection
  29. import tkinter as tk
  30. import os
  31. import sys
  32. import itertools
  33. import ezdxf
  34. import math
  35. import numpy as np
  36. import gettext
  37. import FlatCAMTranslation as fcTranslate
  38. import builtins
  39. fcTranslate.apply_language('strings')
  40. if '_' not in builtins.__dict__:
  41. _ = gettext.gettext
  42. # Interrupts plotting process if FlatCAMObj has been deleted
  43. class ObjectDeleted(Exception):
  44. pass
  45. class ValidationError(Exception):
  46. def __init__(self, message, errors):
  47. super().__init__(message)
  48. self.errors = errors
  49. # #######################################
  50. # # FlatCAMObj ##
  51. # #######################################
  52. class FlatCAMObj(QtCore.QObject):
  53. """
  54. Base type of objects handled in FlatCAM. These become interactive
  55. in the GUI, can be plotted, and their options can be modified
  56. by the user in their respective forms.
  57. """
  58. # Instance of the application to which these are related.
  59. # The app should set this value.
  60. app = None
  61. # signal to plot a single object
  62. plot_single_object = QtCore.pyqtSignal()
  63. def __init__(self, name):
  64. """
  65. Constructor.
  66. :param name: Name of the object given by the user.
  67. :return: FlatCAMObj
  68. """
  69. QtCore.QObject.__init__(self)
  70. # View
  71. self.ui = None
  72. self.options = LoudDict(name=name)
  73. self.options.set_change_callback(self.on_options_change)
  74. self.form_fields = {}
  75. # store here the default data for Geometry Data
  76. self.default_data = {}
  77. # 2D mode
  78. # Axes must exist and be attached to canvas.
  79. self.axes = None
  80. self.kind = None # Override with proper name
  81. if self.app.is_legacy is False:
  82. self.shapes = self.app.plotcanvas.new_shape_group()
  83. # self.shapes = ShapeCollection(parent=self.app.plotcanvas.view.scene, pool=self.app.pool, layers=2)
  84. else:
  85. self.shapes = ShapeCollectionLegacy(obj=self, app=self.app, name=name)
  86. self.mark_shapes = {}
  87. self.item = None # Link with project view item
  88. self.muted_ui = False
  89. self.deleted = False
  90. try:
  91. self._drawing_tolerance = float(self.app.defaults["global_tolerance"]) if \
  92. self.app.defaults["global_tolerance"] else 0.01
  93. except ValueError:
  94. self._drawing_tolerance = 0.01
  95. self.isHovering = False
  96. self.notHovering = True
  97. # Flag to show if a selection shape is drawn
  98. self.selection_shape_drawn = False
  99. # self.units = 'IN'
  100. self.units = self.app.defaults['units']
  101. self.plot_single_object.connect(self.single_object_plot)
  102. def __del__(self):
  103. pass
  104. def __str__(self):
  105. return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
  106. def from_dict(self, d):
  107. """
  108. This supersedes ``from_dict`` in derived classes. Derived classes
  109. must inherit from FlatCAMObj first, then from derivatives of Geometry.
  110. ``self.options`` is only updated, not overwritten. This ensures that
  111. options set by the app do not vanish when reading the objects
  112. from a project file.
  113. :param d: Dictionary with attributes to set.
  114. :return: None
  115. """
  116. for attr in self.ser_attrs:
  117. if attr == 'options':
  118. self.options.update(d[attr])
  119. else:
  120. try:
  121. setattr(self, attr, d[attr])
  122. except KeyError:
  123. log.debug("FlatCAMObj.from_dict() --> KeyError: %s. "
  124. "Means that we are loading an old project that don't"
  125. "have all attributes in the latest FlatCAM." % str(attr))
  126. pass
  127. def on_options_change(self, key):
  128. # Update form on programmatically options change
  129. self.set_form_item(key)
  130. # Set object visibility
  131. if key == 'plot':
  132. self.visible = self.options['plot']
  133. self.optionChanged.emit(key)
  134. def set_ui(self, ui):
  135. self.ui = ui
  136. self.form_fields = {"name": self.ui.name_entry}
  137. assert isinstance(self.ui, ObjectUI)
  138. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  139. try:
  140. # it will raise an exception for those FlatCAM objects that do not build UI with the common elements
  141. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  142. except (TypeError, AttributeError):
  143. pass
  144. try:
  145. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  146. except (TypeError, AttributeError):
  147. pass
  148. try:
  149. self.ui.offsetvector_entry.returnPressed.connect(self.on_offset_button_click)
  150. except (TypeError, AttributeError):
  151. pass
  152. # Creates problems on focusOut
  153. try:
  154. self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  155. except (TypeError, AttributeError):
  156. pass
  157. # self.ui.skew_button.clicked.connect(self.on_skew_button_click)
  158. def build_ui(self):
  159. """
  160. Sets up the UI/form for this object. Show the UI
  161. in the App.
  162. :return: None
  163. :rtype: None
  164. """
  165. self.muted_ui = True
  166. log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  167. try:
  168. # HACK: disconnect the scale entry signal since on focus out event will trigger an undesired scale()
  169. # it seems that the takewidget() does generate a focus out event for the QDoubleSpinbox ...
  170. # and reconnect after the takeWidget() is done
  171. # self.ui.scale_entry.returnPressed.disconnect(self.on_scale_button_click)
  172. self.app.ui.selected_scroll_area.takeWidget()
  173. # self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  174. except Exception as e:
  175. self.app.log.debug("FlatCAMObj.build_ui() --> Nothing to remove: %s" % str(e))
  176. self.app.ui.selected_scroll_area.setWidget(self.ui)
  177. # self.ui.setMinimumWidth(100)
  178. # self.ui.setMaximumWidth(self.app.ui.selected_tab.sizeHint().width())
  179. self.muted_ui = False
  180. def on_name_activate(self, silent=None):
  181. old_name = copy(self.options["name"])
  182. new_name = self.ui.name_entry.get_value()
  183. if new_name != old_name:
  184. # update the SHELL auto-completer model data
  185. try:
  186. self.app.myKeywords.remove(old_name)
  187. self.app.myKeywords.append(new_name)
  188. self.app.shell._edit.set_model_data(self.app.myKeywords)
  189. self.app.ui.code_editor.set_model_data(self.app.myKeywords)
  190. except Exception:
  191. log.debug("on_name_activate() --> Could not remove the old object name from auto-completer model list")
  192. self.options["name"] = self.ui.name_entry.get_value()
  193. self.default_data["name"] = self.ui.name_entry.get_value()
  194. self.app.collection.update_view()
  195. if silent:
  196. self.app.inform.emit('[success] %s: %s %s: %s' % (
  197. _("Name changed from"), str(old_name), _("to"), str(new_name)
  198. )
  199. )
  200. def on_offset_button_click(self):
  201. self.app.report_usage("obj_on_offset_button")
  202. self.read_form()
  203. vector_val = self.ui.offsetvector_entry.get_value()
  204. def worker_task():
  205. with self.app.proc_container.new(_("Offsetting...")):
  206. self.offset(vector_val)
  207. self.app.proc_container.update_view_text('')
  208. with self.app.proc_container.new('%s...' % _("Plotting")):
  209. self.plot()
  210. self.app.object_changed.emit(self)
  211. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  212. def on_scale_button_click(self):
  213. self.read_form()
  214. try:
  215. factor = float(eval(self.ui.scale_entry.get_value()))
  216. except Exception as e:
  217. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scaling could not be executed."))
  218. log.debug("FlatCAMObj.on_scale_button_click() -- %s" % str(e))
  219. return
  220. if type(factor) != float:
  221. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scaling could not be executed."))
  222. # if factor is 1.0 do nothing, there is no point in scaling with a factor of 1.0
  223. if factor == 1.0:
  224. self.app.inform.emit('[success] %s' % _("Scale done."))
  225. return
  226. log.debug("FlatCAMObj.on_scale_button_click()")
  227. def worker_task():
  228. with self.app.proc_container.new(_("Scaling...")):
  229. self.scale(factor)
  230. self.app.inform.emit('[success] %s' % _("Scale done."))
  231. self.app.proc_container.update_view_text('')
  232. with self.app.proc_container.new('%s...' % _("Plotting")):
  233. self.plot()
  234. self.app.object_changed.emit(self)
  235. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  236. def on_skew_button_click(self):
  237. self.app.report_usage("obj_on_skew_button")
  238. self.read_form()
  239. x_angle = self.ui.xangle_entry.get_value()
  240. y_angle = self.ui.yangle_entry.get_value()
  241. def worker_task():
  242. with self.app.proc_container.new(_("Skewing...")):
  243. self.skew(x_angle, y_angle)
  244. self.app.proc_container.update_view_text('')
  245. with self.app.proc_container.new('%s...' % _("Plotting")):
  246. self.plot()
  247. self.app.object_changed.emit(self)
  248. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  249. def to_form(self):
  250. """
  251. Copies options to the UI form.
  252. :return: None
  253. """
  254. log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.to_form()")
  255. for option in self.options:
  256. try:
  257. self.set_form_item(option)
  258. except Exception:
  259. self.app.log.warning("Unexpected error:", sys.exc_info())
  260. def read_form(self):
  261. """
  262. Reads form into ``self.options``.
  263. :return: None
  264. :rtype: None
  265. """
  266. log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
  267. for option in self.options:
  268. try:
  269. self.read_form_item(option)
  270. except Exception:
  271. self.app.log.warning("Unexpected error:", sys.exc_info())
  272. def set_form_item(self, option):
  273. """
  274. Copies the specified option to the UI form.
  275. :param option: Name of the option (Key in ``self.options``).
  276. :type option: str
  277. :return: None
  278. """
  279. try:
  280. self.form_fields[option].set_value(self.options[option])
  281. except KeyError:
  282. # self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
  283. pass
  284. def read_form_item(self, option):
  285. """
  286. Reads the specified option from the UI form into ``self.options``.
  287. :param option: Name of the option.
  288. :type option: str
  289. :return: None
  290. """
  291. try:
  292. self.options[option] = self.form_fields[option].get_value()
  293. except KeyError:
  294. pass
  295. # self.app.log.warning("Failed to read option from field: %s" % option)
  296. def plot(self, kind=None):
  297. """
  298. Plot this object (Extend this method to implement the actual plotting).
  299. Call this in descendants before doing the plotting.
  300. :param kind: Used by only some of the FlatCAM objects
  301. :return: Whether to continue plotting or not depending on the "plot" option. Boolean
  302. """
  303. log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
  304. if self.deleted:
  305. return False
  306. self.clear()
  307. return True
  308. def single_object_plot(self):
  309. def plot_task():
  310. with self.app.proc_container.new('%s...' % _("Plotting")):
  311. self.plot()
  312. self.app.object_changed.emit(self)
  313. self.app.worker_task.emit({'fcn': plot_task, 'params': []})
  314. def serialize(self):
  315. """
  316. Returns a representation of the object as a dictionary so
  317. it can be later exported as JSON. Override this method.
  318. :return: Dictionary representing the object
  319. :rtype: dict
  320. """
  321. return
  322. def deserialize(self, obj_dict):
  323. """
  324. Re-builds an object from its serialized version.
  325. :param obj_dict: Dictionary representing a FlatCAMObj
  326. :type obj_dict: dict
  327. :return: None
  328. """
  329. return
  330. def add_shape(self, **kwargs):
  331. if self.deleted:
  332. raise ObjectDeleted()
  333. else:
  334. key = self.shapes.add(tolerance=self.drawing_tolerance, **kwargs)
  335. return key
  336. def add_mark_shape(self, apid, **kwargs):
  337. if self.deleted:
  338. raise ObjectDeleted()
  339. else:
  340. key = self.mark_shapes[apid].add(tolerance=self.drawing_tolerance, layer=0, **kwargs)
  341. return key
  342. def update_filters(self, last_ext, filter_string):
  343. """
  344. Will modify the filter string that is used when saving a file (a list of file extensions) to have the last
  345. used file extension as the first one in the special string
  346. :param last_ext: The file extension that was last used to save a file
  347. :param filter_string: A key in self.app.defaults that holds a string with the filter from QFileDialog
  348. used when saving a file
  349. :return: None
  350. """
  351. filters = copy(self.app.defaults[filter_string])
  352. filter_list = filters.split(';;')
  353. filter_list_enum_1 = enumerate(filter_list)
  354. # search for the last element in the filters which should always be "All Files (*.*)"
  355. last_elem = ''
  356. for elem in list(filter_list_enum_1):
  357. if '(*.*)' in elem[1]:
  358. last_elem = filter_list.pop(elem[0])
  359. filter_list_enum = enumerate(filter_list)
  360. for elem in list(filter_list_enum):
  361. if '.' + last_ext in elem[1]:
  362. used_ext = filter_list.pop(elem[0])
  363. # sort the extensions back
  364. filter_list.sort(key=lambda x: x.rpartition('.')[2])
  365. # add as a first element the last used extension
  366. filter_list.insert(0, used_ext)
  367. # add back the element that should always be the last (All Files)
  368. filter_list.append(last_elem)
  369. self.app.defaults[filter_string] = ';;'.join(filter_list)
  370. return
  371. @staticmethod
  372. def poly2rings(poly):
  373. return [poly.exterior] + [interior for interior in poly.interiors]
  374. @property
  375. def visible(self):
  376. return self.shapes.visible
  377. @visible.setter
  378. def visible(self, value, threaded=True):
  379. log.debug("FlatCAMObj.visible()")
  380. def worker_task(app_obj):
  381. self.shapes.visible = value
  382. if self.app.is_legacy is False:
  383. # Not all object types has annotations
  384. try:
  385. self.annotation.visible = value
  386. except Exception:
  387. pass
  388. if threaded is False:
  389. worker_task(app_obj=self.app)
  390. else:
  391. self.app.worker_task.emit({'fcn': worker_task, 'params': [self]})
  392. @property
  393. def drawing_tolerance(self):
  394. self.units = self.app.defaults['units'].upper()
  395. tol = self._drawing_tolerance if self.units == 'MM' or not self.units else self._drawing_tolerance / 25.4
  396. return tol
  397. @drawing_tolerance.setter
  398. def drawing_tolerance(self, value):
  399. self.units = self.app.defaults['units'].upper()
  400. self._drawing_tolerance = value if self.units == 'MM' or not self.units else value / 25.4
  401. def clear(self, update=False):
  402. self.shapes.clear(update)
  403. # Not all object types has annotations
  404. try:
  405. self.annotation.clear(update)
  406. except AttributeError:
  407. pass
  408. def delete(self):
  409. # Free resources
  410. del self.ui
  411. del self.options
  412. # Set flag
  413. self.deleted = True
  414. class FlatCAMGerber(FlatCAMObj, Gerber):
  415. """
  416. Represents Gerber code.
  417. """
  418. optionChanged = QtCore.pyqtSignal(str)
  419. replotApertures = QtCore.pyqtSignal()
  420. ui_type = GerberObjectUI
  421. def merge(self, grb_list, grb_final):
  422. """
  423. Merges the geometry of objects in geo_list into
  424. the geometry of geo_final.
  425. :param grb_list: List of FlatCAMGerber Objects to join.
  426. :param grb_final: Destination FlatCAMGeometry object.
  427. :return: None
  428. """
  429. if grb_final.solid_geometry is None:
  430. grb_final.solid_geometry = []
  431. grb_final.follow_geometry = []
  432. if not grb_final.apertures:
  433. grb_final.apertures = {}
  434. if type(grb_final.solid_geometry) is not list:
  435. grb_final.solid_geometry = [grb_final.solid_geometry]
  436. grb_final.follow_geometry = [grb_final.follow_geometry]
  437. for grb in grb_list:
  438. # Expand lists
  439. if type(grb) is list:
  440. FlatCAMGerber.merge(grb, grb_final)
  441. else: # If not list, just append
  442. for option in grb.options:
  443. if option != 'name':
  444. try:
  445. grb_final.options[option] = grb.options[option]
  446. except KeyError:
  447. log.warning("Failed to copy option.", option)
  448. try:
  449. for geos in grb.solid_geometry:
  450. grb_final.solid_geometry.append(geos)
  451. grb_final.follow_geometry.append(geos)
  452. except TypeError:
  453. grb_final.solid_geometry.append(grb.solid_geometry)
  454. grb_final.follow_geometry.append(grb.solid_geometry)
  455. for ap in grb.apertures:
  456. if ap not in grb_final.apertures:
  457. grb_final.apertures[ap] = grb.apertures[ap]
  458. else:
  459. # create a list of integers out of the grb.apertures keys and find the max of that value
  460. # then, the aperture duplicate is assigned an id value incremented with 1,
  461. # and finally made string because the apertures dict keys are strings
  462. max_ap = str(max([int(k) for k in grb_final.apertures.keys()]) + 1)
  463. grb_final.apertures[max_ap] = {}
  464. grb_final.apertures[max_ap]['geometry'] = []
  465. for k, v in grb.apertures[ap].items():
  466. grb_final.apertures[max_ap][k] = deepcopy(v)
  467. grb_final.solid_geometry = MultiPolygon(grb_final.solid_geometry)
  468. grb_final.follow_geometry = MultiPolygon(grb_final.follow_geometry)
  469. def __init__(self, name):
  470. self.decimals = self.app.decimals
  471. self.circle_steps = int(self.app.defaults["gerber_circle_steps"])
  472. Gerber.__init__(self, steps_per_circle=self.circle_steps)
  473. FlatCAMObj.__init__(self, name)
  474. self.kind = "gerber"
  475. # The 'name' is already in self.options from FlatCAMObj
  476. # Automatically updates the UI
  477. self.options.update({
  478. "plot": True,
  479. "multicolored": False,
  480. "solid": False,
  481. "tool_type": 'circular',
  482. "vtipdia": 0.1,
  483. "vtipangle": 30,
  484. "vcutz": -0.05,
  485. "isotooldia": 0.016,
  486. "isopasses": 1,
  487. "isooverlap": 15,
  488. "milling_type": "cl",
  489. "combine_passes": True,
  490. "noncoppermargin": 0.0,
  491. "noncopperrounded": False,
  492. "bboxmargin": 0.0,
  493. "bboxrounded": False,
  494. "aperture_display": False,
  495. "follow": False,
  496. "iso_scope": 'all',
  497. "iso_type": 'full'
  498. })
  499. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  500. self.iso_type = 2
  501. self.multigeo = False
  502. self.follow = False
  503. self.apertures_row = 0
  504. # store the source file here
  505. self.source_file = ""
  506. # list of rows with apertures plotted
  507. self.marked_rows = []
  508. # Mouse events
  509. self.mr = None
  510. self.mm = None
  511. self.mp = None
  512. # dict to store the polygons selected for isolation; key is the shape added to be plotted and value is the poly
  513. self.poly_dict = {}
  514. # store the status of grid snapping
  515. self.grid_status_memory = None
  516. self.units_found = self.app.defaults['units']
  517. self.fill_color = self.app.defaults['gerber_plot_fill']
  518. self.outline_color = self.app.defaults['gerber_plot_line']
  519. self.alpha_level = 'bf'
  520. # keep track if the UI is built so we don't have to build it every time
  521. self.ui_build = False
  522. # build only once the aperture storage (takes time)
  523. self.build_aperture_storage = False
  524. # Attributes to be included in serialization
  525. # Always append to it because it carries contents
  526. # from predecessors.
  527. self.ser_attrs += ['options', 'kind', 'fill_color', 'outline_color', 'alpha_level']
  528. def set_ui(self, ui):
  529. """
  530. Maps options with GUI inputs.
  531. Connects GUI events to methods.
  532. :param ui: GUI object.
  533. :type ui: GerberObjectUI
  534. :return: None
  535. """
  536. FlatCAMObj.set_ui(self, ui)
  537. log.debug("FlatCAMGerber.set_ui()")
  538. self.units = self.app.defaults['units'].upper()
  539. self.replotApertures.connect(self.on_mark_cb_click_table)
  540. self.form_fields.update({
  541. "plot": self.ui.plot_cb,
  542. "multicolored": self.ui.multicolored_cb,
  543. "solid": self.ui.solid_cb,
  544. "tool_type": self.ui.tool_type_radio,
  545. "vtipdia": self.ui.tipdia_spinner,
  546. "vtipangle": self.ui.tipangle_spinner,
  547. "vcutz": self.ui.cutz_spinner,
  548. "isotooldia": self.ui.iso_tool_dia_entry,
  549. "isopasses": self.ui.iso_width_entry,
  550. "isooverlap": self.ui.iso_overlap_entry,
  551. "milling_type": self.ui.milling_type_radio,
  552. "combine_passes": self.ui.combine_passes_cb,
  553. "noncoppermargin": self.ui.noncopper_margin_entry,
  554. "noncopperrounded": self.ui.noncopper_rounded_cb,
  555. "bboxmargin": self.ui.bbmargin_entry,
  556. "bboxrounded": self.ui.bbrounded_cb,
  557. "aperture_display": self.ui.aperture_table_visibility_cb,
  558. "follow": self.ui.follow_cb,
  559. "iso_scope": self.ui.iso_scope_radio,
  560. "iso_type": self.ui.iso_type_radio
  561. })
  562. # Fill form fields only on object create
  563. self.to_form()
  564. assert isinstance(self.ui, GerberObjectUI)
  565. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  566. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  567. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  568. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  569. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  570. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  571. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  572. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  573. self.ui.aperture_table_visibility_cb.stateChanged.connect(self.on_aperture_table_visibility_change)
  574. self.ui.follow_cb.stateChanged.connect(self.on_follow_cb_click)
  575. # set the model for the Area Exception comboboxes
  576. self.ui.obj_combo.setModel(self.app.collection)
  577. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  578. self.ui.obj_combo.is_last = True
  579. self.ui.obj_combo.obj_type = {
  580. _("Gerber"): "Gerber", _("Geometry"): "Geometry"
  581. }[self.ui.type_obj_combo.get_value()]
  582. self.on_type_obj_index_changed()
  583. self.ui.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  584. self.ui.tool_type_radio.activated_custom.connect(self.on_tool_type_change)
  585. # establish visibility for the GUI elements found in the slot function
  586. self.ui.tool_type_radio.activated_custom.emit(self.options['tool_type'])
  587. # Show/Hide Advanced Options
  588. if self.app.defaults["global_app_level"] == 'b':
  589. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  590. self.options['tool_type'] = 'circular'
  591. self.ui.tool_type_label.hide()
  592. self.ui.tool_type_radio.hide()
  593. # override the Preferences Value; in Basic mode the Tool Type is always Circular ('C1')
  594. self.ui.tool_type_radio.set_value('circular')
  595. self.ui.tipdialabel.hide()
  596. self.ui.tipdia_spinner.hide()
  597. self.ui.tipanglelabel.hide()
  598. self.ui.tipangle_spinner.hide()
  599. self.ui.cutzlabel.hide()
  600. self.ui.cutz_spinner.hide()
  601. self.ui.apertures_table_label.hide()
  602. self.ui.aperture_table_visibility_cb.hide()
  603. self.ui.milling_type_label.hide()
  604. self.ui.milling_type_radio.hide()
  605. self.ui.iso_type_label.hide()
  606. self.ui.iso_type_radio.hide()
  607. self.ui.follow_cb.hide()
  608. self.ui.except_cb.setChecked(False)
  609. self.ui.except_cb.hide()
  610. else:
  611. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  612. self.ui.tipdia_spinner.valueChanged.connect(self.on_calculate_tooldia)
  613. self.ui.tipangle_spinner.valueChanged.connect(self.on_calculate_tooldia)
  614. self.ui.cutz_spinner.valueChanged.connect(self.on_calculate_tooldia)
  615. if self.app.defaults["gerber_buffering"] == 'no':
  616. self.ui.create_buffer_button.show()
  617. try:
  618. self.ui.create_buffer_button.clicked.disconnect(self.on_generate_buffer)
  619. except TypeError:
  620. pass
  621. self.ui.create_buffer_button.clicked.connect(self.on_generate_buffer)
  622. else:
  623. self.ui.create_buffer_button.hide()
  624. # set initial state of the aperture table and associated widgets
  625. self.on_aperture_table_visibility_change()
  626. self.build_ui()
  627. self.units_found = self.app.defaults['units']
  628. def on_calculate_tooldia(self):
  629. try:
  630. tdia = float(self.ui.tipdia_spinner.get_value())
  631. except Exception:
  632. return
  633. try:
  634. dang = float(self.ui.tipangle_spinner.get_value())
  635. except Exception:
  636. return
  637. try:
  638. cutz = float(self.ui.cutz_spinner.get_value())
  639. except Exception:
  640. return
  641. cutz *= -1
  642. if cutz < 0:
  643. cutz *= -1
  644. half_tip_angle = dang / 2
  645. tool_diameter = tdia + (2 * cutz * math.tan(math.radians(half_tip_angle)))
  646. self.ui.iso_tool_dia_entry.set_value(tool_diameter)
  647. def on_type_obj_index_changed(self):
  648. val = self.ui.type_obj_combo.get_value()
  649. obj_type = {"Gerber": 0, "Geometry": 2}[val]
  650. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  651. self.ui.obj_combo.setCurrentIndex(0)
  652. self.ui.obj_combo.obj_type = {_("Gerber"): "Gerber", _("Geometry"): "Geometry"}[val]
  653. def on_tool_type_change(self, state):
  654. if state == 'circular':
  655. self.ui.tipdialabel.hide()
  656. self.ui.tipdia_spinner.hide()
  657. self.ui.tipanglelabel.hide()
  658. self.ui.tipangle_spinner.hide()
  659. self.ui.cutzlabel.hide()
  660. self.ui.cutz_spinner.hide()
  661. self.ui.iso_tool_dia_entry.setDisabled(False)
  662. # update the value in the self.iso_tool_dia_entry once this is selected
  663. self.ui.iso_tool_dia_entry.set_value(self.options['isotooldia'])
  664. else:
  665. self.ui.tipdialabel.show()
  666. self.ui.tipdia_spinner.show()
  667. self.ui.tipanglelabel.show()
  668. self.ui.tipangle_spinner.show()
  669. self.ui.cutzlabel.show()
  670. self.ui.cutz_spinner.show()
  671. self.ui.iso_tool_dia_entry.setDisabled(True)
  672. # update the value in the self.iso_tool_dia_entry once this is selected
  673. self.on_calculate_tooldia()
  674. def build_ui(self):
  675. FlatCAMObj.build_ui(self)
  676. if self.ui.aperture_table_visibility_cb.get_value() and self.ui_build is False:
  677. self.ui_build = True
  678. try:
  679. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  680. self.ui.apertures_table.itemChanged.disconnect()
  681. except (TypeError, AttributeError):
  682. pass
  683. self.apertures_row = 0
  684. aper_no = self.apertures_row + 1
  685. sort = []
  686. for k, v in list(self.apertures.items()):
  687. sort.append(int(k))
  688. sorted_apertures = sorted(sort)
  689. n = len(sorted_apertures)
  690. self.ui.apertures_table.setRowCount(n)
  691. for ap_code in sorted_apertures:
  692. ap_code = str(ap_code)
  693. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  694. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  695. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  696. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  697. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  698. ap_type_item = QtWidgets.QTableWidgetItem(str(self.apertures[ap_code]['type']))
  699. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  700. if str(self.apertures[ap_code]['type']) == 'R' or str(self.apertures[ap_code]['type']) == 'O':
  701. ap_dim_item = QtWidgets.QTableWidgetItem(
  702. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['width'],
  703. self.decimals, self.apertures[ap_code]['height']
  704. )
  705. )
  706. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  707. elif str(self.apertures[ap_code]['type']) == 'P':
  708. ap_dim_item = QtWidgets.QTableWidgetItem(
  709. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['diam'],
  710. self.decimals, self.apertures[ap_code]['nVertices'])
  711. )
  712. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  713. else:
  714. ap_dim_item = QtWidgets.QTableWidgetItem('')
  715. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  716. try:
  717. if self.apertures[ap_code]['size'] is not None:
  718. ap_size_item = QtWidgets.QTableWidgetItem(
  719. '%.*f' % (self.decimals, float(self.apertures[ap_code]['size'])))
  720. else:
  721. ap_size_item = QtWidgets.QTableWidgetItem('')
  722. except KeyError:
  723. ap_size_item = QtWidgets.QTableWidgetItem('')
  724. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  725. mark_item = FCCheckBox()
  726. mark_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  727. # if self.ui.aperture_table_visibility_cb.isChecked():
  728. # mark_item.setChecked(True)
  729. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  730. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  731. self.ui.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  732. self.ui.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  733. empty_plot_item = QtWidgets.QTableWidgetItem('')
  734. empty_plot_item.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  735. self.ui.apertures_table.setItem(self.apertures_row, 5, empty_plot_item)
  736. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, mark_item)
  737. self.apertures_row += 1
  738. self.ui.apertures_table.selectColumn(0)
  739. self.ui.apertures_table.resizeColumnsToContents()
  740. self.ui.apertures_table.resizeRowsToContents()
  741. vertical_header = self.ui.apertures_table.verticalHeader()
  742. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  743. vertical_header.hide()
  744. self.ui.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  745. horizontal_header = self.ui.apertures_table.horizontalHeader()
  746. horizontal_header.setMinimumSectionSize(10)
  747. horizontal_header.setDefaultSectionSize(70)
  748. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  749. horizontal_header.resizeSection(0, 27)
  750. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  751. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  752. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  753. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  754. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  755. horizontal_header.resizeSection(5, 17)
  756. self.ui.apertures_table.setColumnWidth(5, 17)
  757. self.ui.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  758. self.ui.apertures_table.setSortingEnabled(False)
  759. self.ui.apertures_table.setMinimumHeight(self.ui.apertures_table.getHeight())
  760. self.ui.apertures_table.setMaximumHeight(self.ui.apertures_table.getHeight())
  761. # update the 'mark' checkboxes state according with what is stored in the self.marked_rows list
  762. if self.marked_rows:
  763. for row in range(self.ui.apertures_table.rowCount()):
  764. try:
  765. self.ui.apertures_table.cellWidget(row, 5).set_value(self.marked_rows[row])
  766. except IndexError:
  767. pass
  768. self.ui_connect()
  769. def ui_connect(self):
  770. for row in range(self.ui.apertures_table.rowCount()):
  771. try:
  772. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect(self.on_mark_cb_click_table)
  773. except (TypeError, AttributeError):
  774. pass
  775. self.ui.apertures_table.cellWidget(row, 5).clicked.connect(self.on_mark_cb_click_table)
  776. try:
  777. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  778. except (TypeError, AttributeError):
  779. pass
  780. self.ui.mark_all_cb.clicked.connect(self.on_mark_all_click)
  781. def ui_disconnect(self):
  782. for row in range(self.ui.apertures_table.rowCount()):
  783. try:
  784. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect()
  785. except (TypeError, AttributeError):
  786. pass
  787. try:
  788. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  789. except (TypeError, AttributeError):
  790. pass
  791. def on_generate_buffer(self):
  792. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Buffering solid geometry"))
  793. def buffer_task():
  794. with self.app.proc_container.new('%s...' % _("Buffering")):
  795. if isinstance(self.solid_geometry, list):
  796. self.solid_geometry = MultiPolygon(self.solid_geometry)
  797. self.solid_geometry = self.solid_geometry.buffer(0.0000001)
  798. self.solid_geometry = self.solid_geometry.buffer(-0.0000001)
  799. self.app.inform.emit('[success] %s.' % _("Done"))
  800. self.plot_single_object.emit()
  801. self.app.worker_task.emit({'fcn': buffer_task, 'params': []})
  802. def on_generatenoncopper_button_click(self, *args):
  803. self.app.report_usage("gerber_on_generatenoncopper_button")
  804. self.read_form()
  805. name = self.options["name"] + "_noncopper"
  806. def geo_init(geo_obj, app_obj):
  807. assert isinstance(geo_obj, FlatCAMGeometry)
  808. if isinstance(self.solid_geometry, list):
  809. try:
  810. self.solid_geometry = MultiPolygon(self.solid_geometry)
  811. except Exception:
  812. self.solid_geometry = cascaded_union(self.solid_geometry)
  813. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["noncoppermargin"]))
  814. if not self.options["noncopperrounded"]:
  815. bounding_box = bounding_box.envelope
  816. non_copper = bounding_box.difference(self.solid_geometry)
  817. if non_copper is None or non_copper.is_empty:
  818. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Operation could not be done."))
  819. return "fail"
  820. geo_obj.solid_geometry = non_copper
  821. self.app.new_object("geometry", name, geo_init)
  822. def on_generatebb_button_click(self, *args):
  823. self.app.report_usage("gerber_on_generatebb_button")
  824. self.read_form()
  825. name = self.options["name"] + "_bbox"
  826. def geo_init(geo_obj, app_obj):
  827. assert isinstance(geo_obj, FlatCAMGeometry)
  828. if isinstance(self.solid_geometry, list):
  829. try:
  830. self.solid_geometry = MultiPolygon(self.solid_geometry)
  831. except Exception:
  832. self.solid_geometry = cascaded_union(self.solid_geometry)
  833. # Bounding box with rounded corners
  834. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["bboxmargin"]))
  835. if not self.options["bboxrounded"]: # Remove rounded corners
  836. bounding_box = bounding_box.envelope
  837. if bounding_box is None or bounding_box.is_empty:
  838. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Operation could not be done."))
  839. return "fail"
  840. geo_obj.solid_geometry = bounding_box
  841. self.app.new_object("geometry", name, geo_init)
  842. def on_iso_button_click(self, *args):
  843. obj = self.app.collection.get_active()
  844. self.iso_type = 2
  845. if self.ui.iso_type_radio.get_value() == 'ext':
  846. self.iso_type = 0
  847. if self.ui.iso_type_radio.get_value() == 'int':
  848. self.iso_type = 1
  849. def worker_task(iso_obj, app_obj):
  850. with self.app.proc_container.new(_("Isolating...")):
  851. if self.ui.follow_cb.get_value() is True:
  852. iso_obj.follow_geo()
  853. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  854. iso_obj.ui.plot_cb.toggle()
  855. else:
  856. app_obj.report_usage("gerber_on_iso_button")
  857. self.read_form()
  858. iso_scope = 'all' if self.ui.iso_scope_radio.get_value() == 'all' else 'single'
  859. self.isolate_handler(iso_type=self.iso_type, iso_scope=iso_scope)
  860. self.app.worker_task.emit({'fcn': worker_task, 'params': [obj, self.app]})
  861. def follow_geo(self, outname=None):
  862. """
  863. Creates a geometry object "following" the gerber paths.
  864. :return: None
  865. """
  866. # default_name = self.options["name"] + "_follow"
  867. # follow_name = outname or default_name
  868. if outname is None:
  869. follow_name = self.options["name"] + "_follow"
  870. else:
  871. follow_name = outname
  872. def follow_init(follow_obj, app):
  873. # Propagate options
  874. follow_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  875. follow_obj.solid_geometry = self.follow_geometry
  876. # TODO: Do something if this is None. Offer changing name?
  877. try:
  878. self.app.new_object("geometry", follow_name, follow_init)
  879. except Exception as e:
  880. return "Operation failed: %s" % str(e)
  881. def isolate_handler(self, iso_type, iso_scope):
  882. if iso_scope == 'all':
  883. self.isolate(iso_type=iso_type)
  884. else:
  885. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  886. if self.app.ui.grid_snap_btn.isChecked():
  887. self.grid_status_memory = True
  888. self.app.ui.grid_snap_btn.trigger()
  889. else:
  890. self.grid_status_memory = False
  891. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  892. if self.app.is_legacy is False:
  893. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  894. else:
  895. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  896. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to isolate it."))
  897. def on_mouse_click_release(self, event):
  898. if self.app.is_legacy is False:
  899. event_pos = event.pos
  900. right_button = 2
  901. self.app.event_is_dragging = self.app.event_is_dragging
  902. else:
  903. event_pos = (event.xdata, event.ydata)
  904. right_button = 3
  905. self.app.event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  906. try:
  907. x = float(event_pos[0])
  908. y = float(event_pos[1])
  909. except TypeError:
  910. return
  911. event_pos = (x, y)
  912. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  913. if self.app.grid_status():
  914. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  915. else:
  916. curr_pos = (curr_pos[0], curr_pos[1])
  917. if event.button == 1:
  918. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]))
  919. if self.app.selection_type is not None:
  920. self.selection_area_handler(self.app.pos, curr_pos, self.app.selection_type)
  921. self.app.selection_type = None
  922. elif clicked_poly:
  923. if clicked_poly not in self.poly_dict.values():
  924. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0, shape=clicked_poly,
  925. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  926. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  927. visible=True)
  928. self.poly_dict[shape_id] = clicked_poly
  929. self.app.inform.emit(
  930. '%s: %d. %s' % (_("Added polygon"), int(len(self.poly_dict)),
  931. _("Click to add next polygon or right click to start isolation."))
  932. )
  933. else:
  934. try:
  935. for k, v in list(self.poly_dict.items()):
  936. if v == clicked_poly:
  937. self.app.tool_shapes.remove(k)
  938. self.poly_dict.pop(k)
  939. break
  940. except TypeError:
  941. return
  942. self.app.inform.emit(
  943. '%s. %s' % (_("Removed polygon"),
  944. _("Click to add/remove next polygon or right click to start isolation."))
  945. )
  946. self.app.tool_shapes.redraw()
  947. else:
  948. self.app.inform.emit(_("No polygon detected under click position."))
  949. elif event.button == right_button and self.app.event_is_dragging is False:
  950. # restore the Grid snapping if it was active before
  951. if self.grid_status_memory is True:
  952. self.app.ui.grid_snap_btn.trigger()
  953. if self.app.is_legacy is False:
  954. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  955. else:
  956. self.app.plotcanvas.graph_event_disconnect(self.mr)
  957. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  958. self.app.on_mouse_click_release_over_plot)
  959. self.app.tool_shapes.clear(update=True)
  960. if self.poly_dict:
  961. poly_list = deepcopy(list(self.poly_dict.values()))
  962. self.isolate(iso_type=self.iso_type, geometry=poly_list)
  963. self.poly_dict.clear()
  964. else:
  965. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  966. def selection_area_handler(self, start_pos, end_pos, sel_type):
  967. """
  968. :param start_pos: mouse position when the selection LMB click was done
  969. :param end_pos: mouse position when the left mouse button is released
  970. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  971. :return:
  972. """
  973. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  974. # delete previous selection shape
  975. self.app.delete_selection_shape()
  976. added_poly_count = 0
  977. try:
  978. for geo in self.solid_geometry:
  979. if geo not in self.poly_dict.values():
  980. if sel_type is True:
  981. if geo.within(poly_selection):
  982. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  983. shape=geo,
  984. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  985. face_color=self.app.defaults[
  986. 'global_sel_draw_color'] + 'AF',
  987. visible=True)
  988. self.poly_dict[shape_id] = geo
  989. added_poly_count += 1
  990. else:
  991. if poly_selection.intersects(geo):
  992. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  993. shape=geo,
  994. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  995. face_color=self.app.defaults[
  996. 'global_sel_draw_color'] + 'AF',
  997. visible=True)
  998. self.poly_dict[shape_id] = geo
  999. added_poly_count += 1
  1000. except TypeError:
  1001. if self.solid_geometry not in self.poly_dict.values():
  1002. if sel_type is True:
  1003. if self.solid_geometry.within(poly_selection):
  1004. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1005. shape=self.solid_geometry,
  1006. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1007. face_color=self.app.defaults[
  1008. 'global_sel_draw_color'] + 'AF',
  1009. visible=True)
  1010. self.poly_dict[shape_id] = self.solid_geometry
  1011. added_poly_count += 1
  1012. else:
  1013. if poly_selection.intersects(self.solid_geometry):
  1014. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1015. shape=self.solid_geometry,
  1016. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1017. face_color=self.app.defaults[
  1018. 'global_sel_draw_color'] + 'AF',
  1019. visible=True)
  1020. self.poly_dict[shape_id] = self.solid_geometry
  1021. added_poly_count += 1
  1022. if added_poly_count > 0:
  1023. self.app.tool_shapes.redraw()
  1024. self.app.inform.emit(
  1025. '%s: %d. %s' % (_("Added polygon"),
  1026. int(added_poly_count),
  1027. _("Click to add next polygon or right click to start isolation."))
  1028. )
  1029. else:
  1030. self.app.inform.emit(_("No polygon in selection."))
  1031. def isolate(self, iso_type=None, geometry=None, dia=None, passes=None, overlap=None, outname=None, combine=None,
  1032. milling_type=None, follow=None, plot=True):
  1033. """
  1034. Creates an isolation routing geometry object in the project.
  1035. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  1036. :param geometry: specific geometry to isolate
  1037. :param dia: Tool diameter
  1038. :param passes: Number of tool widths to cut
  1039. :param overlap: Overlap between passes in fraction of tool diameter
  1040. :param outname: Base name of the output object
  1041. :param combine: Boolean: if to combine passes in one resulting object in case of multiple passes
  1042. :param milling_type: type of milling: conventional or climbing
  1043. :param follow: Boolean: if to generate a 'follow' geometry
  1044. :param plot: Boolean: if to plot the resulting geometry object
  1045. :return: None
  1046. """
  1047. if geometry is None:
  1048. work_geo = self.follow_geometry if follow is True else self.solid_geometry
  1049. else:
  1050. work_geo = geometry
  1051. if dia is None:
  1052. dia = float(self.options["isotooldia"])
  1053. if passes is None:
  1054. passes = int(self.options["isopasses"])
  1055. if overlap is None:
  1056. overlap = float(self.options["isooverlap"])
  1057. overlap /= 100.0
  1058. combine = self.options["combine_passes"] if combine is None else bool(combine)
  1059. if milling_type is None:
  1060. milling_type = self.options["milling_type"]
  1061. if iso_type is None:
  1062. iso_t = 2
  1063. else:
  1064. iso_t = iso_type
  1065. base_name = self.options["name"]
  1066. if combine:
  1067. if outname is None:
  1068. if self.iso_type == 0:
  1069. iso_name = base_name + "_ext_iso"
  1070. elif self.iso_type == 1:
  1071. iso_name = base_name + "_int_iso"
  1072. else:
  1073. iso_name = base_name + "_iso"
  1074. else:
  1075. iso_name = outname
  1076. def iso_init(geo_obj, app_obj):
  1077. # Propagate options
  1078. geo_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  1079. geo_obj.tool_type = self.ui.tool_type_radio.get_value().upper()
  1080. geo_obj.solid_geometry = []
  1081. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  1082. if self.ui.tool_type_radio.get_value() == 'v':
  1083. new_cutz = self.ui.cutz_spinner.get_value()
  1084. new_vtipdia = self.ui.tipdia_spinner.get_value()
  1085. new_vtipangle = self.ui.tipangle_spinner.get_value()
  1086. tool_type = 'V'
  1087. else:
  1088. new_cutz = self.app.defaults['geometry_cutz']
  1089. new_vtipdia = self.app.defaults['geometry_vtipdia']
  1090. new_vtipangle = self.app.defaults['geometry_vtipangle']
  1091. tool_type = 'C1'
  1092. # store here the default data for Geometry Data
  1093. default_data = {}
  1094. default_data.update({
  1095. "name": iso_name,
  1096. "plot": self.app.defaults['geometry_plot'],
  1097. "cutz": new_cutz,
  1098. "vtipdia": new_vtipdia,
  1099. "vtipangle": new_vtipangle,
  1100. "travelz": self.app.defaults['geometry_travelz'],
  1101. "feedrate": self.app.defaults['geometry_feedrate'],
  1102. "feedrate_z": self.app.defaults['geometry_feedrate_z'],
  1103. "feedrate_rapid": self.app.defaults['geometry_feedrate_rapid'],
  1104. "dwell": self.app.defaults['geometry_dwell'],
  1105. "dwelltime": self.app.defaults['geometry_dwelltime'],
  1106. "multidepth": self.app.defaults['geometry_multidepth'],
  1107. "ppname_g": self.app.defaults['geometry_ppname_g'],
  1108. "depthperpass": self.app.defaults['geometry_depthperpass'],
  1109. "extracut": self.app.defaults['geometry_extracut'],
  1110. "extracut_length": self.app.defaults['geometry_extracut_length'],
  1111. "toolchange": self.app.defaults['geometry_toolchange'],
  1112. "toolchangez": self.app.defaults['geometry_toolchangez'],
  1113. "endz": self.app.defaults['geometry_endz'],
  1114. "spindlespeed": self.app.defaults['geometry_spindlespeed'],
  1115. "toolchangexy": self.app.defaults['geometry_toolchangexy'],
  1116. "startz": self.app.defaults['geometry_startz']
  1117. })
  1118. geo_obj.tools = {}
  1119. geo_obj.tools['1'] = {}
  1120. geo_obj.tools.update({
  1121. '1': {
  1122. 'tooldia': float(self.options["isotooldia"]),
  1123. 'offset': 'Path',
  1124. 'offset_value': 0.0,
  1125. 'type': _('Rough'),
  1126. 'tool_type': tool_type,
  1127. 'data': default_data,
  1128. 'solid_geometry': geo_obj.solid_geometry
  1129. }
  1130. })
  1131. for nr_pass in range(passes):
  1132. iso_offset = dia * ((2 * nr_pass + 1) / 2.0) - (nr_pass * overlap * dia)
  1133. # if milling type is climb then the move is counter-clockwise around features
  1134. mill_dir = 1 if milling_type == 'cl' else 0
  1135. geom = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1136. follow=follow, nr_passes=nr_pass)
  1137. if geom == 'fail':
  1138. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1139. return 'fail'
  1140. geo_obj.solid_geometry.append(geom)
  1141. # update the geometry in the tools
  1142. geo_obj.tools['1']['solid_geometry'] = geo_obj.solid_geometry
  1143. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1144. # or just looking in the lists (they are one level depth) and if any is not empty
  1145. # proceed with object creation, if there are empty and the number of them is the length
  1146. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1147. empty_cnt = 0
  1148. if not isinstance(geo_obj.solid_geometry, list) and \
  1149. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  1150. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1151. for g in geo_obj.solid_geometry:
  1152. if g:
  1153. break
  1154. else:
  1155. empty_cnt += 1
  1156. if empty_cnt == len(geo_obj.solid_geometry):
  1157. raise ValidationError("Empty Geometry", None)
  1158. else:
  1159. app_obj.inform.emit('[success] %s" %s' % (_("Isolation geometry created"), geo_obj.options["name"]))
  1160. # even if combine is checked, one pass is still single-geo
  1161. geo_obj.multigeo = True if passes > 1 else False
  1162. # ############################################################
  1163. # ########## AREA SUBTRACTION ################################
  1164. # ############################################################
  1165. if self.ui.except_cb.get_value():
  1166. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1167. geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  1168. # TODO: Do something if this is None. Offer changing name?
  1169. self.app.new_object("geometry", iso_name, iso_init, plot=plot)
  1170. else:
  1171. for i in range(passes):
  1172. offset = dia * ((2 * i + 1) / 2.0) - (i * overlap * dia)
  1173. if passes > 1:
  1174. if outname is None:
  1175. if self.iso_type == 0:
  1176. iso_name = base_name + "_ext_iso" + str(i + 1)
  1177. elif self.iso_type == 1:
  1178. iso_name = base_name + "_int_iso" + str(i + 1)
  1179. else:
  1180. iso_name = base_name + "_iso" + str(i + 1)
  1181. else:
  1182. iso_name = outname
  1183. else:
  1184. if outname is None:
  1185. if self.iso_type == 0:
  1186. iso_name = base_name + "_ext_iso"
  1187. elif self.iso_type == 1:
  1188. iso_name = base_name + "_int_iso"
  1189. else:
  1190. iso_name = base_name + "_iso"
  1191. else:
  1192. iso_name = outname
  1193. def iso_init(geo_obj, app_obj):
  1194. # Propagate options
  1195. geo_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  1196. if self.ui.tool_type_radio.get_value() == 'v':
  1197. geo_obj.tool_type = 'V'
  1198. else:
  1199. geo_obj.tool_type = 'C1'
  1200. # if milling type is climb then the move is counter-clockwise around features
  1201. mill_dir = 1 if milling_type == 'cl' else 0
  1202. geom = self.generate_envelope(offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1203. follow=follow,
  1204. nr_passes=i)
  1205. if geom == 'fail':
  1206. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1207. return 'fail'
  1208. geo_obj.solid_geometry = geom
  1209. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  1210. # even if the resulting geometry is not multigeo we add the tools dict which will hold the data
  1211. # required to be transfered to the Geometry object
  1212. if self.ui.tool_type_radio.get_value() == 'v':
  1213. new_cutz = self.ui.cutz_spinner.get_value()
  1214. new_vtipdia = self.ui.tipdia_spinner.get_value()
  1215. new_vtipangle = self.ui.tipangle_spinner.get_value()
  1216. tool_type = 'V'
  1217. else:
  1218. new_cutz = self.app.defaults['geometry_cutz']
  1219. new_vtipdia = self.app.defaults['geometry_vtipdia']
  1220. new_vtipangle = self.app.defaults['geometry_vtipangle']
  1221. tool_type = 'C1'
  1222. # store here the default data for Geometry Data
  1223. default_data = {}
  1224. default_data.update({
  1225. "name": iso_name,
  1226. "plot": self.app.defaults['geometry_plot'],
  1227. "cutz": new_cutz,
  1228. "vtipdia": new_vtipdia,
  1229. "vtipangle": new_vtipangle,
  1230. "travelz": self.app.defaults['geometry_travelz'],
  1231. "feedrate": self.app.defaults['geometry_feedrate'],
  1232. "feedrate_z": self.app.defaults['geometry_feedrate_z'],
  1233. "feedrate_rapid": self.app.defaults['geometry_feedrate_rapid'],
  1234. "dwell": self.app.defaults['geometry_dwell'],
  1235. "dwelltime": self.app.defaults['geometry_dwelltime'],
  1236. "multidepth": self.app.defaults['geometry_multidepth'],
  1237. "ppname_g": self.app.defaults['geometry_ppname_g'],
  1238. "depthperpass": self.app.defaults['geometry_depthperpass'],
  1239. "extracut": self.app.defaults['geometry_extracut'],
  1240. "extracut_length": self.app.defaults['geometry_extracut_length'],
  1241. "toolchange": self.app.defaults['geometry_toolchange'],
  1242. "toolchangez": self.app.defaults['geometry_toolchangez'],
  1243. "endz": self.app.defaults['geometry_endz'],
  1244. "spindlespeed": self.app.defaults['geometry_spindlespeed'],
  1245. "toolchangexy": self.app.defaults['geometry_toolchangexy'],
  1246. "startz": self.app.defaults['geometry_startz']
  1247. })
  1248. geo_obj.tools = {}
  1249. geo_obj.tools['1'] = {}
  1250. geo_obj.tools.update({
  1251. '1': {
  1252. 'tooldia': float(self.options["isotooldia"]),
  1253. 'offset': 'Path',
  1254. 'offset_value': 0.0,
  1255. 'type': _('Rough'),
  1256. 'tool_type': tool_type,
  1257. 'data': default_data,
  1258. 'solid_geometry': geo_obj.solid_geometry
  1259. }
  1260. })
  1261. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1262. # or just looking in the lists (they are one level depth) and if any is not empty
  1263. # proceed with object creation, if there are empty and the number of them is the length
  1264. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1265. empty_cnt = 0
  1266. if not isinstance(geo_obj.solid_geometry, list):
  1267. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1268. for g in geo_obj.solid_geometry:
  1269. if g:
  1270. break
  1271. else:
  1272. empty_cnt += 1
  1273. if empty_cnt == len(geo_obj.solid_geometry):
  1274. raise ValidationError("Empty Geometry", None)
  1275. else:
  1276. app_obj.inform.emit('[success] %s: %s' %
  1277. (_("Isolation geometry created"), geo_obj.options["name"]))
  1278. geo_obj.multigeo = False
  1279. # ############################################################
  1280. # ########## AREA SUBTRACTION ################################
  1281. # ############################################################
  1282. if self.ui.except_cb.get_value():
  1283. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1284. geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  1285. # TODO: Do something if this is None. Offer changing name?
  1286. self.app.new_object("geometry", iso_name, iso_init, plot=plot)
  1287. def generate_envelope(self, offset, invert, geometry=None, env_iso_type=2, follow=None, nr_passes=0):
  1288. # isolation_geometry produces an envelope that is going on the left of the geometry
  1289. # (the copper features). To leave the least amount of burrs on the features
  1290. # the tool needs to travel on the right side of the features (this is called conventional milling)
  1291. # the first pass is the one cutting all of the features, so it needs to be reversed
  1292. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  1293. # to cut on the right side of the left over copper i.e on the left side of the features.
  1294. if follow:
  1295. geom = self.isolation_geometry(offset, geometry=geometry, follow=follow)
  1296. else:
  1297. try:
  1298. geom = self.isolation_geometry(offset, geometry=geometry, iso_type=env_iso_type, passes=nr_passes)
  1299. except Exception as e:
  1300. log.debug('FlatCAMGerber.isolate().generate_envelope() --> %s' % str(e))
  1301. return 'fail'
  1302. if invert:
  1303. try:
  1304. pl = []
  1305. for p in geom:
  1306. if p is not None:
  1307. if isinstance(p, Polygon):
  1308. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  1309. elif isinstance(p, LinearRing):
  1310. pl.append(Polygon(p.coords[::-1]))
  1311. geom = MultiPolygon(pl)
  1312. except TypeError:
  1313. if isinstance(geom, Polygon) and geom is not None:
  1314. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  1315. elif isinstance(geom, LinearRing) and geom is not None:
  1316. geom = Polygon(geom.coords[::-1])
  1317. else:
  1318. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> Unexpected Geometry %s" %
  1319. type(geom))
  1320. except Exception as e:
  1321. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> %s" % str(e))
  1322. return 'fail'
  1323. return geom
  1324. def area_subtraction(self, geo, subtractor_geo=None):
  1325. """
  1326. Subtracts the subtractor_geo (if present else self.solid_geometry) from the geo
  1327. :param geo: target geometry from which to subtract
  1328. :param subtractor_geo: geometry that acts as subtractor
  1329. :return:
  1330. """
  1331. new_geometry = []
  1332. target_geo = geo
  1333. if subtractor_geo:
  1334. sub_union = cascaded_union(subtractor_geo)
  1335. else:
  1336. name = self.ui.obj_combo.currentText()
  1337. subtractor_obj = self.app.collection.get_by_name(name)
  1338. sub_union = cascaded_union(subtractor_obj.solid_geometry)
  1339. try:
  1340. for geo_elem in target_geo:
  1341. if isinstance(geo_elem, Polygon):
  1342. for ring in self.poly2rings(geo_elem):
  1343. new_geo = ring.difference(sub_union)
  1344. if new_geo and not new_geo.is_empty:
  1345. new_geometry.append(new_geo)
  1346. elif isinstance(geo_elem, MultiPolygon):
  1347. for poly in geo_elem:
  1348. for ring in self.poly2rings(poly):
  1349. new_geo = ring.difference(sub_union)
  1350. if new_geo and not new_geo.is_empty:
  1351. new_geometry.append(new_geo)
  1352. elif isinstance(geo_elem, LineString):
  1353. new_geo = geo_elem.difference(sub_union)
  1354. if new_geo:
  1355. if not new_geo.is_empty:
  1356. new_geometry.append(new_geo)
  1357. elif isinstance(geo_elem, MultiLineString):
  1358. for line_elem in geo_elem:
  1359. new_geo = line_elem.difference(sub_union)
  1360. if new_geo and not new_geo.is_empty:
  1361. new_geometry.append(new_geo)
  1362. except TypeError:
  1363. if isinstance(target_geo, Polygon):
  1364. for ring in self.poly2rings(target_geo):
  1365. new_geo = ring.difference(sub_union)
  1366. if new_geo:
  1367. if not new_geo.is_empty:
  1368. new_geometry.append(new_geo)
  1369. elif isinstance(target_geo, LineString):
  1370. new_geo = target_geo.difference(sub_union)
  1371. if new_geo and not new_geo.is_empty:
  1372. new_geometry.append(new_geo)
  1373. elif isinstance(target_geo, MultiLineString):
  1374. for line_elem in target_geo:
  1375. new_geo = line_elem.difference(sub_union)
  1376. if new_geo and not new_geo.is_empty:
  1377. new_geometry.append(new_geo)
  1378. return new_geometry
  1379. def on_plot_cb_click(self, *args):
  1380. if self.muted_ui:
  1381. return
  1382. self.read_form_item('plot')
  1383. self.plot()
  1384. def on_solid_cb_click(self, *args):
  1385. if self.muted_ui:
  1386. return
  1387. self.read_form_item('solid')
  1388. self.plot()
  1389. def on_multicolored_cb_click(self, *args):
  1390. if self.muted_ui:
  1391. return
  1392. self.read_form_item('multicolored')
  1393. self.plot()
  1394. def on_follow_cb_click(self):
  1395. if self.muted_ui:
  1396. return
  1397. self.plot()
  1398. def on_aperture_table_visibility_change(self):
  1399. if self.ui.aperture_table_visibility_cb.isChecked():
  1400. # add the shapes storage for marking apertures
  1401. if self.build_aperture_storage is False:
  1402. self.build_aperture_storage = True
  1403. if self.app.is_legacy is False:
  1404. for ap_code in self.apertures:
  1405. self.mark_shapes[ap_code] = self.app.plotcanvas.new_shape_collection(layers=1)
  1406. else:
  1407. for ap_code in self.apertures:
  1408. self.mark_shapes[ap_code] = ShapeCollectionLegacy(obj=self, app=self.app,
  1409. name=self.options['name'] + str(ap_code))
  1410. self.ui.apertures_table.setVisible(True)
  1411. for ap in self.mark_shapes:
  1412. self.mark_shapes[ap].enabled = True
  1413. self.ui.mark_all_cb.setVisible(True)
  1414. self.ui.mark_all_cb.setChecked(False)
  1415. self.build_ui()
  1416. else:
  1417. self.ui.apertures_table.setVisible(False)
  1418. self.ui.mark_all_cb.setVisible(False)
  1419. # on hide disable all mark plots
  1420. try:
  1421. for row in range(self.ui.apertures_table.rowCount()):
  1422. self.ui.apertures_table.cellWidget(row, 5).set_value(False)
  1423. self.clear_plot_apertures()
  1424. # for ap in list(self.mark_shapes.keys()):
  1425. # # self.mark_shapes[ap].enabled = False
  1426. # del self.mark_shapes[ap]
  1427. except Exception as e:
  1428. log.debug(" FlatCAMGerber.on_aperture_visibility_changed() --> %s" % str(e))
  1429. def convert_units(self, units):
  1430. """
  1431. Converts the units of the object by scaling dimensions in all geometry
  1432. and options.
  1433. :param units: Units to which to convert the object: "IN" or "MM".
  1434. :type units: str
  1435. :return: None
  1436. :rtype: None
  1437. """
  1438. # units conversion to get a conversion should be done only once even if we found multiple
  1439. # units declaration inside a Gerber file (it can happen to find also the obsolete declaration)
  1440. if self.conversion_done is True:
  1441. log.debug("Gerber units conversion cancelled. Already done.")
  1442. return
  1443. log.debug("FlatCAMObj.FlatCAMGerber.convert_units()")
  1444. factor = Gerber.convert_units(self, units)
  1445. # self.options['isotooldia'] = float(self.options['isotooldia']) * factor
  1446. # self.options['bboxmargin'] = float(self.options['bboxmargin']) * factor
  1447. def plot(self, kind=None, **kwargs):
  1448. """
  1449. :param kind: Not used, for compatibility with the plot method for other objects
  1450. :param kwargs: Color and face_color, visible
  1451. :return:
  1452. """
  1453. log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  1454. # Does all the required setup and returns False
  1455. # if the 'ptint' option is set to False.
  1456. if not FlatCAMObj.plot(self):
  1457. return
  1458. if 'color' in kwargs:
  1459. color = kwargs['color']
  1460. else:
  1461. color = self.outline_color
  1462. if 'face_color' in kwargs:
  1463. face_color = kwargs['face_color']
  1464. else:
  1465. face_color = self.fill_color
  1466. if 'visible' not in kwargs:
  1467. visible = self.options['plot']
  1468. else:
  1469. visible = kwargs['visible']
  1470. # if the Follow Geometry checkbox is checked then plot only the follow geometry
  1471. if self.ui.follow_cb.get_value():
  1472. geometry = self.follow_geometry
  1473. else:
  1474. geometry = self.solid_geometry
  1475. # Make sure geometry is iterable.
  1476. try:
  1477. __ = iter(geometry)
  1478. except TypeError:
  1479. geometry = [geometry]
  1480. if self.app.is_legacy is False:
  1481. def random_color():
  1482. r_color = np.random.rand(4)
  1483. r_color[3] = 1
  1484. return r_color
  1485. else:
  1486. def random_color():
  1487. while True:
  1488. r_color = np.random.rand(4)
  1489. r_color[3] = 1
  1490. new_color = '#'
  1491. for idx in range(len(r_color)):
  1492. new_color += '%x' % int(r_color[idx] * 255)
  1493. # do it until a valid color is generated
  1494. # a valid color has the # symbol, another 6 chars for the color and the last 2 chars for alpha
  1495. # for a total of 9 chars
  1496. if len(new_color) == 9:
  1497. break
  1498. return new_color
  1499. try:
  1500. if self.options["solid"]:
  1501. for g in geometry:
  1502. if type(g) == Polygon or type(g) == LineString:
  1503. self.add_shape(shape=g, color=color,
  1504. face_color=random_color() if self.options['multicolored']
  1505. else face_color, visible=visible)
  1506. elif type(g) == Point:
  1507. pass
  1508. else:
  1509. try:
  1510. for el in g:
  1511. self.add_shape(shape=el, color=color,
  1512. face_color=random_color() if self.options['multicolored']
  1513. else face_color, visible=visible)
  1514. except TypeError:
  1515. self.add_shape(shape=g, color=color,
  1516. face_color=random_color() if self.options['multicolored']
  1517. else face_color, visible=visible)
  1518. else:
  1519. for g in geometry:
  1520. if type(g) == Polygon or type(g) == LineString:
  1521. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  1522. visible=visible)
  1523. elif type(g) == Point:
  1524. pass
  1525. else:
  1526. for el in g:
  1527. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  1528. visible=visible)
  1529. self.shapes.redraw(
  1530. # update_colors=(self.fill_color, self.outline_color),
  1531. # indexes=self.app.plotcanvas.shape_collection.data.keys()
  1532. )
  1533. except (ObjectDeleted, AttributeError):
  1534. self.shapes.clear(update=True)
  1535. except Exception as e:
  1536. log.debug("FlatCAMGerber.plot() --> %s" % str(e))
  1537. # experimental plot() when the solid_geometry is stored in the self.apertures
  1538. def plot_aperture(self, run_thread=True, **kwargs):
  1539. """
  1540. :param run_thread: if True run the aperture plot as a thread in a worker
  1541. :param kwargs: color and face_color
  1542. :return:
  1543. """
  1544. log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot_aperture()")
  1545. # Does all the required setup and returns False
  1546. # if the 'ptint' option is set to False.
  1547. # if not FlatCAMObj.plot(self):
  1548. # return
  1549. # for marking apertures, line color and fill color are the same
  1550. if 'color' in kwargs:
  1551. color = kwargs['color']
  1552. else:
  1553. color = self.app.defaults['gerber_plot_fill']
  1554. if 'marked_aperture' not in kwargs:
  1555. return
  1556. else:
  1557. aperture_to_plot_mark = kwargs['marked_aperture']
  1558. if aperture_to_plot_mark is None:
  1559. return
  1560. if 'visible' not in kwargs:
  1561. visibility = True
  1562. else:
  1563. visibility = kwargs['visible']
  1564. with self.app.proc_container.new(_("Plotting Apertures")):
  1565. def job_thread(app_obj):
  1566. try:
  1567. if aperture_to_plot_mark in self.apertures:
  1568. for elem in self.apertures[aperture_to_plot_mark]['geometry']:
  1569. if 'solid' in elem:
  1570. geo = elem['solid']
  1571. if type(geo) == Polygon or type(geo) == LineString:
  1572. self.add_mark_shape(apid=aperture_to_plot_mark, shape=geo, color=color,
  1573. face_color=color, visible=visibility)
  1574. else:
  1575. for el in geo:
  1576. self.add_mark_shape(apid=aperture_to_plot_mark, shape=el, color=color,
  1577. face_color=color, visible=visibility)
  1578. self.mark_shapes[aperture_to_plot_mark].redraw()
  1579. except (ObjectDeleted, AttributeError):
  1580. self.clear_plot_apertures()
  1581. except Exception as e:
  1582. log.debug("FlatCAMGerber.plot_aperture() --> %s" % str(e))
  1583. if run_thread:
  1584. self.app.worker_task.emit({'fcn': job_thread, 'params': [self]})
  1585. else:
  1586. job_thread(self)
  1587. def clear_plot_apertures(self, aperture='all'):
  1588. """
  1589. :param aperture: string; aperture for which to clear the mark shapes
  1590. :return:
  1591. """
  1592. if self.mark_shapes:
  1593. if aperture == 'all':
  1594. for apid in list(self.apertures.keys()):
  1595. try:
  1596. if self.app.is_legacy is True:
  1597. self.mark_shapes[apid].clear(update=False)
  1598. else:
  1599. self.mark_shapes[apid].clear(update=True)
  1600. except Exception as e:
  1601. log.debug("FlatCAMGerber.clear_plot_apertures() 'all' --> %s" % str(e))
  1602. else:
  1603. try:
  1604. if self.app.is_legacy is True:
  1605. self.mark_shapes[aperture].clear(update=False)
  1606. else:
  1607. self.mark_shapes[aperture].clear(update=True)
  1608. except Exception as e:
  1609. log.debug("FlatCAMGerber.clear_plot_apertures() 'aperture' --> %s" % str(e))
  1610. def clear_mark_all(self):
  1611. self.ui.mark_all_cb.set_value(False)
  1612. self.marked_rows[:] = []
  1613. def on_mark_cb_click_table(self):
  1614. """
  1615. Will mark aperture geometries on canvas or delete the markings depending on the checkbox state
  1616. :return:
  1617. """
  1618. self.ui_disconnect()
  1619. try:
  1620. cw = self.sender()
  1621. assert isinstance(cw, FCCheckBox),\
  1622. "Expected a cellWidget but got %s" % type(cw)
  1623. cw_index = self.ui.apertures_table.indexAt(cw.pos())
  1624. cw_row = cw_index.row()
  1625. except AttributeError:
  1626. cw_row = 0
  1627. except TypeError:
  1628. return
  1629. self.marked_rows[:] = []
  1630. try:
  1631. aperture = self.ui.apertures_table.item(cw_row, 1).text()
  1632. except AttributeError:
  1633. return
  1634. if self.ui.apertures_table.cellWidget(cw_row, 5).isChecked():
  1635. self.marked_rows.append(True)
  1636. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  1637. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1638. marked_aperture=aperture, visible=True, run_thread=True)
  1639. # self.mark_shapes[aperture].redraw()
  1640. else:
  1641. self.marked_rows.append(False)
  1642. self.clear_plot_apertures(aperture=aperture)
  1643. # make sure that the Mark All is disabled if one of the row mark's are disabled and
  1644. # if all the row mark's are enabled also enable the Mark All checkbox
  1645. cb_cnt = 0
  1646. total_row = self.ui.apertures_table.rowCount()
  1647. for row in range(total_row):
  1648. if self.ui.apertures_table.cellWidget(row, 5).isChecked():
  1649. cb_cnt += 1
  1650. else:
  1651. cb_cnt -= 1
  1652. if cb_cnt < total_row:
  1653. self.ui.mark_all_cb.setChecked(False)
  1654. else:
  1655. self.ui.mark_all_cb.setChecked(True)
  1656. self.ui_connect()
  1657. def on_mark_all_click(self):
  1658. self.ui_disconnect()
  1659. mark_all = self.ui.mark_all_cb.isChecked()
  1660. for row in range(self.ui.apertures_table.rowCount()):
  1661. # update the mark_rows list
  1662. if mark_all:
  1663. self.marked_rows.append(True)
  1664. else:
  1665. self.marked_rows[:] = []
  1666. mark_cb = self.ui.apertures_table.cellWidget(row, 5)
  1667. mark_cb.setChecked(mark_all)
  1668. if mark_all:
  1669. for aperture in self.apertures:
  1670. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  1671. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1672. marked_aperture=aperture, visible=True)
  1673. # HACK: enable/disable the grid for a better look
  1674. self.app.ui.grid_snap_btn.trigger()
  1675. self.app.ui.grid_snap_btn.trigger()
  1676. else:
  1677. self.clear_plot_apertures()
  1678. self.marked_rows[:] = []
  1679. self.ui_connect()
  1680. def export_gerber(self, whole, fract, g_zeros='L', factor=1):
  1681. """
  1682. Creates a Gerber file content to be exported to a file.
  1683. :param whole: how many digits in the whole part of coordinates
  1684. :param fract: how many decimals in coordinates
  1685. :param g_zeros: type of the zero suppression used: LZ or TZ; string
  1686. :param factor: factor to be applied onto the Gerber coordinates
  1687. :return: Gerber_code
  1688. """
  1689. log.debug("FlatCAMGerber.export_gerber() --> Generating the Gerber code from the selected Gerber file")
  1690. def tz_format(x, y, fac):
  1691. x_c = x * fac
  1692. y_c = y * fac
  1693. x_form = "{:.{dec}f}".format(x_c, dec=fract)
  1694. y_form = "{:.{dec}f}".format(y_c, dec=fract)
  1695. # extract whole part and decimal part
  1696. x_form = x_form.partition('.')
  1697. y_form = y_form.partition('.')
  1698. # left padd the 'whole' part with zeros
  1699. x_whole = x_form[0].rjust(whole, '0')
  1700. y_whole = y_form[0].rjust(whole, '0')
  1701. # restore the coordinate padded in the left with 0 and added the decimal part
  1702. # without the decinal dot
  1703. x_form = x_whole + x_form[2]
  1704. y_form = y_whole + y_form[2]
  1705. return x_form, y_form
  1706. def lz_format(x, y, fac):
  1707. x_c = x * fac
  1708. y_c = y * fac
  1709. x_form = "{:.{dec}f}".format(x_c, dec=fract).replace('.', '')
  1710. y_form = "{:.{dec}f}".format(y_c, dec=fract).replace('.', '')
  1711. # pad with rear zeros
  1712. x_form.ljust(length, '0')
  1713. y_form.ljust(length, '0')
  1714. return x_form, y_form
  1715. # Gerber code is stored here
  1716. gerber_code = ''
  1717. # apertures processing
  1718. try:
  1719. length = whole + fract
  1720. if '0' in self.apertures:
  1721. if 'geometry' in self.apertures['0']:
  1722. for geo_elem in self.apertures['0']['geometry']:
  1723. if 'solid' in geo_elem:
  1724. geo = geo_elem['solid']
  1725. if not geo.is_empty:
  1726. gerber_code += 'G36*\n'
  1727. geo_coords = list(geo.exterior.coords)
  1728. # first command is a move with pen-up D02 at the beginning of the geo
  1729. if g_zeros == 'T':
  1730. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1731. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1732. yform=y_formatted)
  1733. else:
  1734. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1735. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1736. yform=y_formatted)
  1737. for coord in geo_coords[1:]:
  1738. if g_zeros == 'T':
  1739. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1740. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1741. yform=y_formatted)
  1742. else:
  1743. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1744. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1745. yform=y_formatted)
  1746. gerber_code += 'D02*\n'
  1747. gerber_code += 'G37*\n'
  1748. clear_list = list(geo.interiors)
  1749. if clear_list:
  1750. gerber_code += '%LPC*%\n'
  1751. for clear_geo in clear_list:
  1752. gerber_code += 'G36*\n'
  1753. geo_coords = list(clear_geo.coords)
  1754. # first command is a move with pen-up D02 at the beginning of the geo
  1755. if g_zeros == 'T':
  1756. x_formatted, y_formatted = tz_format(
  1757. geo_coords[0][0], geo_coords[0][1], factor)
  1758. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1759. yform=y_formatted)
  1760. else:
  1761. x_formatted, y_formatted = lz_format(
  1762. geo_coords[0][0], geo_coords[0][1], factor)
  1763. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1764. yform=y_formatted)
  1765. prev_coord = geo_coords[0]
  1766. for coord in geo_coords[1:]:
  1767. if coord != prev_coord:
  1768. if g_zeros == 'T':
  1769. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1770. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1771. yform=y_formatted)
  1772. else:
  1773. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1774. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1775. yform=y_formatted)
  1776. prev_coord = coord
  1777. gerber_code += 'D02*\n'
  1778. gerber_code += 'G37*\n'
  1779. gerber_code += '%LPD*%\n'
  1780. if 'clear' in geo_elem:
  1781. geo = geo_elem['clear']
  1782. if not geo.is_empty:
  1783. gerber_code += '%LPC*%\n'
  1784. gerber_code += 'G36*\n'
  1785. geo_coords = list(geo.exterior.coords)
  1786. # first command is a move with pen-up D02 at the beginning of the geo
  1787. if g_zeros == 'T':
  1788. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1789. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1790. yform=y_formatted)
  1791. else:
  1792. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1793. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1794. yform=y_formatted)
  1795. prev_coord = geo_coords[0]
  1796. for coord in geo_coords[1:]:
  1797. if coord != prev_coord:
  1798. if g_zeros == 'T':
  1799. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1800. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1801. yform=y_formatted)
  1802. else:
  1803. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1804. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1805. yform=y_formatted)
  1806. prev_coord = coord
  1807. gerber_code += 'D02*\n'
  1808. gerber_code += 'G37*\n'
  1809. gerber_code += '%LPD*%\n'
  1810. except Exception as e:
  1811. log.debug("FlatCAMObj.FlatCAMGerber.export_gerber() '0' aperture --> %s" % str(e))
  1812. for apid in self.apertures:
  1813. if apid == '0':
  1814. continue
  1815. else:
  1816. gerber_code += 'D%s*\n' % str(apid)
  1817. if 'geometry' in self.apertures[apid]:
  1818. for geo_elem in self.apertures[apid]['geometry']:
  1819. try:
  1820. if 'follow' in geo_elem:
  1821. geo = geo_elem['follow']
  1822. if not geo.is_empty:
  1823. if isinstance(geo, Point):
  1824. if g_zeros == 'T':
  1825. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1826. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1827. yform=y_formatted)
  1828. else:
  1829. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1830. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1831. yform=y_formatted)
  1832. else:
  1833. geo_coords = list(geo.coords)
  1834. # first command is a move with pen-up D02 at the beginning of the geo
  1835. if g_zeros == 'T':
  1836. x_formatted, y_formatted = tz_format(
  1837. geo_coords[0][0], geo_coords[0][1], factor)
  1838. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1839. yform=y_formatted)
  1840. else:
  1841. x_formatted, y_formatted = lz_format(
  1842. geo_coords[0][0], geo_coords[0][1], factor)
  1843. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1844. yform=y_formatted)
  1845. prev_coord = geo_coords[0]
  1846. for coord in geo_coords[1:]:
  1847. if coord != prev_coord:
  1848. if g_zeros == 'T':
  1849. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1850. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1851. yform=y_formatted)
  1852. else:
  1853. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1854. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1855. yform=y_formatted)
  1856. prev_coord = coord
  1857. # gerber_code += "D02*\n"
  1858. except Exception as e:
  1859. log.debug("FlatCAMObj.FlatCAMGerber.export_gerber() 'follow' --> %s" % str(e))
  1860. try:
  1861. if 'clear' in geo_elem:
  1862. gerber_code += '%LPC*%\n'
  1863. geo = geo_elem['clear']
  1864. if not geo.is_empty:
  1865. if isinstance(geo, Point):
  1866. if g_zeros == 'T':
  1867. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1868. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1869. yform=y_formatted)
  1870. else:
  1871. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1872. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1873. yform=y_formatted)
  1874. elif isinstance(geo, Polygon):
  1875. geo_coords = list(geo.exterior.coords)
  1876. # first command is a move with pen-up D02 at the beginning of the geo
  1877. if g_zeros == 'T':
  1878. x_formatted, y_formatted = tz_format(
  1879. geo_coords[0][0], geo_coords[0][1], factor)
  1880. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1881. yform=y_formatted)
  1882. else:
  1883. x_formatted, y_formatted = lz_format(
  1884. geo_coords[0][0], geo_coords[0][1], factor)
  1885. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1886. yform=y_formatted)
  1887. prev_coord = geo_coords[0]
  1888. for coord in geo_coords[1:]:
  1889. if coord != prev_coord:
  1890. if g_zeros == 'T':
  1891. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1892. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1893. yform=y_formatted)
  1894. else:
  1895. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1896. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1897. yform=y_formatted)
  1898. prev_coord = coord
  1899. for geo_int in geo.interiors:
  1900. geo_coords = list(geo_int.coords)
  1901. # first command is a move with pen-up D02 at the beginning of the geo
  1902. if g_zeros == 'T':
  1903. x_formatted, y_formatted = tz_format(
  1904. geo_coords[0][0], geo_coords[0][1], factor)
  1905. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1906. yform=y_formatted)
  1907. else:
  1908. x_formatted, y_formatted = lz_format(
  1909. geo_coords[0][0], geo_coords[0][1], factor)
  1910. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1911. yform=y_formatted)
  1912. prev_coord = geo_coords[0]
  1913. for coord in geo_coords[1:]:
  1914. if coord != prev_coord:
  1915. if g_zeros == 'T':
  1916. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1917. gerber_code += "X{xform}Y{yform}D01*\n".format(
  1918. xform=x_formatted,
  1919. yform=y_formatted)
  1920. else:
  1921. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1922. gerber_code += "X{xform}Y{yform}D01*\n".format(
  1923. xform=x_formatted,
  1924. yform=y_formatted)
  1925. prev_coord = coord
  1926. else:
  1927. geo_coords = list(geo.coords)
  1928. # first command is a move with pen-up D02 at the beginning of the geo
  1929. if g_zeros == 'T':
  1930. x_formatted, y_formatted = tz_format(
  1931. geo_coords[0][0], geo_coords[0][1], factor)
  1932. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1933. yform=y_formatted)
  1934. else:
  1935. x_formatted, y_formatted = lz_format(
  1936. geo_coords[0][0], geo_coords[0][1], factor)
  1937. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1938. yform=y_formatted)
  1939. prev_coord = geo_coords[0]
  1940. for coord in geo_coords[1:]:
  1941. if coord != prev_coord:
  1942. if g_zeros == 'T':
  1943. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1944. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1945. yform=y_formatted)
  1946. else:
  1947. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1948. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1949. yform=y_formatted)
  1950. prev_coord = coord
  1951. # gerber_code += "D02*\n"
  1952. gerber_code += '%LPD*%\n'
  1953. except Exception as e:
  1954. log.debug("FlatCAMObj.FlatCAMGerber.export_gerber() 'clear' --> %s" % str(e))
  1955. if not self.apertures:
  1956. log.debug("FlatCAMObj.FlatCAMGerber.export_gerber() --> Gerber Object is empty: no apertures.")
  1957. return 'fail'
  1958. return gerber_code
  1959. def mirror(self, axis, point):
  1960. Gerber.mirror(self, axis=axis, point=point)
  1961. self.replotApertures.emit()
  1962. def offset(self, vect):
  1963. Gerber.offset(self, vect=vect)
  1964. self.replotApertures.emit()
  1965. def rotate(self, angle, point):
  1966. Gerber.rotate(self, angle=angle, point=point)
  1967. self.replotApertures.emit()
  1968. def scale(self, xfactor, yfactor=None, point=None):
  1969. Gerber.scale(self, xfactor=xfactor, yfactor=yfactor, point=point)
  1970. self.replotApertures.emit()
  1971. def skew(self, angle_x, angle_y, point):
  1972. Gerber.skew(self, angle_x=angle_x, angle_y=angle_y, point=point)
  1973. self.replotApertures.emit()
  1974. def buffer(self, distance, join, factor=None):
  1975. Gerber.buffer(self, distance=distance, join=join, factor=factor)
  1976. self.replotApertures.emit()
  1977. def serialize(self):
  1978. return {
  1979. "options": self.options,
  1980. "kind": self.kind
  1981. }
  1982. class FlatCAMExcellon(FlatCAMObj, Excellon):
  1983. """
  1984. Represents Excellon/Drill code.
  1985. """
  1986. ui_type = ExcellonObjectUI
  1987. optionChanged = QtCore.pyqtSignal(str)
  1988. def __init__(self, name):
  1989. self.decimals = self.app.decimals
  1990. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  1991. Excellon.__init__(self, geo_steps_per_circle=self.circle_steps)
  1992. FlatCAMObj.__init__(self, name)
  1993. self.kind = "excellon"
  1994. self.options.update({
  1995. "plot": True,
  1996. "solid": False,
  1997. "operation": "drill",
  1998. "milling_type": "drills",
  1999. "milling_dia": 0.04,
  2000. "cutz": -0.1,
  2001. "multidepth": False,
  2002. "depthperpass": 0.7,
  2003. "travelz": 0.1,
  2004. "feedrate": self.app.defaults["geometry_feedrate"],
  2005. "feedrate_z": 5.0,
  2006. "feedrate_rapid": 5.0,
  2007. "tooldia": 0.1,
  2008. "slot_tooldia": 0.1,
  2009. "toolchange": False,
  2010. "toolchangez": 1.0,
  2011. "toolchangexy": "0.0, 0.0",
  2012. "extracut": self.app.defaults["geometry_extracut"],
  2013. "extracut_length": self.app.defaults["geometry_extracut_length"],
  2014. "endz": 2.0,
  2015. "endxy": '',
  2016. "startz": None,
  2017. "offset": 0.0,
  2018. "spindlespeed": 0,
  2019. "dwell": True,
  2020. "dwelltime": 1000,
  2021. "ppname_e": 'default',
  2022. "ppname_g": self.app.defaults["geometry_ppname_g"],
  2023. "z_pdepth": -0.02,
  2024. "feedrate_probe": 3.0,
  2025. "optimization_type": "B",
  2026. })
  2027. # TODO: Document this.
  2028. self.tool_cbs = {}
  2029. # dict that holds the object names and the option name
  2030. # the key is the object name (defines in ObjectUI) for each UI element that is a parameter
  2031. # particular for a tool and the value is the actual name of the option that the UI element is changing
  2032. self.name2option = {}
  2033. # default set of data to be added to each tool in self.tools as self.tools[tool]['data'] = self.default_data
  2034. self.default_data = {}
  2035. # fill in self.default_data values from self.options
  2036. for opt_key, opt_val in self.app.options.items():
  2037. if opt_key.find('excellon_') == 0:
  2038. self.default_data[opt_key] = deepcopy(opt_val)
  2039. for opt_key, opt_val in self.app.options.items():
  2040. if opt_key.find('geometry_') == 0:
  2041. self.default_data[opt_key] = deepcopy(opt_val)
  2042. # variable to store the total amount of drills per job
  2043. self.tot_drill_cnt = 0
  2044. self.tool_row = 0
  2045. # variable to store the total amount of slots per job
  2046. self.tot_slot_cnt = 0
  2047. self.tool_row_slots = 0
  2048. # variable to store the distance travelled
  2049. self.travel_distance = 0.0
  2050. # store the source file here
  2051. self.source_file = ""
  2052. self.multigeo = False
  2053. self.units_found = self.app.defaults['units']
  2054. self.fill_color = self.app.defaults['excellon_plot_fill']
  2055. self.outline_color = self.app.defaults['excellon_plot_line']
  2056. self.alpha_level = 'bf'
  2057. # Attributes to be included in serialization
  2058. # Always append to it because it carries contents
  2059. # from predecessors.
  2060. self.ser_attrs += ['options', 'kind']
  2061. def merge(self, exc_list, exc_final):
  2062. """
  2063. Merge Excellon objects found in exc_list parameter into exc_final object.
  2064. Options are always copied from source .
  2065. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  2066. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  2067. tool_name to be used in the final Excellon object, exc_final.
  2068. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  2069. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  2070. :param exc_final: Destination FlatCAMExcellon object.
  2071. :return: None
  2072. """
  2073. try:
  2074. decimals_exc = self.decimals
  2075. except AttributeError:
  2076. decimals_exc = 4
  2077. # flag to signal that we need to reorder the tools dictionary and drills and slots lists
  2078. flag_order = False
  2079. try:
  2080. flattened_list = list(itertools.chain(*exc_list))
  2081. except TypeError:
  2082. flattened_list = exc_list
  2083. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  2084. # values will be list of Shapely Points; for drills
  2085. custom_dict_drills = {}
  2086. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  2087. # values will be list of Shapely Points; for slots
  2088. custom_dict_slots = {}
  2089. for exc in flattened_list:
  2090. # copy options of the current excellon obj to the final excellon obj
  2091. for option in exc.options:
  2092. if option != 'name':
  2093. try:
  2094. exc_final.options[option] = exc.options[option]
  2095. except Exception:
  2096. exc.app.log.warning("Failed to copy option.", option)
  2097. for drill in exc.drills:
  2098. exc_tool_dia = float('%.*f' % (decimals_exc, exc.tools[drill['tool']]['C']))
  2099. if exc_tool_dia not in custom_dict_drills:
  2100. custom_dict_drills[exc_tool_dia] = [drill['point']]
  2101. else:
  2102. custom_dict_drills[exc_tool_dia].append(drill['point'])
  2103. for slot in exc.slots:
  2104. exc_tool_dia = float('%.*f' % (decimals_exc, exc.tools[slot['tool']]['C']))
  2105. if exc_tool_dia not in custom_dict_slots:
  2106. custom_dict_slots[exc_tool_dia] = [[slot['start'], slot['stop']]]
  2107. else:
  2108. custom_dict_slots[exc_tool_dia].append([slot['start'], slot['stop']])
  2109. # add the zeros and units to the exc_final object
  2110. exc_final.zeros = exc.zeros
  2111. exc_final.units = exc.units
  2112. # ##########################################
  2113. # Here we add data to the exc_final object #
  2114. # ##########################################
  2115. # variable to make tool_name for the tools
  2116. current_tool = 0
  2117. # The tools diameter are now the keys in the drill_dia dict and the values are the Shapely Points in case of
  2118. # drills
  2119. for tool_dia in custom_dict_drills:
  2120. # we create a tool name for each key in the drill_dia dict (the key is a unique drill diameter)
  2121. current_tool += 1
  2122. tool_name = str(current_tool)
  2123. spec = {"C": float(tool_dia)}
  2124. exc_final.tools[tool_name] = spec
  2125. # rebuild the drills list of dict's that belong to the exc_final object
  2126. for point in custom_dict_drills[tool_dia]:
  2127. exc_final.drills.append(
  2128. {
  2129. "point": point,
  2130. "tool": str(current_tool)
  2131. }
  2132. )
  2133. # The tools diameter are now the keys in the drill_dia dict and the values are a list ([start, stop])
  2134. # of two Shapely Points in case of slots
  2135. for tool_dia in custom_dict_slots:
  2136. # we create a tool name for each key in the slot_dia dict (the key is a unique slot diameter)
  2137. # but only if there are no drills
  2138. if not exc_final.tools:
  2139. current_tool += 1
  2140. tool_name = str(current_tool)
  2141. spec = {"C": float(tool_dia)}
  2142. exc_final.tools[tool_name] = spec
  2143. else:
  2144. dia_list = []
  2145. for v in exc_final.tools.values():
  2146. dia_list.append(float(v["C"]))
  2147. if tool_dia not in dia_list:
  2148. flag_order = True
  2149. current_tool = len(dia_list) + 1
  2150. tool_name = str(current_tool)
  2151. spec = {"C": float(tool_dia)}
  2152. exc_final.tools[tool_name] = spec
  2153. else:
  2154. for k, v in exc_final.tools.items():
  2155. if v["C"] == tool_dia:
  2156. current_tool = int(k)
  2157. break
  2158. # rebuild the slots list of dict's that belong to the exc_final object
  2159. for point in custom_dict_slots[tool_dia]:
  2160. exc_final.slots.append(
  2161. {
  2162. "start": point[0],
  2163. "stop": point[1],
  2164. "tool": str(current_tool)
  2165. }
  2166. )
  2167. # flag_order == True means that there was an slot diameter not in the tools and we also have drills
  2168. # and the new tool was added to self.tools therefore we need to reorder the tools and drills and slots
  2169. current_tool = 0
  2170. if flag_order is True:
  2171. dia_list = []
  2172. temp_drills = []
  2173. temp_slots = []
  2174. temp_tools = {}
  2175. for v in exc_final.tools.values():
  2176. dia_list.append(float(v["C"]))
  2177. dia_list.sort()
  2178. for ordered_dia in dia_list:
  2179. current_tool += 1
  2180. tool_name_temp = str(current_tool)
  2181. spec_temp = {"C": float(ordered_dia)}
  2182. temp_tools[tool_name_temp] = spec_temp
  2183. for drill in exc_final.drills:
  2184. exc_tool_dia = float('%.*f' % (decimals_exc, exc_final.tools[drill['tool']]['C']))
  2185. if exc_tool_dia == ordered_dia:
  2186. temp_drills.append(
  2187. {
  2188. "point": drill["point"],
  2189. "tool": str(current_tool)
  2190. }
  2191. )
  2192. for slot in exc_final.slots:
  2193. slot_tool_dia = float('%.*f' % (decimals_exc, exc_final.tools[slot['tool']]['C']))
  2194. if slot_tool_dia == ordered_dia:
  2195. temp_slots.append(
  2196. {
  2197. "start": slot["start"],
  2198. "stop": slot["stop"],
  2199. "tool": str(current_tool)
  2200. }
  2201. )
  2202. # delete the exc_final tools, drills and slots
  2203. exc_final.tools = {}
  2204. exc_final.drills[:] = []
  2205. exc_final.slots[:] = []
  2206. # update the exc_final tools, drills and slots with the ordered values
  2207. exc_final.tools = temp_tools
  2208. exc_final.drills[:] = temp_drills
  2209. exc_final.slots[:] = temp_slots
  2210. # create the geometry for the exc_final object
  2211. exc_final.create_geometry()
  2212. def build_ui(self):
  2213. FlatCAMObj.build_ui(self)
  2214. self.units = self.app.defaults['units'].upper()
  2215. for row in range(self.ui.tools_table.rowCount()):
  2216. try:
  2217. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2218. offset_spin_widget = self.ui.tools_table.cellWidget(row, 4)
  2219. offset_spin_widget.valueChanged.disconnect()
  2220. except (TypeError, AttributeError):
  2221. pass
  2222. n = len(self.tools)
  2223. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  2224. self.ui.tools_table.setRowCount(n + 2)
  2225. self.tot_drill_cnt = 0
  2226. self.tot_slot_cnt = 0
  2227. self.tool_row = 0
  2228. sort = []
  2229. for k, v in list(self.tools.items()):
  2230. sort.append((k, v.get('C')))
  2231. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  2232. tools = [i[0] for i in sorted_tools]
  2233. new_options = {}
  2234. for opt in self.options:
  2235. new_options[opt] = self.options[opt]
  2236. for tool_no in tools:
  2237. # add the data dictionary for each tool with the default values
  2238. self.tools[tool_no]['data'] = deepcopy(new_options)
  2239. # self.tools[tool_no]['data']["tooldia"] = self.tools[tool_no]["C"]
  2240. # self.tools[tool_no]['data']["slot_tooldia"] = self.tools[tool_no]["C"]
  2241. drill_cnt = 0 # variable to store the nr of drills per tool
  2242. slot_cnt = 0 # variable to store the nr of slots per tool
  2243. # Find no of drills for the current tool
  2244. for drill in self.drills:
  2245. if drill['tool'] == tool_no:
  2246. drill_cnt += 1
  2247. self.tot_drill_cnt += drill_cnt
  2248. # Find no of slots for the current tool
  2249. for slot in self.slots:
  2250. if slot['tool'] == tool_no:
  2251. slot_cnt += 1
  2252. self.tot_slot_cnt += slot_cnt
  2253. exc_id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  2254. exc_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2255. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, self.tools[tool_no]['C']))
  2256. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2257. drill_count_item = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  2258. drill_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2259. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  2260. slot_count_str = '%d' % slot_cnt if slot_cnt > 0 else ''
  2261. slot_count_item = QtWidgets.QTableWidgetItem(slot_count_str)
  2262. slot_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2263. plot_item = FCCheckBox()
  2264. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  2265. if self.ui.plot_cb.isChecked():
  2266. plot_item.setChecked(True)
  2267. self.ui.tools_table.setItem(self.tool_row, 0, exc_id_item) # Tool name/id
  2268. self.ui.tools_table.setItem(self.tool_row, 1, dia_item) # Diameter
  2269. self.ui.tools_table.setItem(self.tool_row, 2, drill_count_item) # Number of drills per tool
  2270. self.ui.tools_table.setItem(self.tool_row, 3, slot_count_item) # Number of drills per tool
  2271. empty_plot_item = QtWidgets.QTableWidgetItem('')
  2272. empty_plot_item.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2273. self.ui.tools_table.setItem(self.tool_row, 5, empty_plot_item)
  2274. self.ui.tools_table.setCellWidget(self.tool_row, 5, plot_item)
  2275. self.tool_row += 1
  2276. # add a last row with the Total number of drills
  2277. empty_1 = QtWidgets.QTableWidgetItem('')
  2278. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2279. empty_1_1 = QtWidgets.QTableWidgetItem('')
  2280. empty_1_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2281. empty_1_2 = QtWidgets.QTableWidgetItem('')
  2282. empty_1_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2283. empty_1_3 = QtWidgets.QTableWidgetItem('')
  2284. empty_1_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2285. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  2286. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  2287. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2288. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2289. self.ui.tools_table.setItem(self.tool_row, 0, empty_1)
  2290. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  2291. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  2292. self.ui.tools_table.setItem(self.tool_row, 3, empty_1_1)
  2293. self.ui.tools_table.setItem(self.tool_row, 5, empty_1_3)
  2294. font = QtGui.QFont()
  2295. font.setBold(True)
  2296. font.setWeight(75)
  2297. for k in [1, 2]:
  2298. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  2299. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  2300. self.tool_row += 1
  2301. # add a last row with the Total number of slots
  2302. empty_2 = QtWidgets.QTableWidgetItem('')
  2303. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2304. empty_2_1 = QtWidgets.QTableWidgetItem('')
  2305. empty_2_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2306. empty_2_2 = QtWidgets.QTableWidgetItem('')
  2307. empty_2_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2308. empty_2_3 = QtWidgets.QTableWidgetItem('')
  2309. empty_2_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2310. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  2311. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  2312. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2313. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2314. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  2315. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  2316. self.ui.tools_table.setItem(self.tool_row, 2, empty_2_1)
  2317. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  2318. self.ui.tools_table.setItem(self.tool_row, 5, empty_2_3)
  2319. for kl in [1, 2, 3]:
  2320. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  2321. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  2322. # sort the tool diameter column
  2323. # self.ui.tools_table.sortItems(1)
  2324. # all the tools are selected by default
  2325. self.ui.tools_table.selectColumn(0)
  2326. self.ui.tools_table.resizeColumnsToContents()
  2327. self.ui.tools_table.resizeRowsToContents()
  2328. vertical_header = self.ui.tools_table.verticalHeader()
  2329. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  2330. vertical_header.hide()
  2331. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2332. horizontal_header = self.ui.tools_table.horizontalHeader()
  2333. horizontal_header.setMinimumSectionSize(10)
  2334. horizontal_header.setDefaultSectionSize(70)
  2335. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  2336. horizontal_header.resizeSection(0, 20)
  2337. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  2338. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  2339. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  2340. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  2341. horizontal_header.resizeSection(5, 17)
  2342. self.ui.tools_table.setColumnWidth(5, 17)
  2343. # horizontal_header.setStretchLastSection(True)
  2344. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  2345. # horizontal_header.setStretchLastSection(True)
  2346. self.ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2347. self.ui.tools_table.setSortingEnabled(False)
  2348. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  2349. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  2350. if not self.drills:
  2351. self.ui.tooldia_entry.hide()
  2352. self.ui.generate_milling_button.hide()
  2353. else:
  2354. self.ui.tooldia_entry.show()
  2355. self.ui.generate_milling_button.show()
  2356. if not self.slots:
  2357. self.ui.slot_tooldia_entry.hide()
  2358. self.ui.generate_milling_slots_button.hide()
  2359. else:
  2360. self.ui.slot_tooldia_entry.show()
  2361. self.ui.generate_milling_slots_button.show()
  2362. # set the text on tool_data_label after loading the object
  2363. sel_items = self.ui.tools_table.selectedItems()
  2364. sel_rows = [it.row() for it in sel_items]
  2365. if len(sel_rows) > 1:
  2366. self.ui.tool_data_label.setText(
  2367. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  2368. )
  2369. self.ui_connect()
  2370. def set_ui(self, ui):
  2371. """
  2372. Configures the user interface for this object.
  2373. Connects options to form fields.
  2374. :param ui: User interface object.
  2375. :type ui: ExcellonObjectUI
  2376. :return: None
  2377. """
  2378. FlatCAMObj.set_ui(self, ui)
  2379. log.debug("FlatCAMExcellon.set_ui()")
  2380. self.units = self.app.defaults['units'].upper()
  2381. self.form_fields.update({
  2382. "plot": self.ui.plot_cb,
  2383. "solid": self.ui.solid_cb,
  2384. "operation": self.ui.operation_radio,
  2385. "milling_type": self.ui.milling_type_radio,
  2386. "milling_dia": self.ui.mill_dia_entry,
  2387. "cutz": self.ui.cutz_entry,
  2388. "multidepth": self.ui.mpass_cb,
  2389. "depthperpass": self.ui.maxdepth_entry,
  2390. "travelz": self.ui.travelz_entry,
  2391. "feedrate_z": self.ui.feedrate_z_entry,
  2392. "feedrate": self.ui.xyfeedrate_entry,
  2393. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  2394. "tooldia": self.ui.tooldia_entry,
  2395. "slot_tooldia": self.ui.slot_tooldia_entry,
  2396. "toolchange": self.ui.toolchange_cb,
  2397. "toolchangez": self.ui.toolchangez_entry,
  2398. "extracut": self.ui.extracut_cb,
  2399. "extracut_length": self.ui.e_cut_entry,
  2400. "spindlespeed": self.ui.spindlespeed_entry,
  2401. "dwell": self.ui.dwell_cb,
  2402. "dwelltime": self.ui.dwelltime_entry,
  2403. "startz": self.ui.estartz_entry,
  2404. "endz": self.ui.endz_entry,
  2405. "endxy": self.ui.endxy_entry,
  2406. "offset": self.ui.offset_entry,
  2407. "ppname_e": self.ui.pp_excellon_name_cb,
  2408. "ppname_g": self.ui.pp_geo_name_cb,
  2409. "z_pdepth": self.ui.pdepth_entry,
  2410. "feedrate_probe": self.ui.feedrate_probe_entry,
  2411. # "gcode_type": self.ui.excellon_gcode_type_radio
  2412. })
  2413. self.name2option = {
  2414. "e_operation": "operation",
  2415. "e_milling_type": "milling_type",
  2416. "e_milling_dia": "milling_dia",
  2417. "e_cutz": "cutz",
  2418. "e_multidepth": "multidepth",
  2419. "e_depthperpass": "depthperpass",
  2420. "e_travelz": "travelz",
  2421. "e_feedratexy": "feedrate",
  2422. "e_feedratez": "feedrate_z",
  2423. "e_fr_rapid": "feedrate_rapid",
  2424. "e_extracut": "extracut",
  2425. "e_extracut_length": "extracut_length",
  2426. "e_spindlespeed": "spindlespeed",
  2427. "e_dwell": "dwell",
  2428. "e_dwelltime": "dwelltime",
  2429. "e_offset": "offset",
  2430. }
  2431. # populate Excellon preprocessor combobox list
  2432. for name in list(self.app.preprocessors.keys()):
  2433. # the HPGL preprocessor is only for Geometry not for Excellon job therefore don't add it
  2434. if name == 'hpgl':
  2435. continue
  2436. self.ui.pp_excellon_name_cb.addItem(name)
  2437. # populate Geometry (milling) preprocessor combobox list
  2438. for name in list(self.app.preprocessors.keys()):
  2439. self.ui.pp_geo_name_cb.addItem(name)
  2440. # Fill form fields
  2441. self.to_form()
  2442. # update the changes in UI depending on the selected preprocessor in Preferences
  2443. # after this moment all the changes in the Posprocessor combo will be handled by the activated signal of the
  2444. # self.ui.pp_excellon_name_cb combobox
  2445. self.on_pp_changed()
  2446. # Show/Hide Advanced Options
  2447. if self.app.defaults["global_app_level"] == 'b':
  2448. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  2449. self.ui.tools_table.setColumnHidden(4, True)
  2450. self.ui.tools_table.setColumnHidden(5, True)
  2451. self.ui.estartz_label.hide()
  2452. self.ui.estartz_entry.hide()
  2453. self.ui.feedrate_rapid_label.hide()
  2454. self.ui.feedrate_rapid_entry.hide()
  2455. self.ui.pdepth_label.hide()
  2456. self.ui.pdepth_entry.hide()
  2457. self.ui.feedrate_probe_label.hide()
  2458. self.ui.feedrate_probe_entry.hide()
  2459. else:
  2460. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  2461. assert isinstance(self.ui, ExcellonObjectUI), \
  2462. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  2463. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2464. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  2465. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  2466. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  2467. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  2468. self.on_operation_type(val='drill')
  2469. self.ui.operation_radio.activated_custom.connect(self.on_operation_type)
  2470. self.ui.pp_excellon_name_cb.activated.connect(self.on_pp_changed)
  2471. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  2472. self.units_found = self.app.defaults['units']
  2473. # ########################################
  2474. # #######3 TEMP SETTINGS #################
  2475. # ########################################
  2476. self.ui.operation_radio.set_value("drill")
  2477. self.ui.operation_radio.setEnabled(False)
  2478. def ui_connect(self):
  2479. # selective plotting
  2480. for row in range(self.ui.tools_table.rowCount() - 2):
  2481. self.ui.tools_table.cellWidget(row, 5).clicked.connect(self.on_plot_cb_click_table)
  2482. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2483. # rows selected
  2484. self.ui.tools_table.clicked.connect(self.on_row_selection_change)
  2485. self.ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  2486. # value changed in the particular parameters of a tool
  2487. for key, option in self.name2option.items():
  2488. current_widget = self.form_fields[option]
  2489. if isinstance(current_widget, FCCheckBox):
  2490. current_widget.stateChanged.connect(self.form_to_storage)
  2491. if isinstance(current_widget, RadioSet):
  2492. current_widget.activated_custom.connect(self.form_to_storage)
  2493. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  2494. current_widget.returnPressed.connect(self.form_to_storage)
  2495. def ui_disconnect(self):
  2496. # selective plotting
  2497. for row in range(self.ui.tools_table.rowCount()):
  2498. try:
  2499. self.ui.tools_table.cellWidget(row, 5).clicked.disconnect()
  2500. except (TypeError, AttributeError):
  2501. pass
  2502. try:
  2503. self.ui.plot_cb.stateChanged.disconnect()
  2504. except (TypeError, AttributeError):
  2505. pass
  2506. # rows selected
  2507. try:
  2508. self.ui.tools_table.clicked.disconnect()
  2509. except (TypeError, AttributeError):
  2510. pass
  2511. try:
  2512. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect()
  2513. except (TypeError, AttributeError):
  2514. pass
  2515. # value changed in the particular parameters of a tool
  2516. for key, option in self.name2option.items():
  2517. current_widget = self.form_fields[option]
  2518. if isinstance(current_widget, FCCheckBox):
  2519. try:
  2520. current_widget.stateChanged.disconnect(self.form_to_storage)
  2521. except (TypeError, ValueError):
  2522. pass
  2523. if isinstance(current_widget, RadioSet):
  2524. try:
  2525. current_widget.activated_custom.disconnect(self.form_to_storage)
  2526. except (TypeError, ValueError):
  2527. pass
  2528. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  2529. try:
  2530. current_widget.returnPressed.disconnect(self.form_to_storage)
  2531. except (TypeError, ValueError):
  2532. pass
  2533. def on_row_selection_change(self):
  2534. self.ui_disconnect()
  2535. sel_rows = []
  2536. sel_items = self.ui.tools_table.selectedItems()
  2537. for it in sel_items:
  2538. sel_rows.append(it.row())
  2539. if not sel_rows:
  2540. self.ui.tool_data_label.setText(
  2541. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  2542. )
  2543. self.ui.generate_cnc_button.setDisabled(True)
  2544. self.ui.generate_milling_button.setDisabled(True)
  2545. self.ui.generate_milling_slots_button.setDisabled(True)
  2546. self.ui_connect()
  2547. return
  2548. else:
  2549. self.ui.generate_cnc_button.setDisabled(False)
  2550. self.ui.generate_milling_button.setDisabled(False)
  2551. self.ui.generate_milling_slots_button.setDisabled(False)
  2552. if len(sel_rows) == 1:
  2553. # update the QLabel that shows for which Tool we have the parameters in the UI form
  2554. tooluid = int(self.ui.tools_table.item(sel_rows[0], 0).text())
  2555. self.ui.tool_data_label.setText(
  2556. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), tooluid)
  2557. )
  2558. else:
  2559. self.ui.tool_data_label.setText(
  2560. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  2561. )
  2562. for c_row in sel_rows:
  2563. # populate the form with the data from the tool associated with the row parameter
  2564. try:
  2565. item = self.ui.tools_table.item(c_row, 0)
  2566. if type(item) is not None:
  2567. tooluid = item.text()
  2568. self.storage_to_form(self.tools[str(tooluid)]['data'])
  2569. else:
  2570. self.ui_connect()
  2571. return
  2572. except Exception as e:
  2573. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2574. self.ui_connect()
  2575. return
  2576. self.ui_connect()
  2577. def storage_to_form(self, dict_storage):
  2578. for form_key in self.form_fields:
  2579. for storage_key in dict_storage:
  2580. if form_key == storage_key and form_key not in \
  2581. ["toolchange", "toolchangez", "startz", "endz", "ppname_e", "ppname_g"]:
  2582. try:
  2583. self.form_fields[form_key].set_value(dict_storage[form_key])
  2584. except Exception as e:
  2585. log.debug("FlatCAMExcellon.storage_to_form() --> %s" % str(e))
  2586. pass
  2587. def form_to_storage(self):
  2588. if self.ui.tools_table.rowCount() == 0:
  2589. # there is no tool in tool table so we can't save the GUI elements values to storage
  2590. return
  2591. self.ui_disconnect()
  2592. widget_changed = self.sender()
  2593. wdg_objname = widget_changed.objectName()
  2594. option_changed = self.name2option[wdg_objname]
  2595. # row = self.ui.tools_table.currentRow()
  2596. rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  2597. for row in rows:
  2598. if row < 0:
  2599. row = 0
  2600. tooluid_item = int(self.ui.tools_table.item(row, 0).text())
  2601. for tooluid_key, tooluid_val in self.tools.items():
  2602. if int(tooluid_key) == tooluid_item:
  2603. new_option_value = self.form_fields[option_changed].get_value()
  2604. if option_changed in tooluid_val:
  2605. tooluid_val[option_changed] = new_option_value
  2606. if option_changed in tooluid_val['data']:
  2607. tooluid_val['data'][option_changed] = new_option_value
  2608. self.ui_connect()
  2609. def on_operation_type(self, val):
  2610. if val == 'mill':
  2611. self.ui.mill_type_label.show()
  2612. self.ui.milling_type_radio.show()
  2613. self.ui.mill_dia_label.show()
  2614. self.ui.mill_dia_entry.show()
  2615. self.ui.frxylabel.show()
  2616. self.ui.xyfeedrate_entry.show()
  2617. self.ui.extracut_cb.show()
  2618. self.ui.e_cut_entry.show()
  2619. # if 'laser' not in self.ui.pp_excellon_name_cb.get_value().lower():
  2620. # self.ui.mpass_cb.show()
  2621. # self.ui.maxdepth_entry.show()
  2622. else:
  2623. self.ui.mill_type_label.hide()
  2624. self.ui.milling_type_radio.hide()
  2625. self.ui.mill_dia_label.hide()
  2626. self.ui.mill_dia_entry.hide()
  2627. # self.ui.mpass_cb.hide()
  2628. # self.ui.maxdepth_entry.hide()
  2629. self.ui.frxylabel.hide()
  2630. self.ui.xyfeedrate_entry.hide()
  2631. self.ui.extracut_cb.hide()
  2632. self.ui.e_cut_entry.hide()
  2633. def get_selected_tools_list(self):
  2634. """
  2635. Returns the keys to the self.tools dictionary corresponding
  2636. to the selections on the tool list in the GUI.
  2637. :return: List of tools.
  2638. :rtype: list
  2639. """
  2640. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  2641. def get_selected_tools_table_items(self):
  2642. """
  2643. Returns a list of lists, each list in the list is made out of row elements
  2644. :return: List of table_tools items.
  2645. :rtype: list
  2646. """
  2647. table_tools_items = []
  2648. for x in self.ui.tools_table.selectedItems():
  2649. # from the columnCount we subtract a value of 1 which represent the last column (plot column)
  2650. # which does not have text
  2651. txt = ''
  2652. elem = []
  2653. for column in range(0, self.ui.tools_table.columnCount() - 1):
  2654. try:
  2655. txt = self.ui.tools_table.item(x.row(), column).text()
  2656. except AttributeError:
  2657. try:
  2658. txt = self.ui.tools_table.cellWidget(x.row(), column).currentText()
  2659. except AttributeError:
  2660. pass
  2661. elem.append(txt)
  2662. table_tools_items.append(deepcopy(elem))
  2663. # table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  2664. # for column in range(0, self.ui.tools_table.columnCount() - 1)])
  2665. for item in table_tools_items:
  2666. item[0] = str(item[0])
  2667. return table_tools_items
  2668. def export_excellon(self, whole, fract, e_zeros=None, form='dec', factor=1, slot_type='routing'):
  2669. """
  2670. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  2671. :return: has_slots and Excellon_code
  2672. """
  2673. excellon_code = ''
  2674. # store here if the file has slots, return 1 if any slots, 0 if only drills
  2675. has_slots = 0
  2676. # drills processing
  2677. try:
  2678. if self.drills:
  2679. length = whole + fract
  2680. for tool in self.tools:
  2681. excellon_code += 'T0%s\n' % str(tool) if int(tool) < 10 else 'T%s\n' % str(tool)
  2682. for drill in self.drills:
  2683. if form == 'dec' and tool == drill['tool']:
  2684. drill_x = drill['point'].x * factor
  2685. drill_y = drill['point'].y * factor
  2686. excellon_code += "X{:.{dec}f}Y{:.{dec}f}\n".format(drill_x, drill_y, dec=fract)
  2687. elif e_zeros == 'LZ' and tool == drill['tool']:
  2688. drill_x = drill['point'].x * factor
  2689. drill_y = drill['point'].y * factor
  2690. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract)
  2691. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract)
  2692. # extract whole part and decimal part
  2693. exc_x_formatted = exc_x_formatted.partition('.')
  2694. exc_y_formatted = exc_y_formatted.partition('.')
  2695. # left padd the 'whole' part with zeros
  2696. x_whole = exc_x_formatted[0].rjust(whole, '0')
  2697. y_whole = exc_y_formatted[0].rjust(whole, '0')
  2698. # restore the coordinate padded in the left with 0 and added the decimal part
  2699. # without the decinal dot
  2700. exc_x_formatted = x_whole + exc_x_formatted[2]
  2701. exc_y_formatted = y_whole + exc_y_formatted[2]
  2702. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  2703. yform=exc_y_formatted)
  2704. elif tool == drill['tool']:
  2705. drill_x = drill['point'].x * factor
  2706. drill_y = drill['point'].y * factor
  2707. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract).replace('.', '')
  2708. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract).replace('.', '')
  2709. # pad with rear zeros
  2710. exc_x_formatted.ljust(length, '0')
  2711. exc_y_formatted.ljust(length, '0')
  2712. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  2713. yform=exc_y_formatted)
  2714. except Exception as e:
  2715. log.debug(str(e))
  2716. # slots processing
  2717. try:
  2718. if self.slots:
  2719. has_slots = 1
  2720. for tool in self.tools:
  2721. excellon_code += 'G05\n'
  2722. if int(tool) < 10:
  2723. excellon_code += 'T0' + str(tool) + '\n'
  2724. else:
  2725. excellon_code += 'T' + str(tool) + '\n'
  2726. for slot in self.slots:
  2727. if form == 'dec' and tool == slot['tool']:
  2728. start_slot_x = slot['start'].x * factor
  2729. start_slot_y = slot['start'].y * factor
  2730. stop_slot_x = slot['stop'].x * factor
  2731. stop_slot_y = slot['stop'].y * factor
  2732. if slot_type == 'routing':
  2733. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM15\n".format(start_slot_x,
  2734. start_slot_y,
  2735. dec=fract)
  2736. excellon_code += "G01X{:.{dec}f}Y{:.{dec}f}\nM16\n".format(stop_slot_x,
  2737. stop_slot_y,
  2738. dec=fract)
  2739. elif slot_type == 'drilling':
  2740. excellon_code += "X{:.{dec}f}Y{:.{dec}f}G85X{:.{dec}f}Y{:.{dec}f}\nG05\n".format(
  2741. start_slot_x, start_slot_y, stop_slot_x, stop_slot_y, dec=fract
  2742. )
  2743. elif e_zeros == 'LZ' and tool == slot['tool']:
  2744. start_slot_x = slot['start'].x * factor
  2745. start_slot_y = slot['start'].y * factor
  2746. stop_slot_x = slot['stop'].x * factor
  2747. stop_slot_y = slot['stop'].y * factor
  2748. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  2749. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  2750. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  2751. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  2752. # extract whole part and decimal part
  2753. start_slot_x_formatted = start_slot_x_formatted.partition('.')
  2754. start_slot_y_formatted = start_slot_y_formatted.partition('.')
  2755. stop_slot_x_formatted = stop_slot_x_formatted.partition('.')
  2756. stop_slot_y_formatted = stop_slot_y_formatted.partition('.')
  2757. # left padd the 'whole' part with zeros
  2758. start_x_whole = start_slot_x_formatted[0].rjust(whole, '0')
  2759. start_y_whole = start_slot_y_formatted[0].rjust(whole, '0')
  2760. stop_x_whole = stop_slot_x_formatted[0].rjust(whole, '0')
  2761. stop_y_whole = stop_slot_y_formatted[0].rjust(whole, '0')
  2762. # restore the coordinate padded in the left with 0 and added the decimal part
  2763. # without the decinal dot
  2764. start_slot_x_formatted = start_x_whole + start_slot_x_formatted[2]
  2765. start_slot_y_formatted = start_y_whole + start_slot_y_formatted[2]
  2766. stop_slot_x_formatted = stop_x_whole + stop_slot_x_formatted[2]
  2767. stop_slot_y_formatted = stop_y_whole + stop_slot_y_formatted[2]
  2768. if slot_type == 'routing':
  2769. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  2770. ystart=start_slot_y_formatted)
  2771. excellon_code += "G01X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  2772. ystop=stop_slot_y_formatted)
  2773. elif slot_type == 'drilling':
  2774. excellon_code += "{xstart}Y{ystart}G85X{xstop}Y{ystop}\nG05\n".format(
  2775. xstart=start_slot_x_formatted, ystart=start_slot_y_formatted,
  2776. xstop=stop_slot_x_formatted, ystop=stop_slot_y_formatted
  2777. )
  2778. elif tool == slot['tool']:
  2779. start_slot_x = slot['start'].x * factor
  2780. start_slot_y = slot['start'].y * factor
  2781. stop_slot_x = slot['stop'].x * factor
  2782. stop_slot_y = slot['stop'].y * factor
  2783. length = whole + fract
  2784. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  2785. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  2786. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  2787. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  2788. # pad with rear zeros
  2789. start_slot_x_formatted.ljust(length, '0')
  2790. start_slot_y_formatted.ljust(length, '0')
  2791. stop_slot_x_formatted.ljust(length, '0')
  2792. stop_slot_y_formatted.ljust(length, '0')
  2793. if slot_type == 'routing':
  2794. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  2795. ystart=start_slot_y_formatted)
  2796. excellon_code += "G01X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  2797. ystop=stop_slot_y_formatted)
  2798. elif slot_type == 'drilling':
  2799. excellon_code += "{xstart}Y{ystart}G85X{xstop}Y{ystop}\nG05\n".format(
  2800. xstart=start_slot_x_formatted, ystart=start_slot_y_formatted,
  2801. xstop=stop_slot_x_formatted, ystop=stop_slot_y_formatted
  2802. )
  2803. except Exception as e:
  2804. log.debug(str(e))
  2805. if not self.drills and not self.slots:
  2806. log.debug("FlatCAMObj.FlatCAMExcellon.export_excellon() --> Excellon Object is empty: no drills, no slots.")
  2807. return 'fail'
  2808. return has_slots, excellon_code
  2809. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, plot=False, use_thread=False):
  2810. """
  2811. Note: This method is a good template for generic operations as
  2812. it takes it's options from parameters or otherwise from the
  2813. object's options and returns a (success, msg) tuple as feedback
  2814. for shell operations.
  2815. :return: Success/failure condition tuple (bool, str).
  2816. :rtype: tuple
  2817. """
  2818. # Get the tools from the list. These are keys
  2819. # to self.tools
  2820. if tools is None:
  2821. tools = self.get_selected_tools_list()
  2822. if outname is None:
  2823. outname = self.options["name"] + "_mill"
  2824. if tooldia is None:
  2825. tooldia = float(self.options["tooldia"])
  2826. # Sort tools by diameter. items() -> [('name', diameter), ...]
  2827. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  2828. sort = []
  2829. for k, v in self.tools.items():
  2830. sort.append((k, v.get('C')))
  2831. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  2832. if tools == "all":
  2833. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  2834. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  2835. if len(tools) == 0:
  2836. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2837. _("Please select one or more tools from the list and try again."))
  2838. return False, "Error: No tools."
  2839. for tool in tools:
  2840. if tooldia > self.tools[tool]["C"]:
  2841. self.app.inform.emit(
  2842. '[ERROR_NOTCL] %s %s: %s' % (
  2843. _("Milling tool for DRILLS is larger than hole size. Cancelled."),
  2844. _("Tool"),
  2845. str(tool)
  2846. )
  2847. )
  2848. return False, "Error: Milling tool is larger than hole."
  2849. def geo_init(geo_obj, app_obj):
  2850. assert isinstance(geo_obj, FlatCAMGeometry), \
  2851. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2852. # ## Add properties to the object
  2853. # get the tool_table items in a list of row items
  2854. tool_table_items = self.get_selected_tools_table_items()
  2855. # insert an information only element in the front
  2856. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  2857. geo_obj.options['Tools_in_use'] = tool_table_items
  2858. geo_obj.options['type'] = 'Excellon Geometry'
  2859. geo_obj.options["cnctooldia"] = str(tooldia)
  2860. geo_obj.solid_geometry = []
  2861. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  2862. # for FlatCAM is 6 decimals,
  2863. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  2864. for hole in self.drills:
  2865. if hole['tool'] in tools:
  2866. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  2867. if buffer_value == 0:
  2868. geo_obj.solid_geometry.append(
  2869. Point(hole['point']).buffer(0.0000001).exterior)
  2870. else:
  2871. geo_obj.solid_geometry.append(
  2872. Point(hole['point']).buffer(buffer_value).exterior)
  2873. if use_thread:
  2874. def geo_thread(app_obj):
  2875. app_obj.new_object("geometry", outname, geo_init, plot=plot)
  2876. # Create a promise with the new name
  2877. self.app.collection.promise(outname)
  2878. # Send to worker
  2879. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  2880. else:
  2881. self.app.new_object("geometry", outname, geo_init, plot=plot)
  2882. return True, ""
  2883. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, plot=True, use_thread=False):
  2884. """
  2885. Note: This method is a good template for generic operations as
  2886. it takes it's options from parameters or otherwise from the
  2887. object's options and returns a (success, msg) tuple as feedback
  2888. for shell operations.
  2889. :return: Success/failure condition tuple (bool, str).
  2890. :rtype: tuple
  2891. """
  2892. # Get the tools from the list. These are keys
  2893. # to self.tools
  2894. if tools is None:
  2895. tools = self.get_selected_tools_list()
  2896. if outname is None:
  2897. outname = self.options["name"] + "_mill"
  2898. if tooldia is None:
  2899. tooldia = float(self.options["slot_tooldia"])
  2900. # Sort tools by diameter. items() -> [('name', diameter), ...]
  2901. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  2902. sort = []
  2903. for k, v in self.tools.items():
  2904. sort.append((k, v.get('C')))
  2905. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  2906. if tools == "all":
  2907. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  2908. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  2909. if len(tools) == 0:
  2910. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2911. _("Please select one or more tools from the list and try again."))
  2912. return False, "Error: No tools."
  2913. for tool in tools:
  2914. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  2915. adj_toolstable_tooldia = float('%.*f' % (self.decimals, float(tooldia)))
  2916. adj_file_tooldia = float('%.*f' % (self.decimals, float(self.tools[tool]["C"])))
  2917. if adj_toolstable_tooldia > adj_file_tooldia + 0.0001:
  2918. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2919. _("Milling tool for SLOTS is larger than hole size. Cancelled."))
  2920. return False, "Error: Milling tool is larger than hole."
  2921. def geo_init(geo_obj, app_obj):
  2922. assert isinstance(geo_obj, FlatCAMGeometry), \
  2923. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2924. # ## Add properties to the object
  2925. # get the tool_table items in a list of row items
  2926. tool_table_items = self.get_selected_tools_table_items()
  2927. # insert an information only element in the front
  2928. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  2929. geo_obj.options['Tools_in_use'] = tool_table_items
  2930. geo_obj.options['type'] = 'Excellon Geometry'
  2931. geo_obj.options["cnctooldia"] = str(tooldia)
  2932. geo_obj.solid_geometry = []
  2933. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  2934. # for FlatCAM is 6 decimals,
  2935. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  2936. for slot in self.slots:
  2937. if slot['tool'] in tools:
  2938. toolstable_tool = float('%.*f' % (self.decimals, float(tooldia)))
  2939. file_tool = float('%.*f' % (self.decimals, float(self.tools[tool]["C"])))
  2940. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  2941. # for the file_tool (tooldia actually)
  2942. buffer_value = float(file_tool / 2) - float(toolstable_tool / 2) + 0.0001
  2943. if buffer_value == 0:
  2944. start = slot['start']
  2945. stop = slot['stop']
  2946. lines_string = LineString([start, stop])
  2947. poly = lines_string.buffer(0.0000001, int(self.geo_steps_per_circle)).exterior
  2948. geo_obj.solid_geometry.append(poly)
  2949. else:
  2950. start = slot['start']
  2951. stop = slot['stop']
  2952. lines_string = LineString([start, stop])
  2953. poly = lines_string.buffer(buffer_value, int(self.geo_steps_per_circle)).exterior
  2954. geo_obj.solid_geometry.append(poly)
  2955. if use_thread:
  2956. def geo_thread(app_obj):
  2957. app_obj.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  2958. # Create a promise with the new name
  2959. self.app.collection.promise(outname)
  2960. # Send to worker
  2961. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  2962. else:
  2963. self.app.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  2964. return True, ""
  2965. def on_generate_milling_button_click(self, *args):
  2966. self.app.report_usage("excellon_on_create_milling_drills button")
  2967. self.read_form()
  2968. self.generate_milling_drills(use_thread=False)
  2969. def on_generate_milling_slots_button_click(self, *args):
  2970. self.app.report_usage("excellon_on_create_milling_slots_button")
  2971. self.read_form()
  2972. self.generate_milling_slots(use_thread=False)
  2973. def on_pp_changed(self):
  2974. current_pp = self.ui.pp_excellon_name_cb.get_value()
  2975. if "toolchange_probe" in current_pp.lower():
  2976. self.ui.pdepth_entry.setVisible(True)
  2977. self.ui.pdepth_label.show()
  2978. self.ui.feedrate_probe_entry.setVisible(True)
  2979. self.ui.feedrate_probe_label.show()
  2980. else:
  2981. self.ui.pdepth_entry.setVisible(False)
  2982. self.ui.pdepth_label.hide()
  2983. self.ui.feedrate_probe_entry.setVisible(False)
  2984. self.ui.feedrate_probe_label.hide()
  2985. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  2986. self.ui.feedrate_rapid_label.show()
  2987. self.ui.feedrate_rapid_entry.show()
  2988. else:
  2989. self.ui.feedrate_rapid_label.hide()
  2990. self.ui.feedrate_rapid_entry.hide()
  2991. if 'laser' in current_pp.lower():
  2992. self.ui.cutzlabel.hide()
  2993. self.ui.cutz_entry.hide()
  2994. try:
  2995. self.ui.mpass_cb.hide()
  2996. self.ui.maxdepth_entry.hide()
  2997. except AttributeError:
  2998. pass
  2999. if 'marlin' in current_pp.lower():
  3000. self.ui.travelzlabel.setText('%s:' % _("Focus Z"))
  3001. self.ui.endz_label.show()
  3002. self.ui.endz_entry.show()
  3003. else:
  3004. self.ui.travelzlabel.hide()
  3005. self.ui.travelz_entry.hide()
  3006. self.ui.endz_label.hide()
  3007. self.ui.endz_entry.hide()
  3008. try:
  3009. self.ui.frzlabel.hide()
  3010. self.ui.feedrate_z_entry.hide()
  3011. except AttributeError:
  3012. pass
  3013. self.ui.dwell_cb.hide()
  3014. self.ui.dwelltime_entry.hide()
  3015. self.ui.spindle_label.setText('%s:' % _("Laser Power"))
  3016. try:
  3017. self.ui.tool_offset_label.hide()
  3018. self.ui.offset_entry.hide()
  3019. except AttributeError:
  3020. pass
  3021. else:
  3022. self.ui.cutzlabel.show()
  3023. self.ui.cutz_entry.show()
  3024. try:
  3025. self.ui.mpass_cb.show()
  3026. self.ui.maxdepth_entry.show()
  3027. except AttributeError:
  3028. pass
  3029. self.ui.travelzlabel.setText('%s:' % _('Travel Z'))
  3030. self.ui.travelzlabel.show()
  3031. self.ui.travelz_entry.show()
  3032. self.ui.endz_label.show()
  3033. self.ui.endz_entry.show()
  3034. try:
  3035. self.ui.frzlabel.show()
  3036. self.ui.feedrate_z_entry.show()
  3037. except AttributeError:
  3038. pass
  3039. self.ui.dwell_cb.show()
  3040. self.ui.dwelltime_entry.show()
  3041. self.ui.spindle_label.setText('%s:' % _('Spindle speed'))
  3042. try:
  3043. self.ui.tool_offset_lbl.show()
  3044. self.ui.offset_entry.show()
  3045. except AttributeError:
  3046. pass
  3047. def on_create_cncjob_button_click(self, *args):
  3048. self.app.report_usage("excellon_on_create_cncjob_button")
  3049. self.read_form()
  3050. # Get the tools from the list
  3051. tools = self.get_selected_tools_list()
  3052. if len(tools) == 0:
  3053. # if there is a single tool in the table (remember that the last 2 rows are for totals and do not count in
  3054. # tool number) it means that there are 3 rows (1 tool and 2 totals).
  3055. # in this case regardless of the selection status of that tool, use it.
  3056. if self.ui.tools_table.rowCount() == 3:
  3057. tools.append(self.ui.tools_table.item(0, 0).text())
  3058. else:
  3059. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3060. _("Please select one or more tools from the list and try again."))
  3061. return
  3062. xmin = self.options['xmin']
  3063. ymin = self.options['ymin']
  3064. xmax = self.options['xmax']
  3065. ymax = self.options['ymax']
  3066. job_name = self.options["name"] + "_cnc"
  3067. pp_excellon_name = self.options["ppname_e"]
  3068. # Object initialization function for app.new_object()
  3069. def job_init(job_obj, app_obj):
  3070. assert isinstance(job_obj, FlatCAMCNCjob), \
  3071. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3072. # get the tool_table items in a list of row items
  3073. tool_table_items = self.get_selected_tools_table_items()
  3074. # insert an information only element in the front
  3075. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  3076. # ## Add properties to the object
  3077. job_obj.origin_kind = 'excellon'
  3078. job_obj.options['Tools_in_use'] = tool_table_items
  3079. job_obj.options['type'] = 'Excellon'
  3080. job_obj.options['ppname_e'] = pp_excellon_name
  3081. job_obj.multidepth = self.options["multidepth"]
  3082. job_obj.z_depthpercut = self.options["depthperpass"]
  3083. job_obj.z_move = float(self.options["travelz"])
  3084. job_obj.feedrate = float(self.options["feedrate_z"])
  3085. job_obj.z_feedrate = float(self.options["feedrate_z"])
  3086. job_obj.feedrate_rapid = float(self.options["feedrate_rapid"])
  3087. job_obj.spindlespeed = float(self.options["spindlespeed"]) if self.options["spindlespeed"] != 0 else None
  3088. job_obj.spindledir = self.app.defaults['excellon_spindledir']
  3089. job_obj.dwell = self.options["dwell"]
  3090. job_obj.dwelltime = float(self.options["dwelltime"])
  3091. job_obj.pp_excellon_name = pp_excellon_name
  3092. job_obj.toolchange_xy_type = "excellon"
  3093. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  3094. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  3095. job_obj.options['xmin'] = xmin
  3096. job_obj.options['ymin'] = ymin
  3097. job_obj.options['xmax'] = xmax
  3098. job_obj.options['ymax'] = ymax
  3099. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3100. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3101. job_obj.z_cut = float(self.options['cutz'])
  3102. job_obj.toolchange = self.options["toolchange"]
  3103. job_obj.xy_toolchange = self.app.defaults["excellon_toolchangexy"]
  3104. job_obj.z_toolchange = float(self.options["toolchangez"])
  3105. job_obj.startz = float(self.options["startz"]) if self.options["startz"] else None
  3106. job_obj.endz = float(self.options["endz"])
  3107. job_obj.xy_end = self.options["endxy"]
  3108. job_obj.excellon_optimization_type = self.app.defaults["excellon_optimization_type"]
  3109. tools_csv = ','.join(tools)
  3110. ret_val = job_obj.generate_from_excellon_by_tool(self, tools_csv, use_ui=True)
  3111. if ret_val == 'fail':
  3112. return 'fail'
  3113. job_obj.gcode_parse()
  3114. job_obj.create_geometry()
  3115. # To be run in separate thread
  3116. def job_thread(app_obj):
  3117. with self.app.proc_container.new(_("Generating CNC Code")):
  3118. app_obj.new_object("cncjob", job_name, job_init)
  3119. # Create promise for the new name.
  3120. self.app.collection.promise(job_name)
  3121. # Send to worker
  3122. # self.app.worker.add_task(job_thread, [self.app])
  3123. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3124. def convert_units(self, units):
  3125. log.debug("FlatCAMObj.FlatCAMExcellon.convert_units()")
  3126. Excellon.convert_units(self, units)
  3127. # factor = Excellon.convert_units(self, units)
  3128. # self.options['drillz'] = float(self.options['drillz']) * factor
  3129. # self.options['travelz'] = float(self.options['travelz']) * factor
  3130. # self.options['feedrate'] = float(self.options['feedrate']) * factor
  3131. # self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  3132. # self.options['toolchangez'] = float(self.options['toolchangez']) * factor
  3133. #
  3134. # if self.app.defaults["excellon_toolchangexy"] == '':
  3135. # self.options['toolchangexy'] = "0.0, 0.0"
  3136. # else:
  3137. # coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  3138. # if len(coords_xy) < 2:
  3139. # self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  3140. # "in the format (x, y) \n"
  3141. # "but now there is only one value, not two. "))
  3142. # return 'fail'
  3143. # coords_xy[0] *= factor
  3144. # coords_xy[1] *= factor
  3145. # self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3146. #
  3147. # if self.options['startz'] is not None:
  3148. # self.options['startz'] = float(self.options['startz']) * factor
  3149. # self.options['endz'] = float(self.options['endz']) * factor
  3150. def on_solid_cb_click(self, *args):
  3151. if self.muted_ui:
  3152. return
  3153. self.read_form_item('solid')
  3154. self.plot()
  3155. def on_plot_cb_click(self, *args):
  3156. if self.muted_ui:
  3157. return
  3158. self.plot()
  3159. self.read_form_item('plot')
  3160. self.ui_disconnect()
  3161. cb_flag = self.ui.plot_cb.isChecked()
  3162. for row in range(self.ui.tools_table.rowCount() - 2):
  3163. table_cb = self.ui.tools_table.cellWidget(row, 5)
  3164. if cb_flag:
  3165. table_cb.setChecked(True)
  3166. else:
  3167. table_cb.setChecked(False)
  3168. self.ui_connect()
  3169. def on_plot_cb_click_table(self):
  3170. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  3171. self.ui_disconnect()
  3172. # cw = self.sender()
  3173. # cw_index = self.ui.tools_table.indexAt(cw.pos())
  3174. # cw_row = cw_index.row()
  3175. check_row = 0
  3176. self.shapes.clear(update=True)
  3177. for tool_key in self.tools:
  3178. solid_geometry = self.tools[tool_key]['solid_geometry']
  3179. # find the geo_tool_table row associated with the tool_key
  3180. for row in range(self.ui.tools_table.rowCount()):
  3181. tool_item = int(self.ui.tools_table.item(row, 0).text())
  3182. if tool_item == int(tool_key):
  3183. check_row = row
  3184. break
  3185. if self.ui.tools_table.cellWidget(check_row, 5).isChecked():
  3186. self.options['plot'] = True
  3187. # self.plot_element(element=solid_geometry, visible=True)
  3188. # Plot excellon (All polygons?)
  3189. if self.options["solid"]:
  3190. for geo in solid_geometry:
  3191. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  3192. visible=self.options['plot'],
  3193. layer=2)
  3194. else:
  3195. for geo in solid_geometry:
  3196. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  3197. for ints in geo.interiors:
  3198. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  3199. self.shapes.redraw()
  3200. # make sure that the general plot is disabled if one of the row plot's are disabled and
  3201. # if all the row plot's are enabled also enable the general plot checkbox
  3202. cb_cnt = 0
  3203. total_row = self.ui.tools_table.rowCount()
  3204. for row in range(total_row - 2):
  3205. if self.ui.tools_table.cellWidget(row, 5).isChecked():
  3206. cb_cnt += 1
  3207. else:
  3208. cb_cnt -= 1
  3209. if cb_cnt < total_row - 2:
  3210. self.ui.plot_cb.setChecked(False)
  3211. else:
  3212. self.ui.plot_cb.setChecked(True)
  3213. self.ui_connect()
  3214. def plot(self, visible=None, kind=None):
  3215. # Does all the required setup and returns False
  3216. # if the 'ptint' option is set to False.
  3217. if not FlatCAMObj.plot(self):
  3218. return
  3219. # try:
  3220. # # Plot Excellon (All polygons?)
  3221. # if self.options["solid"]:
  3222. # for tool in self.tools:
  3223. # for geo in self.tools[tool]['solid_geometry']:
  3224. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  3225. # visible=self.options['plot'],
  3226. # layer=2)
  3227. # else:
  3228. # for tool in self.tools:
  3229. # for geo in self.tools[tool]['solid_geometry']:
  3230. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  3231. # for ints in geo.interiors:
  3232. # self.add_shape(shape=ints, color='orange', visible=self.options['plot'])
  3233. #
  3234. # self.shapes.redraw()
  3235. # return
  3236. # except (ObjectDeleted, AttributeError, KeyError):
  3237. # self.shapes.clear(update=True)
  3238. # this stays for compatibility reasons, in case we try to open old projects
  3239. try:
  3240. __ = iter(self.solid_geometry)
  3241. except TypeError:
  3242. self.solid_geometry = [self.solid_geometry]
  3243. visible = visible if visible else self.options['plot']
  3244. try:
  3245. # Plot Excellon (All polygons?)
  3246. if self.options["solid"]:
  3247. for geo in self.solid_geometry:
  3248. self.add_shape(shape=geo,
  3249. color=self.outline_color,
  3250. face_color=self.fill_color,
  3251. visible=visible,
  3252. layer=2)
  3253. else:
  3254. for geo in self.solid_geometry:
  3255. self.add_shape(shape=geo.exterior, color='red', visible=visible)
  3256. for ints in geo.interiors:
  3257. self.add_shape(shape=ints, color='orange', visible=visible)
  3258. self.shapes.redraw()
  3259. except (ObjectDeleted, AttributeError):
  3260. self.shapes.clear(update=True)
  3261. def on_apply_param_to_all_clicked(self):
  3262. if self.ui.tools_table.rowCount() == 0:
  3263. # there is no tool in tool table so we can't save the GUI elements values to storage
  3264. log.debug("FlatCAMExcellon.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  3265. return
  3266. self.ui_disconnect()
  3267. row = self.ui.tools_table.currentRow()
  3268. if row < 0:
  3269. row = 0
  3270. tooluid_item = int(self.ui.tools_table.item(row, 0).text())
  3271. temp_tool_data = {}
  3272. for tooluid_key, tooluid_val in self.tools.items():
  3273. if int(tooluid_key) == tooluid_item:
  3274. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  3275. # the current row in the tool table
  3276. temp_tool_data = tooluid_val['data']
  3277. break
  3278. for tooluid_key, tooluid_val in self.tools.items():
  3279. tooluid_val['data'] = deepcopy(temp_tool_data)
  3280. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  3281. self.ui_connect()
  3282. class FlatCAMGeometry(FlatCAMObj, Geometry):
  3283. """
  3284. Geometric object not associated with a specific
  3285. format.
  3286. """
  3287. optionChanged = QtCore.pyqtSignal(str)
  3288. ui_type = GeometryObjectUI
  3289. def __init__(self, name):
  3290. self.decimals = self.app.decimals
  3291. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  3292. FlatCAMObj.__init__(self, name)
  3293. Geometry.__init__(self, geo_steps_per_circle=self.circle_steps)
  3294. self.kind = "geometry"
  3295. self.options.update({
  3296. "plot": True,
  3297. "cutz": -0.002,
  3298. "vtipdia": 0.1,
  3299. "vtipangle": 30,
  3300. "travelz": 0.1,
  3301. "feedrate": 5.0,
  3302. "feedrate_z": 5.0,
  3303. "feedrate_rapid": 5.0,
  3304. "spindlespeed": 0,
  3305. "dwell": True,
  3306. "dwelltime": 1000,
  3307. "multidepth": False,
  3308. "depthperpass": 0.002,
  3309. "extracut": False,
  3310. "extracut_length": 0.1,
  3311. "endz": 2.0,
  3312. "endxy": '',
  3313. "startz": None,
  3314. "toolchange": False,
  3315. "toolchangez": 1.0,
  3316. "toolchangexy": "0.0, 0.0",
  3317. "ppname_g": 'default',
  3318. "z_pdepth": -0.02,
  3319. "feedrate_probe": 3.0,
  3320. })
  3321. if "cnctooldia" not in self.options:
  3322. if type(self.app.defaults["geometry_cnctooldia"]) == float:
  3323. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  3324. else:
  3325. try:
  3326. tools_string = self.app.defaults["geometry_cnctooldia"].split(",")
  3327. tools_diameters = [eval(a) for a in tools_string if a != '']
  3328. self.options["cnctooldia"] = tools_diameters[0] if tools_diameters else 0.0
  3329. except Exception as e:
  3330. log.debug("FlatCAMObj.FlatCAMGeometry.init() --> %s" % str(e))
  3331. self.options["startz"] = self.app.defaults["geometry_startz"]
  3332. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  3333. self.tooluid = 0
  3334. '''
  3335. self.tools = {}
  3336. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  3337. tool_id of the tools and the value is another dict that will hold the data under the following form:
  3338. {tooluid: {
  3339. 'tooldia': 1,
  3340. 'offset': 'Path',
  3341. 'offset_value': 0.0
  3342. 'type': 'Rough',
  3343. 'tool_type': 'C1',
  3344. 'data': self.default_tool_data
  3345. 'solid_geometry': []
  3346. }
  3347. }
  3348. '''
  3349. self.tools = {}
  3350. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  3351. # those elements are the ones used for generating GCode
  3352. self.sel_tools = {}
  3353. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  3354. self.type_item_options = [_("Iso"), _("Rough"), _("Finish")]
  3355. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  3356. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  3357. self.v_tool_type = None
  3358. # flag to store if the Geometry is type 'multi-geometry' meaning that each tool has it's own geometry
  3359. # the default value is False
  3360. self.multigeo = False
  3361. # flag to store if the geometry is part of a special group of geometries that can't be processed by the default
  3362. # engine of FlatCAM. Most likely are generated by some of tools and are special cases of geometries.
  3363. self.special_group = None
  3364. self.old_pp_state = self.app.defaults["geometry_multidepth"]
  3365. self.old_toolchangeg_state = self.app.defaults["geometry_toolchange"]
  3366. self.units_found = self.app.defaults['units']
  3367. # this variable can be updated by the Object that generates the geometry
  3368. self.tool_type = 'C1'
  3369. # save here the old value for the Cut Z before it is changed by selecting a V-shape type tool in the tool table
  3370. self.old_cutz = self.app.defaults["geometry_cutz"]
  3371. self.fill_color = self.app.defaults['geometry_plot_line']
  3372. self.outline_color = self.app.defaults['geometry_plot_line']
  3373. self.alpha_level = 'FF'
  3374. self.param_fields = {}
  3375. # Attributes to be included in serialization
  3376. # Always append to it because it carries contents
  3377. # from predecessors.
  3378. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  3379. def build_ui(self):
  3380. self.ui_disconnect()
  3381. FlatCAMObj.build_ui(self)
  3382. self.units = self.app.defaults['units']
  3383. tool_idx = 0
  3384. n = len(self.tools)
  3385. self.ui.geo_tools_table.setRowCount(n)
  3386. for tooluid_key, tooluid_value in self.tools.items():
  3387. tool_idx += 1
  3388. row_no = tool_idx - 1
  3389. tool_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  3390. tool_id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  3391. self.ui.geo_tools_table.setItem(row_no, 0, tool_id) # Tool name/id
  3392. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  3393. # There are no tool bits in MM with more than 3 decimals diameter.
  3394. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  3395. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(tooluid_value['tooldia'])))
  3396. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3397. offset_item = FCComboBox()
  3398. for item in self.offset_item_options:
  3399. offset_item.addItem(item)
  3400. # offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  3401. idx = offset_item.findText(tooluid_value['offset'])
  3402. offset_item.setCurrentIndex(idx)
  3403. type_item = FCComboBox()
  3404. for item in self.type_item_options:
  3405. type_item.addItem(item)
  3406. # type_item.setStyleSheet('background-color: rgb(255,255,255)')
  3407. idx = type_item.findText(tooluid_value['type'])
  3408. type_item.setCurrentIndex(idx)
  3409. tool_type_item = FCComboBox()
  3410. for item in self.tool_type_item_options:
  3411. tool_type_item.addItem(item)
  3412. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  3413. idx = tool_type_item.findText(tooluid_value['tool_type'])
  3414. tool_type_item.setCurrentIndex(idx)
  3415. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  3416. plot_item = FCCheckBox()
  3417. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  3418. if self.ui.plot_cb.isChecked():
  3419. plot_item.setChecked(True)
  3420. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  3421. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  3422. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  3423. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  3424. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  3425. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  3426. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  3427. try:
  3428. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  3429. except Exception as e:
  3430. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools. Error: %s" % str(e))
  3431. # make the diameter column editable
  3432. for row in range(tool_idx):
  3433. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  3434. QtCore.Qt.ItemIsEditable |
  3435. QtCore.Qt.ItemIsEnabled)
  3436. # sort the tool diameter column
  3437. # self.ui.geo_tools_table.sortItems(1)
  3438. # all the tools are selected by default
  3439. # self.ui.geo_tools_table.selectColumn(0)
  3440. self.ui.geo_tools_table.resizeColumnsToContents()
  3441. self.ui.geo_tools_table.resizeRowsToContents()
  3442. vertical_header = self.ui.geo_tools_table.verticalHeader()
  3443. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  3444. vertical_header.hide()
  3445. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3446. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  3447. horizontal_header.setMinimumSectionSize(10)
  3448. horizontal_header.setDefaultSectionSize(70)
  3449. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  3450. horizontal_header.resizeSection(0, 20)
  3451. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  3452. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  3453. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  3454. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  3455. horizontal_header.resizeSection(4, 40)
  3456. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  3457. horizontal_header.resizeSection(4, 17)
  3458. # horizontal_header.setStretchLastSection(True)
  3459. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3460. self.ui.geo_tools_table.setColumnWidth(0, 20)
  3461. self.ui.geo_tools_table.setColumnWidth(4, 40)
  3462. self.ui.geo_tools_table.setColumnWidth(6, 17)
  3463. # self.ui.geo_tools_table.setSortingEnabled(True)
  3464. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  3465. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  3466. # update UI for all rows - useful after units conversion but only if there is at least one row
  3467. row_cnt = self.ui.geo_tools_table.rowCount()
  3468. if row_cnt > 0:
  3469. for r in range(row_cnt):
  3470. self.update_ui(r)
  3471. # select only the first tool / row
  3472. selected_row = 0
  3473. try:
  3474. self.select_tools_table_row(selected_row, clearsel=True)
  3475. # update the Geometry UI
  3476. self.update_ui()
  3477. except Exception as e:
  3478. # when the tools table is empty there will be this error but once the table is populated it will go away
  3479. log.debug(str(e))
  3480. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  3481. # and can create some problems
  3482. if self.multigeo is False:
  3483. self.ui.geo_tools_table.setColumnHidden(6, True)
  3484. else:
  3485. self.ui.geo_tools_table.setColumnHidden(6, False)
  3486. self.set_tool_offset_visibility(selected_row)
  3487. # HACK: for whatever reasons the name in Selected tab is reverted to the original one after a successful rename
  3488. # done in the collection view but only for Geometry objects. Perhaps some references remains. Should be fixed.
  3489. self.ui.name_entry.set_value(self.options['name'])
  3490. self.ui_connect()
  3491. self.ui.e_cut_entry.setDisabled(False) if self.ui.extracut_cb.get_value() else \
  3492. self.ui.e_cut_entry.setDisabled(True)
  3493. # set the text on tool_data_label after loading the object
  3494. sel_rows = []
  3495. sel_items = self.ui.geo_tools_table.selectedItems()
  3496. for it in sel_items:
  3497. sel_rows.append(it.row())
  3498. if len(sel_rows) > 1:
  3499. self.ui.tool_data_label.setText(
  3500. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  3501. )
  3502. def set_ui(self, ui):
  3503. FlatCAMObj.set_ui(self, ui)
  3504. log.debug("FlatCAMGeometry.set_ui()")
  3505. assert isinstance(self.ui, GeometryObjectUI), \
  3506. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  3507. self.units = self.app.defaults['units'].upper()
  3508. self.units_found = self.app.defaults['units']
  3509. # populate preprocessor names in the combobox
  3510. for name in list(self.app.preprocessors.keys()):
  3511. self.ui.pp_geometry_name_cb.addItem(name)
  3512. self.form_fields.update({
  3513. "plot": self.ui.plot_cb,
  3514. "cutz": self.ui.cutz_entry,
  3515. "vtipdia": self.ui.tipdia_entry,
  3516. "vtipangle": self.ui.tipangle_entry,
  3517. "travelz": self.ui.travelz_entry,
  3518. "feedrate": self.ui.cncfeedrate_entry,
  3519. "feedrate_z": self.ui.feedrate_z_entry,
  3520. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  3521. "spindlespeed": self.ui.cncspindlespeed_entry,
  3522. "dwell": self.ui.dwell_cb,
  3523. "dwelltime": self.ui.dwelltime_entry,
  3524. "multidepth": self.ui.mpass_cb,
  3525. "ppname_g": self.ui.pp_geometry_name_cb,
  3526. "z_pdepth": self.ui.pdepth_entry,
  3527. "feedrate_probe": self.ui.feedrate_probe_entry,
  3528. "depthperpass": self.ui.maxdepth_entry,
  3529. "extracut": self.ui.extracut_cb,
  3530. "extracut_length": self.ui.e_cut_entry,
  3531. "toolchange": self.ui.toolchangeg_cb,
  3532. "toolchangez": self.ui.toolchangez_entry,
  3533. "endz": self.ui.endz_entry,
  3534. "endxy": self.ui.endxy_entry,
  3535. "cnctooldia": self.ui.addtool_entry
  3536. })
  3537. self.param_fields.update({
  3538. "vtipdia": self.ui.tipdia_entry,
  3539. "vtipangle": self.ui.tipangle_entry,
  3540. "cutz": self.ui.cutz_entry,
  3541. "depthperpass": self.ui.maxdepth_entry,
  3542. "multidepth": self.ui.mpass_cb,
  3543. "travelz": self.ui.travelz_entry,
  3544. "feedrate": self.ui.cncfeedrate_entry,
  3545. "feedrate_z": self.ui.feedrate_z_entry,
  3546. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  3547. "extracut": self.ui.extracut_cb,
  3548. "extracut_length": self.ui.e_cut_entry,
  3549. "spindlespeed": self.ui.cncspindlespeed_entry,
  3550. "dwelltime": self.ui.dwelltime_entry,
  3551. "dwell": self.ui.dwell_cb,
  3552. "pdepth": self.ui.pdepth_entry,
  3553. "pfeedrate": self.ui.feedrate_probe_entry,
  3554. })
  3555. # Fill form fields only on object create
  3556. self.to_form()
  3557. # update the changes in UI depending on the selected preprocessor in Preferences
  3558. # after this moment all the changes in the Posprocessor combo will be handled by the activated signal of the
  3559. # self.ui.pp_geometry_name_cb combobox
  3560. self.on_pp_changed()
  3561. self.ui.tipdialabel.hide()
  3562. self.ui.tipdia_entry.hide()
  3563. self.ui.tipanglelabel.hide()
  3564. self.ui.tipangle_entry.hide()
  3565. self.ui.cutz_entry.setDisabled(False)
  3566. # store here the default data for Geometry Data
  3567. self.default_data = {}
  3568. self.default_data.update({
  3569. "name": None,
  3570. "plot": None,
  3571. "cutz": None,
  3572. "vtipdia": None,
  3573. "vtipangle": None,
  3574. "travelz": None,
  3575. "feedrate": None,
  3576. "feedrate_z": None,
  3577. "feedrate_rapid": None,
  3578. "dwell": None,
  3579. "dwelltime": None,
  3580. "multidepth": None,
  3581. "ppname_g": None,
  3582. "depthperpass": None,
  3583. "extracut": None,
  3584. "extracut_length": None,
  3585. "toolchange": None,
  3586. "toolchangez": None,
  3587. "endz": None,
  3588. "endxy": '',
  3589. "spindlespeed": 0,
  3590. "toolchangexy": None,
  3591. "startz": None
  3592. })
  3593. # fill in self.default_data values from self.options
  3594. for def_key in self.default_data:
  3595. for opt_key, opt_val in self.options.items():
  3596. if def_key == opt_key:
  3597. self.default_data[def_key] = deepcopy(opt_val)
  3598. if type(self.options["cnctooldia"]) == float:
  3599. tools_list = [self.options["cnctooldia"]]
  3600. else:
  3601. try:
  3602. temp_tools = self.options["cnctooldia"].split(",")
  3603. tools_list = [
  3604. float(eval(dia)) for dia in temp_tools if dia != ''
  3605. ]
  3606. except Exception as e:
  3607. log.error("FlatCAMGeometry.set_ui() -> At least one tool diameter needed. "
  3608. "Verify in Edit -> Preferences -> Geometry General -> Tool dia. %s" % str(e))
  3609. return
  3610. self.tooluid += 1
  3611. if not self.tools:
  3612. for toold in tools_list:
  3613. new_data = deepcopy(self.default_data)
  3614. self.tools.update({
  3615. self.tooluid: {
  3616. 'tooldia': float('%.*f' % (self.decimals, float(toold))),
  3617. 'offset': 'Path',
  3618. 'offset_value': 0.0,
  3619. 'type': _('Rough'),
  3620. 'tool_type': self.tool_type,
  3621. 'data': new_data,
  3622. 'solid_geometry': self.solid_geometry
  3623. }
  3624. })
  3625. self.tooluid += 1
  3626. else:
  3627. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  3628. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  3629. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  3630. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  3631. # following convoluted way of changing the keys from string to float type
  3632. temp_tools = {}
  3633. for tooluid_key in self.tools:
  3634. val = deepcopy(self.tools[tooluid_key])
  3635. new_key = deepcopy(int(tooluid_key))
  3636. temp_tools[new_key] = val
  3637. self.tools.clear()
  3638. self.tools = deepcopy(temp_tools)
  3639. self.ui.tool_offset_entry.hide()
  3640. self.ui.tool_offset_lbl.hide()
  3641. # used to store the state of the mpass_cb if the selected preprocessor for geometry is hpgl
  3642. self.old_pp_state = self.default_data['multidepth']
  3643. self.old_toolchangeg_state = self.default_data['toolchange']
  3644. if not isinstance(self.ui, GeometryObjectUI):
  3645. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  3646. return
  3647. self.ui.geo_tools_table.setupContextMenu()
  3648. self.ui.geo_tools_table.addContextMenu(
  3649. _("Add from Tool DB"), self.on_tool_add_from_db_clicked,
  3650. icon=QtGui.QIcon(self.app.resource_location + "/plus16.png"))
  3651. self.ui.geo_tools_table.addContextMenu(
  3652. _("Copy"), self.on_tool_copy,
  3653. icon=QtGui.QIcon(self.app.resource_location + "/copy16.png"))
  3654. self.ui.geo_tools_table.addContextMenu(
  3655. _("Delete"), lambda: self.on_tool_delete(all_tools=None),
  3656. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png"))
  3657. # Show/Hide Advanced Options
  3658. if self.app.defaults["global_app_level"] == 'b':
  3659. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  3660. self.ui.geo_tools_table.setColumnHidden(2, True)
  3661. self.ui.geo_tools_table.setColumnHidden(3, True)
  3662. # self.ui.geo_tools_table.setColumnHidden(4, True)
  3663. self.ui.addtool_entry_lbl.hide()
  3664. self.ui.addtool_entry.hide()
  3665. self.ui.addtool_btn.hide()
  3666. self.ui.copytool_btn.hide()
  3667. self.ui.deltool_btn.hide()
  3668. # self.ui.endz_label.hide()
  3669. # self.ui.endz_entry.hide()
  3670. self.ui.fr_rapidlabel.hide()
  3671. self.ui.feedrate_rapid_entry.hide()
  3672. self.ui.extracut_cb.hide()
  3673. self.ui.e_cut_entry.hide()
  3674. self.ui.pdepth_label.hide()
  3675. self.ui.pdepth_entry.hide()
  3676. self.ui.feedrate_probe_label.hide()
  3677. self.ui.feedrate_probe_entry.hide()
  3678. else:
  3679. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  3680. self.ui.e_cut_entry.setDisabled(False) if self.app.defaults['geometry_extracut'] else \
  3681. self.ui.e_cut_entry.setDisabled(True)
  3682. self.ui.extracut_cb.toggled.connect(lambda state: self.ui.e_cut_entry.setDisabled(not state))
  3683. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  3684. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  3685. self.ui.paint_tool_button.clicked.connect(lambda: self.app.paint_tool.run(toggle=False))
  3686. self.ui.generate_ncc_button.clicked.connect(lambda: self.app.ncclear_tool.run(toggle=False))
  3687. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  3688. self.ui.tipdia_entry.valueChanged.connect(self.update_cutz)
  3689. self.ui.tipangle_entry.valueChanged.connect(self.update_cutz)
  3690. self.ui.addtool_from_db_btn.clicked.connect(self.on_tool_add_from_db_clicked)
  3691. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  3692. self.ui.cutz_entry.returnPressed.connect(self.on_cut_z_changed)
  3693. def on_cut_z_changed(self):
  3694. self.old_cutz = self.ui.cutz_entry.get_value()
  3695. def set_tool_offset_visibility(self, current_row):
  3696. if current_row is None:
  3697. return
  3698. try:
  3699. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  3700. if tool_offset is not None:
  3701. tool_offset_txt = tool_offset.currentText()
  3702. if tool_offset_txt == 'Custom':
  3703. self.ui.tool_offset_entry.show()
  3704. self.ui.tool_offset_lbl.show()
  3705. else:
  3706. self.ui.tool_offset_entry.hide()
  3707. self.ui.tool_offset_lbl.hide()
  3708. except Exception as e:
  3709. log.debug("set_tool_offset_visibility() --> " + str(e))
  3710. return
  3711. def on_offset_value_edited(self):
  3712. """
  3713. This will save the offset_value into self.tools storage whenever the offset value is edited
  3714. :return:
  3715. """
  3716. for current_row in self.ui.geo_tools_table.selectedItems():
  3717. # sometime the header get selected and it has row number -1
  3718. # we don't want to do anything with the header :)
  3719. if current_row.row() < 0:
  3720. continue
  3721. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3722. self.set_tool_offset_visibility(current_row.row())
  3723. for tooluid_key, tooluid_value in self.tools.items():
  3724. if int(tooluid_key) == tool_uid:
  3725. try:
  3726. tooluid_value['offset_value'] = float(self.ui.tool_offset_entry.get_value())
  3727. except ValueError:
  3728. # try to convert comma to decimal point. if it's still not working error message and return
  3729. try:
  3730. tooluid_value['offset_value'] = float(
  3731. self.ui.tool_offset_entry.get_value().replace(',', '.')
  3732. )
  3733. except ValueError:
  3734. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3735. _("Wrong value format entered, use a number."))
  3736. return
  3737. def ui_connect(self):
  3738. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  3739. # changes in geometry UI
  3740. for i in self.param_fields:
  3741. current_widget = self.param_fields[i]
  3742. if isinstance(current_widget, FCCheckBox):
  3743. current_widget.stateChanged.connect(self.gui_form_to_storage)
  3744. elif isinstance(current_widget, FCComboBox):
  3745. current_widget.currentIndexChanged.connect(self.gui_form_to_storage)
  3746. elif isinstance(current_widget, FloatEntry) or isinstance(current_widget, LengthEntry) or \
  3747. isinstance(current_widget, FCEntry) or isinstance(current_widget, IntEntry):
  3748. current_widget.editingFinished.connect(self.gui_form_to_storage)
  3749. elif isinstance(current_widget, FCSpinner) or isinstance(current_widget, FCDoubleSpinner):
  3750. current_widget.returnPressed.connect(self.gui_form_to_storage)
  3751. for row in range(self.ui.geo_tools_table.rowCount()):
  3752. for col in [2, 3, 4]:
  3753. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  3754. self.on_tooltable_cellwidget_change)
  3755. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  3756. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  3757. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  3758. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  3759. # self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  3760. self.ui.geo_tools_table.clicked.connect(self.on_row_selection_change)
  3761. self.ui.geo_tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  3762. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  3763. self.ui.tool_offset_entry.returnPressed.connect(self.on_offset_value_edited)
  3764. for row in range(self.ui.geo_tools_table.rowCount()):
  3765. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  3766. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  3767. # common parameters update
  3768. self.ui.pp_geometry_name_cb.currentIndexChanged.connect(self.update_common_param_in_storage)
  3769. def ui_disconnect(self):
  3770. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  3771. # changes in geometry UI
  3772. for i in self.param_fields:
  3773. # current_widget = self.ui.grid3.itemAt(i).widget()
  3774. current_widget = self.param_fields[i]
  3775. if isinstance(current_widget, FCCheckBox):
  3776. try:
  3777. current_widget.stateChanged.disconnect(self.gui_form_to_storage)
  3778. except (TypeError, AttributeError):
  3779. pass
  3780. elif isinstance(current_widget, FCComboBox):
  3781. try:
  3782. current_widget.currentIndexChanged.disconnect(self.gui_form_to_storage)
  3783. except (TypeError, AttributeError):
  3784. pass
  3785. elif isinstance(current_widget, LengthEntry) or isinstance(current_widget, IntEntry) or \
  3786. isinstance(current_widget, FCEntry) or isinstance(current_widget, FloatEntry):
  3787. try:
  3788. current_widget.editingFinished.disconnect(self.gui_form_to_storage)
  3789. except (TypeError, AttributeError):
  3790. pass
  3791. elif isinstance(current_widget, FCSpinner) or isinstance(current_widget, FCDoubleSpinner):
  3792. try:
  3793. current_widget.returnPressed.disconnect(self.gui_form_to_storage)
  3794. except TypeError:
  3795. pass
  3796. for row in range(self.ui.geo_tools_table.rowCount()):
  3797. for col in [2, 3, 4]:
  3798. try:
  3799. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  3800. except (TypeError, AttributeError):
  3801. pass
  3802. try:
  3803. self.ui.addtool_btn.clicked.disconnect()
  3804. except (TypeError, AttributeError):
  3805. pass
  3806. try:
  3807. self.ui.copytool_btn.clicked.disconnect()
  3808. except (TypeError, AttributeError):
  3809. pass
  3810. try:
  3811. self.ui.deltool_btn.clicked.disconnect()
  3812. except (TypeError, AttributeError):
  3813. pass
  3814. try:
  3815. self.ui.geo_tools_table.clicked.disconnect()
  3816. except (TypeError, AttributeError):
  3817. pass
  3818. try:
  3819. self.ui.geo_tools_table.horizontalHeader().sectionClicked.disconnect()
  3820. except (TypeError, AttributeError):
  3821. pass
  3822. try:
  3823. self.ui.geo_tools_table.itemChanged.disconnect()
  3824. except (TypeError, AttributeError):
  3825. pass
  3826. try:
  3827. self.ui.tool_offset_entry.returnPressed.disconnect()
  3828. except (TypeError, AttributeError):
  3829. pass
  3830. for row in range(self.ui.geo_tools_table.rowCount()):
  3831. try:
  3832. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  3833. except (TypeError, AttributeError):
  3834. pass
  3835. try:
  3836. self.ui.plot_cb.stateChanged.disconnect()
  3837. except (TypeError, AttributeError):
  3838. pass
  3839. def on_row_selection_change(self):
  3840. self.update_ui()
  3841. def update_ui(self, row=None):
  3842. self.ui_disconnect()
  3843. if row is None:
  3844. sel_rows = []
  3845. sel_items = self.ui.geo_tools_table.selectedItems()
  3846. for it in sel_items:
  3847. sel_rows.append(it.row())
  3848. else:
  3849. sel_rows = row if type(row) == list else [row]
  3850. if not sel_rows:
  3851. sel_rows = [0]
  3852. for current_row in sel_rows:
  3853. self.set_tool_offset_visibility(current_row)
  3854. # populate the form with the data from the tool associated with the row parameter
  3855. try:
  3856. item = self.ui.geo_tools_table.item(current_row, 5)
  3857. if type(item) is not None:
  3858. tooluid = int(item.text())
  3859. else:
  3860. self.ui_connect()
  3861. return
  3862. except Exception as e:
  3863. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  3864. self.ui_connect()
  3865. return
  3866. # update the QLabel that shows for which Tool we have the parameters in the UI form
  3867. if len(sel_rows) == 1:
  3868. self.ui.tool_data_label.setText(
  3869. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), tooluid)
  3870. )
  3871. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  3872. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  3873. try:
  3874. item = self.ui.geo_tools_table.cellWidget(current_row, 4)
  3875. if item is not None:
  3876. tool_type_txt = item.currentText()
  3877. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  3878. else:
  3879. self.ui_connect()
  3880. return
  3881. except Exception as e:
  3882. log.debug("Tool missing in ui_update_v_shape(). Add a tool in Geo Tool Table. %s" % str(e))
  3883. return
  3884. try:
  3885. # set the form with data from the newly selected tool
  3886. for tooluid_key, tooluid_value in list(self.tools.items()):
  3887. if int(tooluid_key) == tooluid:
  3888. for key, value in list(tooluid_value.items()):
  3889. if key == 'data':
  3890. form_value_storage = tooluid_value['data']
  3891. self.update_form(form_value_storage)
  3892. if key == 'offset_value':
  3893. # update the offset value in the entry even if the entry is hidden
  3894. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  3895. if key == 'tool_type' and value == 'V':
  3896. self.update_cutz()
  3897. except Exception as e:
  3898. log.debug("FlatCAMGeometry.update_ui() -> %s " % str(e))
  3899. else:
  3900. self.ui.tool_data_label.setText(
  3901. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  3902. )
  3903. self.ui_connect()
  3904. def on_tool_add(self, dia=None):
  3905. self.ui_disconnect()
  3906. self.units = self.app.defaults['units'].upper()
  3907. if dia is not None:
  3908. tooldia = dia
  3909. else:
  3910. tooldia = float(self.ui.addtool_entry.get_value())
  3911. # construct a list of all 'tooluid' in the self.tools
  3912. # tool_uid_list = []
  3913. # for tooluid_key in self.tools:
  3914. # tool_uid_list.append(int(tooluid_key))
  3915. tool_uid_list = [int(tooluid_key) for tooluid_key in self.tools]
  3916. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  3917. max_uid = max(tool_uid_list) if tool_uid_list else 0
  3918. self.tooluid = max_uid + 1
  3919. tooldia = float('%.*f' % (self.decimals, tooldia))
  3920. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  3921. # otherwise we add a tool with data copied from last tool
  3922. if self.tools:
  3923. last_data = self.tools[max_uid]['data']
  3924. last_offset = self.tools[max_uid]['offset']
  3925. last_offset_value = self.tools[max_uid]['offset_value']
  3926. last_type = self.tools[max_uid]['type']
  3927. last_tool_type = self.tools[max_uid]['tool_type']
  3928. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  3929. # if previous geometry was empty (it may happen for the first tool added)
  3930. # then copy the object.solid_geometry
  3931. if not last_solid_geometry:
  3932. last_solid_geometry = self.solid_geometry
  3933. self.tools.update({
  3934. self.tooluid: {
  3935. 'tooldia': tooldia,
  3936. 'offset': last_offset,
  3937. 'offset_value': last_offset_value,
  3938. 'type': last_type,
  3939. 'tool_type': last_tool_type,
  3940. 'data': deepcopy(last_data),
  3941. 'solid_geometry': deepcopy(last_solid_geometry)
  3942. }
  3943. })
  3944. else:
  3945. self.tools.update({
  3946. self.tooluid: {
  3947. 'tooldia': tooldia,
  3948. 'offset': 'Path',
  3949. 'offset_value': 0.0,
  3950. 'type': _('Rough'),
  3951. 'tool_type': 'C1',
  3952. 'data': deepcopy(self.default_data),
  3953. 'solid_geometry': self.solid_geometry
  3954. }
  3955. })
  3956. self.tools[self.tooluid]['data']['name'] = self.options['name']
  3957. self.ui.tool_offset_entry.hide()
  3958. self.ui.tool_offset_lbl.hide()
  3959. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3960. try:
  3961. self.ser_attrs.remove('tools')
  3962. except TypeError:
  3963. pass
  3964. self.ser_attrs.append('tools')
  3965. self.app.inform.emit('[success] %s' % _("Tool added in Tool Table."))
  3966. self.ui_connect()
  3967. self.build_ui()
  3968. # if there is no tool left in the Tools Table, enable the parameters GUI
  3969. if self.ui.geo_tools_table.rowCount() != 0:
  3970. self.ui.geo_param_frame.setDisabled(False)
  3971. def on_tool_add_from_db_clicked(self):
  3972. """
  3973. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  3974. and display the Tools Database tab in the form needed for the Tool adding
  3975. :return: None
  3976. """
  3977. # if the Tools Database is already opened focus on it
  3978. for idx in range(self.app.ui.plot_tab_area.count()):
  3979. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  3980. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  3981. break
  3982. self.app.on_tools_database()
  3983. self.app.tools_db_tab.ok_to_add = True
  3984. self.app.tools_db_tab.buttons_frame.hide()
  3985. self.app.tools_db_tab.add_tool_from_db.show()
  3986. self.app.tools_db_tab.cancel_tool_from_db.show()
  3987. def on_tool_from_db_inserted(self, tool):
  3988. """
  3989. Called from the Tools DB object through a App method when adding a tool from Tools Database
  3990. :param tool: a dict with the tool data
  3991. :return: None
  3992. """
  3993. self.ui_disconnect()
  3994. self.units = self.app.defaults['units'].upper()
  3995. tooldia = float(tool['tooldia'])
  3996. # construct a list of all 'tooluid' in the self.tools
  3997. tool_uid_list = []
  3998. for tooluid_key in self.tools:
  3999. tool_uid_item = int(tooluid_key)
  4000. tool_uid_list.append(tool_uid_item)
  4001. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  4002. if not tool_uid_list:
  4003. max_uid = 0
  4004. else:
  4005. max_uid = max(tool_uid_list)
  4006. self.tooluid = max_uid + 1
  4007. tooldia = float('%.*f' % (self.decimals, tooldia))
  4008. self.tools.update({
  4009. self.tooluid: {
  4010. 'tooldia': tooldia,
  4011. 'offset': tool['offset'],
  4012. 'offset_value': float(tool['offset_value']),
  4013. 'type': tool['type'],
  4014. 'tool_type': tool['tool_type'],
  4015. 'data': deepcopy(tool['data']),
  4016. 'solid_geometry': self.solid_geometry
  4017. }
  4018. })
  4019. self.tools[self.tooluid]['data']['name'] = self.options['name']
  4020. self.ui.tool_offset_entry.hide()
  4021. self.ui.tool_offset_lbl.hide()
  4022. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  4023. try:
  4024. self.ser_attrs.remove('tools')
  4025. except TypeError:
  4026. pass
  4027. self.ser_attrs.append('tools')
  4028. self.ui_connect()
  4029. self.build_ui()
  4030. # if there is no tool left in the Tools Table, enable the parameters GUI
  4031. if self.ui.geo_tools_table.rowCount() != 0:
  4032. self.ui.geo_param_frame.setDisabled(False)
  4033. def on_tool_copy(self, all_tools=None):
  4034. self.ui_disconnect()
  4035. # find the tool_uid maximum value in the self.tools
  4036. uid_list = []
  4037. for key in self.tools:
  4038. uid_list.append(int(key))
  4039. try:
  4040. max_uid = max(uid_list, key=int)
  4041. except ValueError:
  4042. max_uid = 0
  4043. if all_tools is None:
  4044. if self.ui.geo_tools_table.selectedItems():
  4045. for current_row in self.ui.geo_tools_table.selectedItems():
  4046. # sometime the header get selected and it has row number -1
  4047. # we don't want to do anything with the header :)
  4048. if current_row.row() < 0:
  4049. continue
  4050. try:
  4051. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  4052. self.set_tool_offset_visibility(current_row.row())
  4053. max_uid += 1
  4054. self.tools[int(max_uid)] = deepcopy(self.tools[tooluid_copy])
  4055. except AttributeError:
  4056. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to copy."))
  4057. self.ui_connect()
  4058. self.build_ui()
  4059. return
  4060. except Exception as e:
  4061. log.debug("on_tool_copy() --> " + str(e))
  4062. # deselect the table
  4063. # self.ui.geo_tools_table.clearSelection()
  4064. else:
  4065. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to copy."))
  4066. self.ui_connect()
  4067. self.build_ui()
  4068. return
  4069. else:
  4070. # we copy all tools in geo_tools_table
  4071. try:
  4072. temp_tools = deepcopy(self.tools)
  4073. max_uid += 1
  4074. for tooluid in temp_tools:
  4075. self.tools[int(max_uid)] = deepcopy(temp_tools[tooluid])
  4076. temp_tools.clear()
  4077. except Exception as e:
  4078. log.debug("on_tool_copy() --> " + str(e))
  4079. # if there are no more tools in geo tools table then hide the tool offset
  4080. if not self.tools:
  4081. self.ui.tool_offset_entry.hide()
  4082. self.ui.tool_offset_lbl.hide()
  4083. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  4084. try:
  4085. self.ser_attrs.remove('tools')
  4086. except ValueError:
  4087. pass
  4088. self.ser_attrs.append('tools')
  4089. self.ui_connect()
  4090. self.build_ui()
  4091. self.app.inform.emit('[success] %s' % _("Tool was copied in Tool Table."))
  4092. def on_tool_edit(self, current_item):
  4093. self.ui_disconnect()
  4094. current_row = current_item.row()
  4095. try:
  4096. d = float(self.ui.geo_tools_table.item(current_row, 1).text())
  4097. except ValueError:
  4098. # try to convert comma to decimal point. if it's still not working error message and return
  4099. try:
  4100. d = float(self.ui.geo_tools_table.item(current_row, 1).text().replace(',', '.'))
  4101. except ValueError:
  4102. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  4103. return
  4104. tool_dia = float('%.*f' % (self.decimals, d))
  4105. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  4106. self.tools[tooluid]['tooldia'] = tool_dia
  4107. try:
  4108. self.ser_attrs.remove('tools')
  4109. self.ser_attrs.append('tools')
  4110. except (TypeError, ValueError):
  4111. pass
  4112. self.app.inform.emit('[success] %s' % _("Tool was edited in Tool Table."))
  4113. self.ui_connect()
  4114. self.build_ui()
  4115. def on_tool_delete(self, all_tools=None):
  4116. self.ui_disconnect()
  4117. if all_tools is None:
  4118. if self.ui.geo_tools_table.selectedItems():
  4119. for current_row in self.ui.geo_tools_table.selectedItems():
  4120. # sometime the header get selected and it has row number -1
  4121. # we don't want to do anything with the header :)
  4122. if current_row.row() < 0:
  4123. continue
  4124. try:
  4125. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  4126. self.set_tool_offset_visibility(current_row.row())
  4127. temp_tools = deepcopy(self.tools)
  4128. for tooluid_key in self.tools:
  4129. if int(tooluid_key) == tooluid_del:
  4130. # if the self.tools has only one tool and we delete it then we move the solid_geometry
  4131. # as a property of the object otherwise there will be nothing to hold it
  4132. if len(self.tools) == 1:
  4133. self.solid_geometry = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  4134. temp_tools.pop(tooluid_del, None)
  4135. self.tools = deepcopy(temp_tools)
  4136. temp_tools.clear()
  4137. except AttributeError:
  4138. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to delete."))
  4139. self.ui_connect()
  4140. self.build_ui()
  4141. return
  4142. except Exception as e:
  4143. log.debug("on_tool_delete() --> " + str(e))
  4144. # deselect the table
  4145. # self.ui.geo_tools_table.clearSelection()
  4146. else:
  4147. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to delete."))
  4148. self.ui_connect()
  4149. self.build_ui()
  4150. return
  4151. else:
  4152. # we delete all tools in geo_tools_table
  4153. self.tools.clear()
  4154. self.app.plot_all()
  4155. # if there are no more tools in geo tools table then hide the tool offset
  4156. if not self.tools:
  4157. self.ui.tool_offset_entry.hide()
  4158. self.ui.tool_offset_lbl.hide()
  4159. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  4160. try:
  4161. self.ser_attrs.remove('tools')
  4162. except TypeError:
  4163. pass
  4164. self.ser_attrs.append('tools')
  4165. self.ui_connect()
  4166. self.build_ui()
  4167. self.app.inform.emit('[success] %s' % _("Tool was deleted in Tool Table."))
  4168. obj_active = self.app.collection.get_active()
  4169. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  4170. # we make it back SingleGeo
  4171. if self.ui.geo_tools_table.rowCount() <= 0:
  4172. obj_active.multigeo = False
  4173. obj_active.options['xmin'] = 0
  4174. obj_active.options['ymin'] = 0
  4175. obj_active.options['xmax'] = 0
  4176. obj_active.options['ymax'] = 0
  4177. if obj_active.multigeo is True:
  4178. try:
  4179. xmin, ymin, xmax, ymax = obj_active.bounds()
  4180. obj_active.options['xmin'] = xmin
  4181. obj_active.options['ymin'] = ymin
  4182. obj_active.options['xmax'] = xmax
  4183. obj_active.options['ymax'] = ymax
  4184. except Exception:
  4185. obj_active.options['xmin'] = 0
  4186. obj_active.options['ymin'] = 0
  4187. obj_active.options['xmax'] = 0
  4188. obj_active.options['ymax'] = 0
  4189. # if there is no tool left in the Tools Table, disable the parameters GUI
  4190. if self.ui.geo_tools_table.rowCount() == 0:
  4191. self.ui.geo_param_frame.setDisabled(True)
  4192. def ui_update_v_shape(self, tool_type_txt):
  4193. if tool_type_txt == 'V':
  4194. self.ui.tipdialabel.show()
  4195. self.ui.tipdia_entry.show()
  4196. self.ui.tipanglelabel.show()
  4197. self.ui.tipangle_entry.show()
  4198. self.ui.cutz_entry.setDisabled(True)
  4199. self.update_cutz()
  4200. else:
  4201. self.ui.tipdialabel.hide()
  4202. self.ui.tipdia_entry.hide()
  4203. self.ui.tipanglelabel.hide()
  4204. self.ui.tipangle_entry.hide()
  4205. self.ui.cutz_entry.setDisabled(False)
  4206. def update_cutz(self):
  4207. vdia = float(self.ui.tipdia_entry.get_value())
  4208. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  4209. row = self.ui.geo_tools_table.currentRow()
  4210. tool_uid_item = self.ui.geo_tools_table.item(row, 5)
  4211. if tool_uid_item is None:
  4212. return
  4213. tool_uid = int(tool_uid_item.text())
  4214. tool_dia_item = self.ui.geo_tools_table.item(row, 1)
  4215. if tool_dia_item is None:
  4216. return
  4217. tooldia = float(tool_dia_item.text())
  4218. try:
  4219. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  4220. except ZeroDivisionError:
  4221. new_cutz = self.old_cutz
  4222. new_cutz = float('%.*f' % (self.decimals, new_cutz)) * -1.0 # this value has to be negative
  4223. self.ui.cutz_entry.set_value(new_cutz)
  4224. # store the new CutZ value into storage (self.tools)
  4225. for tooluid_key, tooluid_value in self.tools.items():
  4226. if int(tooluid_key) == tool_uid:
  4227. tooluid_value['data']['cutz'] = new_cutz
  4228. def on_tooltable_cellwidget_change(self):
  4229. cw = self.sender()
  4230. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  4231. cw_row = cw_index.row()
  4232. cw_col = cw_index.column()
  4233. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  4234. # store the text of the cellWidget that changed it's index in the self.tools
  4235. for tooluid_key, tooluid_value in self.tools.items():
  4236. if int(tooluid_key) == current_uid:
  4237. cb_txt = cw.currentText()
  4238. if cw_col == 2:
  4239. tooluid_value['offset'] = cb_txt
  4240. if cb_txt == 'Custom':
  4241. self.ui.tool_offset_entry.show()
  4242. self.ui.tool_offset_lbl.show()
  4243. else:
  4244. self.ui.tool_offset_entry.hide()
  4245. self.ui.tool_offset_lbl.hide()
  4246. # reset the offset_value in storage self.tools
  4247. tooluid_value['offset_value'] = 0.0
  4248. elif cw_col == 3:
  4249. # force toolpath type as 'Iso' if the tool type is V-Shape
  4250. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  4251. tooluid_value['type'] = _('Iso')
  4252. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  4253. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  4254. else:
  4255. tooluid_value['type'] = cb_txt
  4256. elif cw_col == 4:
  4257. tooluid_value['tool_type'] = cb_txt
  4258. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  4259. if cb_txt == 'V':
  4260. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  4261. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  4262. else:
  4263. self.ui.cutz_entry.set_value(self.old_cutz)
  4264. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  4265. def update_form(self, dict_storage):
  4266. for form_key in self.form_fields:
  4267. for storage_key in dict_storage:
  4268. if form_key == storage_key:
  4269. try:
  4270. self.form_fields[form_key].set_value(dict_storage[form_key])
  4271. except Exception as e:
  4272. log.debug(str(e))
  4273. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  4274. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  4275. self.ui.ois_dwell_geo.on_cb_change()
  4276. self.ui.ois_mpass_geo.on_cb_change()
  4277. self.ui.ois_tcz_geo.on_cb_change()
  4278. def on_apply_param_to_all_clicked(self):
  4279. if self.ui.geo_tools_table.rowCount() == 0:
  4280. # there is no tool in tool table so we can't save the GUI elements values to storage
  4281. log.debug("FlatCAMGeometry.gui_form_to_storage() --> no tool in Tools Table, aborting.")
  4282. return
  4283. self.ui_disconnect()
  4284. row = self.ui.geo_tools_table.currentRow()
  4285. if row < 0:
  4286. row = 0
  4287. # store all the data associated with the row parameter to the self.tools storage
  4288. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  4289. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  4290. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  4291. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  4292. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  4293. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  4294. temp_tools = {}
  4295. temp_dia = {}
  4296. temp_data = {}
  4297. for tooluid_key, tooluid_value in self.tools.items():
  4298. for key, value in tooluid_value.items():
  4299. if key == 'tooldia':
  4300. temp_dia[key] = tooldia_item
  4301. # update the 'offset', 'type' and 'tool_type' sections
  4302. if key == 'offset':
  4303. temp_dia[key] = offset_item
  4304. if key == 'type':
  4305. temp_dia[key] = type_item
  4306. if key == 'tool_type':
  4307. temp_dia[key] = tool_type_item
  4308. if key == 'offset_value':
  4309. temp_dia[key] = offset_value_item
  4310. if key == 'data':
  4311. # update the 'data' section
  4312. for data_key in tooluid_value[key].keys():
  4313. for form_key, form_value in self.form_fields.items():
  4314. if form_key == data_key:
  4315. temp_data[data_key] = form_value.get_value()
  4316. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  4317. # updated from self.app.defaults
  4318. if data_key not in self.form_fields:
  4319. temp_data[data_key] = value[data_key]
  4320. temp_dia[key] = deepcopy(temp_data)
  4321. temp_data.clear()
  4322. if key == 'solid_geometry':
  4323. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  4324. temp_tools[tooluid_key] = deepcopy(temp_dia)
  4325. self.tools.clear()
  4326. self.tools = deepcopy(temp_tools)
  4327. temp_tools.clear()
  4328. self.ui_connect()
  4329. def gui_form_to_storage(self):
  4330. if self.ui.geo_tools_table.rowCount() == 0:
  4331. # there is no tool in tool table so we can't save the GUI elements values to storage
  4332. log.debug("FlatCAMGeometry.gui_form_to_storage() --> no tool in Tools Table, aborting.")
  4333. return
  4334. self.ui_disconnect()
  4335. widget_changed = self.sender()
  4336. try:
  4337. widget_idx = self.ui.grid3.indexOf(widget_changed)
  4338. except Exception:
  4339. return
  4340. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  4341. if widget_idx == 1 or widget_idx == 3:
  4342. self.update_cutz()
  4343. # the original connect() function of the OptionalInputSelection is no longer working because of the
  4344. # ui_diconnect() so I use this 'hack'
  4345. if isinstance(widget_changed, FCCheckBox):
  4346. if widget_changed.text() == 'Multi-Depth:':
  4347. self.ui.ois_mpass_geo.on_cb_change()
  4348. if widget_changed.text() == 'Tool change':
  4349. self.ui.ois_tcz_geo.on_cb_change()
  4350. if widget_changed.text() == 'Dwell:':
  4351. self.ui.ois_dwell_geo.on_cb_change()
  4352. row = self.ui.geo_tools_table.currentRow()
  4353. if row < 0:
  4354. row = 0
  4355. # store all the data associated with the row parameter to the self.tools storage
  4356. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  4357. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  4358. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  4359. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  4360. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  4361. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  4362. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  4363. temp_tools = {}
  4364. temp_dia = {}
  4365. temp_data = {}
  4366. for tooluid_key, tooluid_value in self.tools.items():
  4367. if int(tooluid_key) == tooluid_item:
  4368. for key, value in tooluid_value.items():
  4369. if key == 'tooldia':
  4370. temp_dia[key] = tooldia_item
  4371. # update the 'offset', 'type' and 'tool_type' sections
  4372. if key == 'offset':
  4373. temp_dia[key] = offset_item
  4374. if key == 'type':
  4375. temp_dia[key] = type_item
  4376. if key == 'tool_type':
  4377. temp_dia[key] = tool_type_item
  4378. if key == 'offset_value':
  4379. temp_dia[key] = offset_value_item
  4380. if key == 'data':
  4381. # update the 'data' section
  4382. for data_key in tooluid_value[key].keys():
  4383. for form_key, form_value in self.form_fields.items():
  4384. if form_key == data_key:
  4385. temp_data[data_key] = form_value.get_value()
  4386. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  4387. # updated from self.app.defaults
  4388. if data_key not in self.form_fields:
  4389. temp_data[data_key] = value[data_key]
  4390. temp_dia[key] = deepcopy(temp_data)
  4391. temp_data.clear()
  4392. if key == 'solid_geometry':
  4393. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  4394. temp_tools[tooluid_key] = deepcopy(temp_dia)
  4395. else:
  4396. temp_tools[tooluid_key] = deepcopy(tooluid_value)
  4397. self.tools.clear()
  4398. self.tools = deepcopy(temp_tools)
  4399. temp_tools.clear()
  4400. self.ui_connect()
  4401. def update_common_param_in_storage(self):
  4402. for tooluid_value in self.tools.values():
  4403. tooluid_value['data']['ppname_g'] = self.ui.pp_geometry_name_cb.get_value()
  4404. def select_tools_table_row(self, row, clearsel=None):
  4405. if clearsel:
  4406. self.ui.geo_tools_table.clearSelection()
  4407. if self.ui.geo_tools_table.rowCount() > 0:
  4408. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  4409. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  4410. def export_dxf(self):
  4411. dwg = None
  4412. try:
  4413. dwg = ezdxf.new('R2010')
  4414. msp = dwg.modelspace()
  4415. def g2dxf(dxf_space, geo_obj):
  4416. if isinstance(geo_obj, MultiPolygon):
  4417. for poly in geo_obj:
  4418. ext_points = list(poly.exterior.coords)
  4419. dxf_space.add_lwpolyline(ext_points)
  4420. for interior in poly.interiors:
  4421. dxf_space.add_lwpolyline(list(interior.coords))
  4422. if isinstance(geo_obj, Polygon):
  4423. ext_points = list(geo_obj.exterior.coords)
  4424. dxf_space.add_lwpolyline(ext_points)
  4425. for interior in geo_obj.interiors:
  4426. dxf_space.add_lwpolyline(list(interior.coords))
  4427. if isinstance(geo_obj, MultiLineString):
  4428. for line in geo_obj:
  4429. dxf_space.add_lwpolyline(list(line.coords))
  4430. if isinstance(geo_obj, LineString) or isinstance(geo_obj, LinearRing):
  4431. dxf_space.add_lwpolyline(list(geo_obj.coords))
  4432. multigeo_solid_geometry = []
  4433. if self.multigeo:
  4434. for tool in self.tools:
  4435. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  4436. else:
  4437. multigeo_solid_geometry = self.solid_geometry
  4438. for geo in multigeo_solid_geometry:
  4439. if type(geo) == list:
  4440. for g in geo:
  4441. g2dxf(msp, g)
  4442. else:
  4443. g2dxf(msp, geo)
  4444. # points = FlatCAMGeometry.get_pts(geo)
  4445. # msp.add_lwpolyline(points)
  4446. except Exception as e:
  4447. log.debug(str(e))
  4448. return dwg
  4449. def get_selected_tools_table_items(self):
  4450. """
  4451. Returns a list of lists, each list in the list is made out of row elements
  4452. :return: List of table_tools items.
  4453. :rtype: list
  4454. """
  4455. table_tools_items = []
  4456. if self.multigeo:
  4457. for x in self.ui.geo_tools_table.selectedItems():
  4458. elem = []
  4459. txt = ''
  4460. for column in range(0, self.ui.geo_tools_table.columnCount()):
  4461. try:
  4462. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  4463. except AttributeError:
  4464. try:
  4465. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  4466. except AttributeError:
  4467. pass
  4468. elem.append(txt)
  4469. table_tools_items.append(deepcopy(elem))
  4470. # table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  4471. # for column in range(0, self.ui.geo_tools_table.columnCount())])
  4472. else:
  4473. for x in self.ui.geo_tools_table.selectedItems():
  4474. r = []
  4475. txt = ''
  4476. # the last 2 columns for single-geo geometry are irrelevant and create problems reading
  4477. # so we don't read them
  4478. for column in range(0, self.ui.geo_tools_table.columnCount() - 2):
  4479. # the columns have items that have text but also have items that are widgets
  4480. # for which the text they hold has to be read differently
  4481. try:
  4482. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  4483. except AttributeError:
  4484. try:
  4485. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  4486. except AttributeError:
  4487. pass
  4488. r.append(txt)
  4489. table_tools_items.append(r)
  4490. for item in table_tools_items:
  4491. item[0] = str(item[0])
  4492. return table_tools_items
  4493. def on_pp_changed(self):
  4494. current_pp = self.ui.pp_geometry_name_cb.get_value()
  4495. if current_pp == 'hpgl':
  4496. self.old_pp_state = self.ui.mpass_cb.get_value()
  4497. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  4498. self.ui.mpass_cb.set_value(False)
  4499. self.ui.mpass_cb.setDisabled(True)
  4500. self.ui.toolchangeg_cb.set_value(True)
  4501. self.ui.toolchangeg_cb.setDisabled(True)
  4502. else:
  4503. self.ui.mpass_cb.set_value(self.old_pp_state)
  4504. self.ui.mpass_cb.setDisabled(False)
  4505. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  4506. self.ui.toolchangeg_cb.setDisabled(False)
  4507. if "toolchange_probe" in current_pp.lower():
  4508. self.ui.pdepth_entry.setVisible(True)
  4509. self.ui.pdepth_label.show()
  4510. self.ui.feedrate_probe_entry.setVisible(True)
  4511. self.ui.feedrate_probe_label.show()
  4512. else:
  4513. self.ui.pdepth_entry.setVisible(False)
  4514. self.ui.pdepth_label.hide()
  4515. self.ui.feedrate_probe_entry.setVisible(False)
  4516. self.ui.feedrate_probe_label.hide()
  4517. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  4518. self.ui.fr_rapidlabel.show()
  4519. self.ui.feedrate_rapid_entry.show()
  4520. else:
  4521. self.ui.fr_rapidlabel.hide()
  4522. self.ui.feedrate_rapid_entry.hide()
  4523. if 'laser' in current_pp.lower():
  4524. self.ui.cutzlabel.hide()
  4525. self.ui.cutz_entry.hide()
  4526. try:
  4527. self.ui.mpass_cb.hide()
  4528. self.ui.maxdepth_entry.hide()
  4529. except AttributeError:
  4530. pass
  4531. if 'marlin' in current_pp.lower():
  4532. self.ui.travelzlabel.setText('%s:' % _("Focus Z"))
  4533. self.ui.endz_label.show()
  4534. self.ui.endz_entry.show()
  4535. else:
  4536. self.ui.travelzlabel.hide()
  4537. self.ui.travelz_entry.hide()
  4538. self.ui.endz_label.hide()
  4539. self.ui.endz_entry.hide()
  4540. try:
  4541. self.ui.frzlabel.hide()
  4542. self.ui.feedrate_z_entry.hide()
  4543. except AttributeError:
  4544. pass
  4545. self.ui.dwell_cb.hide()
  4546. self.ui.dwelltime_entry.hide()
  4547. self.ui.spindle_label.setText('%s:' % _("Laser Power"))
  4548. try:
  4549. self.ui.tool_offset_label.hide()
  4550. self.ui.offset_entry.hide()
  4551. except AttributeError:
  4552. pass
  4553. else:
  4554. self.ui.cutzlabel.show()
  4555. self.ui.cutz_entry.show()
  4556. try:
  4557. self.ui.mpass_cb.show()
  4558. self.ui.maxdepth_entry.show()
  4559. except AttributeError:
  4560. pass
  4561. self.ui.travelzlabel.setText('%s:' % _('Travel Z'))
  4562. self.ui.travelzlabel.show()
  4563. self.ui.travelz_entry.show()
  4564. self.ui.endz_label.show()
  4565. self.ui.endz_entry.show()
  4566. try:
  4567. self.ui.frzlabel.show()
  4568. self.ui.feedrate_z_entry.show()
  4569. except AttributeError:
  4570. pass
  4571. self.ui.dwell_cb.show()
  4572. self.ui.dwelltime_entry.show()
  4573. self.ui.spindle_label.setText('%s:' % _('Spindle speed'))
  4574. try:
  4575. self.ui.tool_offset_lbl.show()
  4576. self.ui.offset_entry.show()
  4577. except AttributeError:
  4578. pass
  4579. def on_generatecnc_button_click(self, *args):
  4580. log.debug("Generating CNCJob from Geometry ...")
  4581. self.app.report_usage("geometry_on_generatecnc_button")
  4582. # this reads the values in the UI form to the self.options dictionary
  4583. self.read_form()
  4584. self.sel_tools = {}
  4585. try:
  4586. if self.special_group:
  4587. self.app.inform.emit(
  4588. '[WARNING_NOTCL] %s %s %s.' %
  4589. (_("This Geometry can't be processed because it is"), str(self.special_group), _("geometry"))
  4590. )
  4591. return
  4592. except AttributeError:
  4593. pass
  4594. # test to see if we have tools available in the tool table
  4595. if self.ui.geo_tools_table.selectedItems():
  4596. for x in self.ui.geo_tools_table.selectedItems():
  4597. # try:
  4598. # tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  4599. # except ValueError:
  4600. # # try to convert comma to decimal point. if it's still not working error message and return
  4601. # try:
  4602. # tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text().replace(',', '.'))
  4603. # except ValueError:
  4604. # self.app.inform.emit('[ERROR_NOTCL] %s' %
  4605. # _("Wrong value format entered, use a number."))
  4606. # return
  4607. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  4608. for tooluid_key, tooluid_value in self.tools.items():
  4609. if int(tooluid_key) == tooluid:
  4610. self.sel_tools.update({
  4611. tooluid: deepcopy(tooluid_value)
  4612. })
  4613. self.mtool_gen_cncjob()
  4614. self.ui.geo_tools_table.clearSelection()
  4615. elif self.ui.geo_tools_table.rowCount() == 1:
  4616. tooluid = int(self.ui.geo_tools_table.item(0, 5).text())
  4617. for tooluid_key, tooluid_value in self.tools.items():
  4618. if int(tooluid_key) == tooluid:
  4619. self.sel_tools.update({
  4620. tooluid: deepcopy(tooluid_value)
  4621. })
  4622. self.mtool_gen_cncjob()
  4623. self.ui.geo_tools_table.clearSelection()
  4624. else:
  4625. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No tool selected in the tool table ..."))
  4626. def mtool_gen_cncjob(self, outname=None, tools_dict=None, tools_in_use=None, segx=None, segy=None,
  4627. plot=True, use_thread=True):
  4628. """
  4629. Creates a multi-tool CNCJob out of this Geometry object.
  4630. The actual work is done by the target FlatCAMCNCjob object's
  4631. `generate_from_geometry_2()` method.
  4632. :param tools_dict: a dictionary that holds the whole data needed to create the Gcode
  4633. (including the solid_geometry)
  4634. :param tools_in_use: the tools that are used, needed by some preprocessors
  4635. :type list of lists, each list in the list is made out of row elements of tools table from GUI
  4636. :param outname:
  4637. :param tools_dict:
  4638. :param tools_in_use:
  4639. :param segx: number of segments on the X axis, for auto-levelling
  4640. :param segy: number of segments on the Y axis, for auto-levelling
  4641. :param plot: if True the generated object will be plotted; if False will not be plotted
  4642. :param use_thread: if True use threading
  4643. :return: None
  4644. """
  4645. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  4646. outname = "%s_%s" % (self.options["name"], 'cnc') if outname is None else outname
  4647. tools_dict = self.sel_tools if tools_dict is None else tools_dict
  4648. tools_in_use = tools_in_use if tools_in_use is not None else self.get_selected_tools_table_items()
  4649. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  4650. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  4651. try:
  4652. xmin = self.options['xmin']
  4653. ymin = self.options['ymin']
  4654. xmax = self.options['xmax']
  4655. ymax = self.options['ymax']
  4656. except Exception as e:
  4657. log.debug("FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s\n" % str(e))
  4658. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  4659. msg += '%s %s' % ('FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() -->', str(e))
  4660. msg += traceback.format_exc()
  4661. self.app.inform.emit(msg)
  4662. return
  4663. # Object initialization function for app.new_object()
  4664. # RUNNING ON SEPARATE THREAD!
  4665. def job_init_single_geometry(job_obj, app_obj):
  4666. log.debug("Creating a CNCJob out of a single-geometry")
  4667. assert isinstance(job_obj, FlatCAMCNCjob), \
  4668. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4669. job_obj.options['xmin'] = xmin
  4670. job_obj.options['ymin'] = ymin
  4671. job_obj.options['xmax'] = xmax
  4672. job_obj.options['ymax'] = ymax
  4673. # count the tools
  4674. tool_cnt = 0
  4675. dia_cnc_dict = {}
  4676. # this turn on the FlatCAMCNCJob plot for multiple tools
  4677. job_obj.multitool = True
  4678. job_obj.multigeo = False
  4679. job_obj.cnc_tools.clear()
  4680. job_obj.options['Tools_in_use'] = tools_in_use
  4681. job_obj.segx = segx if segx else float(self.app.defaults["geometry_segx"])
  4682. job_obj.segy = segy if segy else float(self.app.defaults["geometry_segy"])
  4683. job_obj.z_pdepth = float(self.app.defaults["geometry_z_pdepth"])
  4684. job_obj.feedrate_probe = float(self.app.defaults["geometry_feedrate_probe"])
  4685. for tooluid_key in list(tools_dict.keys()):
  4686. tool_cnt += 1
  4687. dia_cnc_dict = deepcopy(tools_dict[tooluid_key])
  4688. tooldia_val = float('%.*f' % (self.decimals, float(tools_dict[tooluid_key]['tooldia'])))
  4689. dia_cnc_dict.update({
  4690. 'tooldia': tooldia_val
  4691. })
  4692. if dia_cnc_dict['offset'] == 'in':
  4693. tool_offset = -dia_cnc_dict['tooldia'] / 2
  4694. elif dia_cnc_dict['offset'].lower() == 'out':
  4695. tool_offset = dia_cnc_dict['tooldia'] / 2
  4696. elif dia_cnc_dict['offset'].lower() == 'custom':
  4697. try:
  4698. offset_value = float(self.ui.tool_offset_entry.get_value())
  4699. except ValueError:
  4700. # try to convert comma to decimal point. if it's still not working error message and return
  4701. try:
  4702. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  4703. except ValueError:
  4704. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  4705. return
  4706. if offset_value:
  4707. tool_offset = float(offset_value)
  4708. else:
  4709. self.app.inform.emit(
  4710. '[WARNING] %s' % _("Tool Offset is selected in Tool Table but no value is provided.\n"
  4711. "Add a Tool Offset or change the Offset Type.")
  4712. )
  4713. return
  4714. else:
  4715. tool_offset = 0.0
  4716. dia_cnc_dict.update({
  4717. 'offset_value': tool_offset
  4718. })
  4719. z_cut = tools_dict[tooluid_key]['data']["cutz"]
  4720. z_move = tools_dict[tooluid_key]['data']["travelz"]
  4721. feedrate = tools_dict[tooluid_key]['data']["feedrate"]
  4722. feedrate_z = tools_dict[tooluid_key]['data']["feedrate_z"]
  4723. feedrate_rapid = tools_dict[tooluid_key]['data']["feedrate_rapid"]
  4724. multidepth = tools_dict[tooluid_key]['data']["multidepth"]
  4725. extracut = tools_dict[tooluid_key]['data']["extracut"]
  4726. extracut_length = tools_dict[tooluid_key]['data']["extracut_length"]
  4727. depthpercut = tools_dict[tooluid_key]['data']["depthperpass"]
  4728. toolchange = tools_dict[tooluid_key]['data']["toolchange"]
  4729. toolchangez = tools_dict[tooluid_key]['data']["toolchangez"]
  4730. toolchangexy = tools_dict[tooluid_key]['data']["toolchangexy"]
  4731. startz = tools_dict[tooluid_key]['data']["startz"]
  4732. endz = tools_dict[tooluid_key]['data']["endz"]
  4733. endxy = self.options["endxy"]
  4734. spindlespeed = tools_dict[tooluid_key]['data']["spindlespeed"]
  4735. dwell = tools_dict[tooluid_key]['data']["dwell"]
  4736. dwelltime = tools_dict[tooluid_key]['data']["dwelltime"]
  4737. pp_geometry_name = tools_dict[tooluid_key]['data']["ppname_g"]
  4738. spindledir = self.app.defaults['geometry_spindledir']
  4739. tool_solid_geometry = self.solid_geometry
  4740. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4741. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4742. # Propagate options
  4743. job_obj.options["tooldia"] = tooldia_val
  4744. job_obj.options['type'] = 'Geometry'
  4745. job_obj.options['tool_dia'] = tooldia_val
  4746. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  4747. # to a value of 0.0005 which is 20 times less than 0.01
  4748. tol = float(self.app.defaults['global_tolerance']) / 20
  4749. res = job_obj.generate_from_geometry_2(
  4750. self, tooldia=tooldia_val, offset=tool_offset, tolerance=tol,
  4751. z_cut=z_cut, z_move=z_move,
  4752. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4753. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  4754. multidepth=multidepth, depthpercut=depthpercut,
  4755. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz, endxy=endxy,
  4756. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4757. pp_geometry_name=pp_geometry_name,
  4758. tool_no=tool_cnt)
  4759. if res == 'fail':
  4760. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  4761. return 'fail'
  4762. else:
  4763. dia_cnc_dict['gcode'] = res
  4764. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  4765. # object is the source of gcode
  4766. job_obj.toolchange_xy_type = "geometry"
  4767. self.app.inform.emit('[success] %s' % _("G-Code parsing in progress..."))
  4768. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  4769. self.app.inform.emit('[success] %s' % _("G-Code parsing finished..."))
  4770. # TODO this serve for bounding box creation only; should be optimized
  4771. # commented this; there is no need for the actual GCode geometry - the original one will serve as well
  4772. # for bounding box values
  4773. # dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  4774. try:
  4775. dia_cnc_dict['solid_geometry'] = tool_solid_geometry
  4776. self.app.inform.emit('[success] %s...' % _("Finished G-Code processing"))
  4777. except Exception as e:
  4778. self.app.inform.emit('[ERROR] %s: %s' % (_("G-Code processing failed with error"), str(e)))
  4779. job_obj.cnc_tools.update({
  4780. tooluid_key: deepcopy(dia_cnc_dict)
  4781. })
  4782. dia_cnc_dict.clear()
  4783. # Object initialization function for app.new_object()
  4784. # RUNNING ON SEPARATE THREAD!
  4785. def job_init_multi_geometry(job_obj, app_obj):
  4786. log.debug("Creating a CNCJob out of a multi-geometry")
  4787. assert isinstance(job_obj, FlatCAMCNCjob), \
  4788. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4789. current_uid = int(1)
  4790. job_obj.options['xmin'] = xmin
  4791. job_obj.options['ymin'] = ymin
  4792. job_obj.options['xmax'] = xmax
  4793. job_obj.options['ymax'] = ymax
  4794. # count the tools
  4795. tool_cnt = 0
  4796. dia_cnc_dict = {}
  4797. # this turn on the FlatCAMCNCJob plot for multiple tools
  4798. job_obj.multitool = True
  4799. job_obj.multigeo = True
  4800. job_obj.cnc_tools.clear()
  4801. job_obj.options['Tools_in_use'] = tools_in_use
  4802. job_obj.segx = segx if segx else float(self.app.defaults["geometry_segx"])
  4803. job_obj.segy = segy if segy else float(self.app.defaults["geometry_segy"])
  4804. job_obj.z_pdepth = float(self.app.defaults["geometry_z_pdepth"])
  4805. job_obj.feedrate_probe = float(self.app.defaults["geometry_feedrate_probe"])
  4806. # make sure that trying to make a CNCJob from an empty file is not creating an app crash
  4807. if not self.solid_geometry:
  4808. a = 0
  4809. for tooluid_key in self.tools:
  4810. if self.tools[tooluid_key]['solid_geometry'] is None:
  4811. a += 1
  4812. if a == len(self.tools):
  4813. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('Cancelled. Empty file, it has no geometry'))
  4814. return 'fail'
  4815. for tooluid_key in list(tools_dict.keys()):
  4816. tool_cnt += 1
  4817. dia_cnc_dict = deepcopy(tools_dict[tooluid_key])
  4818. tooldia_val = float('%.*f' % (self.decimals, float(tools_dict[tooluid_key]['tooldia'])))
  4819. dia_cnc_dict.update({
  4820. 'tooldia': tooldia_val
  4821. })
  4822. # find the tool_dia associated with the tooluid_key
  4823. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  4824. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  4825. # for k, v in self.tools.items():
  4826. # if float('%.*f' % (self.decimals, float(v['tooldia']))) == tooldia_val:
  4827. # current_uid = int(k)
  4828. # break
  4829. if dia_cnc_dict['offset'] == 'in':
  4830. tool_offset = -tooldia_val / 2
  4831. elif dia_cnc_dict['offset'].lower() == 'out':
  4832. tool_offset = tooldia_val / 2
  4833. elif dia_cnc_dict['offset'].lower() == 'custom':
  4834. offset_value = float(self.ui.tool_offset_entry.get_value())
  4835. if offset_value:
  4836. tool_offset = float(offset_value)
  4837. else:
  4838. self.app.inform.emit('[WARNING] %s' %
  4839. _("Tool Offset is selected in Tool Table but "
  4840. "no value is provided.\n"
  4841. "Add a Tool Offset or change the Offset Type."))
  4842. return
  4843. else:
  4844. tool_offset = 0.0
  4845. dia_cnc_dict.update({
  4846. 'offset_value': tool_offset
  4847. })
  4848. z_cut = tools_dict[tooluid_key]['data']["cutz"]
  4849. z_move = tools_dict[tooluid_key]['data']["travelz"]
  4850. feedrate = tools_dict[tooluid_key]['data']["feedrate"]
  4851. feedrate_z = tools_dict[tooluid_key]['data']["feedrate_z"]
  4852. feedrate_rapid = tools_dict[tooluid_key]['data']["feedrate_rapid"]
  4853. multidepth = tools_dict[tooluid_key]['data']["multidepth"]
  4854. extracut = tools_dict[tooluid_key]['data']["extracut"]
  4855. extracut_length = tools_dict[tooluid_key]['data']["extracut_length"]
  4856. depthpercut = tools_dict[tooluid_key]['data']["depthperpass"]
  4857. toolchange = tools_dict[tooluid_key]['data']["toolchange"]
  4858. toolchangez = tools_dict[tooluid_key]['data']["toolchangez"]
  4859. toolchangexy = tools_dict[tooluid_key]['data']["toolchangexy"]
  4860. startz = tools_dict[tooluid_key]['data']["startz"]
  4861. endz = tools_dict[tooluid_key]['data']["endz"]
  4862. endxy = self.options["endxy"]
  4863. spindlespeed = tools_dict[tooluid_key]['data']["spindlespeed"]
  4864. dwell = tools_dict[tooluid_key]['data']["dwell"]
  4865. dwelltime = tools_dict[tooluid_key]['data']["dwelltime"]
  4866. pp_geometry_name = tools_dict[tooluid_key]['data']["ppname_g"]
  4867. spindledir = self.app.defaults['geometry_spindledir']
  4868. tool_solid_geometry = self.tools[tooluid_key]['solid_geometry']
  4869. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4870. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4871. # Propagate options
  4872. job_obj.options["tooldia"] = tooldia_val
  4873. job_obj.options['type'] = 'Geometry'
  4874. job_obj.options['tool_dia'] = tooldia_val
  4875. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  4876. # to a value of 0.0005 which is 20 times less than 0.01
  4877. tol = float(self.app.defaults['global_tolerance']) / 20
  4878. res = job_obj.generate_from_multitool_geometry(
  4879. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  4880. tolerance=tol, z_cut=z_cut, z_move=z_move,
  4881. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4882. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  4883. multidepth=multidepth, depthpercut=depthpercut,
  4884. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz, endxy=endxy,
  4885. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4886. pp_geometry_name=pp_geometry_name,
  4887. tool_no=tool_cnt)
  4888. if res == 'fail':
  4889. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  4890. return 'fail'
  4891. else:
  4892. dia_cnc_dict['gcode'] = res
  4893. self.app.inform.emit('[success] %s' % _("G-Code parsing in progress..."))
  4894. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  4895. self.app.inform.emit('[success] %s' % _("G-Code parsing finished..."))
  4896. # TODO this serve for bounding box creation only; should be optimized
  4897. # commented this; there is no need for the actual GCode geometry - the original one will serve as well
  4898. # for bounding box values
  4899. # geo_for_bound_values = cascaded_union([
  4900. # geo['geom'] for geo in dia_cnc_dict['gcode_parsed'] if geo['geom'].is_valid is True
  4901. # ])
  4902. try:
  4903. dia_cnc_dict['solid_geometry'] = deepcopy(tool_solid_geometry)
  4904. self.app.inform.emit('[success] %s' % _("Finished G-Code processing..."))
  4905. except Exception as ee:
  4906. self.app.inform.emit('[ERROR] %s: %s' % (_("G-Code processing failed with error"), str(ee)))
  4907. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  4908. # object is the source of gcode
  4909. job_obj.toolchange_xy_type = "geometry"
  4910. job_obj.cnc_tools.update({
  4911. tooluid_key: deepcopy(dia_cnc_dict)
  4912. })
  4913. dia_cnc_dict.clear()
  4914. if use_thread:
  4915. # To be run in separate thread
  4916. def job_thread(app_obj):
  4917. if self.multigeo is False:
  4918. with self.app.proc_container.new(_("Generating CNC Code")):
  4919. if app_obj.new_object("cncjob", outname, job_init_single_geometry, plot=plot) != 'fail':
  4920. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created"), outname))
  4921. else:
  4922. with self.app.proc_container.new(_("Generating CNC Code")):
  4923. if app_obj.new_object("cncjob", outname, job_init_multi_geometry) != 'fail':
  4924. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created"), outname))
  4925. # Create a promise with the name
  4926. self.app.collection.promise(outname)
  4927. # Send to worker
  4928. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  4929. else:
  4930. if self.solid_geometry:
  4931. self.app.new_object("cncjob", outname, job_init_single_geometry, plot=plot)
  4932. else:
  4933. self.app.new_object("cncjob", outname, job_init_multi_geometry, plot=plot)
  4934. def generatecncjob(
  4935. self, outname=None,
  4936. dia=None, offset=None,
  4937. z_cut=None, z_move=None,
  4938. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  4939. spindlespeed=None, dwell=None, dwelltime=None,
  4940. multidepth=None, depthperpass=None,
  4941. toolchange=None, toolchangez=None, toolchangexy=None,
  4942. extracut=None, extracut_length=None, startz=None, endz=None,
  4943. pp=None,
  4944. segx=None, segy=None,
  4945. use_thread=True,
  4946. plot=True):
  4947. """
  4948. Only used for TCL Command.
  4949. Creates a CNCJob out of this Geometry object. The actual
  4950. work is done by the target camlib.CNCjob
  4951. `generate_from_geometry_2()` method.
  4952. :param outname: Name of the new object
  4953. :param dia: Tool diameter
  4954. :param offset:
  4955. :param z_cut: Cut depth (negative value)
  4956. :param z_move: Height of the tool when travelling (not cutting)
  4957. :param feedrate: Feed rate while cutting on X - Y plane
  4958. :param feedrate_z: Feed rate while cutting on Z plane
  4959. :param feedrate_rapid: Feed rate while moving with rapids
  4960. :param spindlespeed: Spindle speed (RPM)
  4961. :param dwell:
  4962. :param dwelltime:
  4963. :param multidepth:
  4964. :param depthperpass:
  4965. :param toolchange:
  4966. :param toolchangez:
  4967. :param toolchangexy:
  4968. :param extracut:
  4969. :param extracut_length:
  4970. :param startz:
  4971. :param endz:
  4972. :param pp: Name of the preprocessor
  4973. :param segx:
  4974. :param segy:
  4975. :param use_thread:
  4976. :param plot:
  4977. :return: None
  4978. """
  4979. tooldia = dia if dia else float(self.options["cnctooldia"])
  4980. outname = outname if outname is not None else self.options["name"]
  4981. z_cut = z_cut if z_cut is not None else float(self.options["cutz"])
  4982. z_move = z_move if z_move is not None else float(self.options["travelz"])
  4983. feedrate = feedrate if feedrate is not None else float(self.options["feedrate"])
  4984. feedrate_z = feedrate_z if feedrate_z is not None else float(self.options["feedrate_z"])
  4985. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else float(self.options["feedrate_rapid"])
  4986. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  4987. depthperpass = depthperpass if depthperpass is not None else float(self.options["depthperpass"])
  4988. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  4989. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  4990. extracut = extracut if extracut is not None else float(self.options["extracut"])
  4991. extracut_length = extracut_length if extracut_length is not None else float(self.options["extracut_length"])
  4992. startz = startz if startz is not None else self.options["startz"]
  4993. endz = endz if endz is not None else float(self.options["endz"])
  4994. endxy = self.options["endxy"]
  4995. toolchangez = toolchangez if toolchangez else float(self.options["toolchangez"])
  4996. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  4997. toolchange = toolchange if toolchange else self.options["toolchange"]
  4998. offset = offset if offset else 0.0
  4999. # int or None.
  5000. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  5001. dwell = dwell if dwell else self.options["dwell"]
  5002. dwelltime = dwelltime if dwelltime else float(self.options["dwelltime"])
  5003. ppname_g = pp if pp else self.options["ppname_g"]
  5004. # Object initialization function for app.new_object()
  5005. # RUNNING ON SEPARATE THREAD!
  5006. def job_init(job_obj, app_obj):
  5007. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  5008. # Propagate options
  5009. job_obj.options["tooldia"] = tooldia
  5010. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  5011. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  5012. job_obj.options['type'] = 'Geometry'
  5013. job_obj.options['tool_dia'] = tooldia
  5014. job_obj.segx = segx
  5015. job_obj.segy = segy
  5016. job_obj.z_pdepth = float(self.options["z_pdepth"])
  5017. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  5018. job_obj.options['xmin'] = self.options['xmin']
  5019. job_obj.options['ymin'] = self.options['ymin']
  5020. job_obj.options['xmax'] = self.options['xmax']
  5021. job_obj.options['ymax'] = self.options['ymax']
  5022. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  5023. # to a value of 0.0005 which is 20 times less than 0.01
  5024. tol = float(self.app.defaults['global_tolerance']) / 20
  5025. job_obj.generate_from_geometry_2(
  5026. self, tooldia=tooldia, offset=offset, tolerance=tol,
  5027. z_cut=z_cut, z_move=z_move,
  5028. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  5029. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  5030. multidepth=multidepth, depthpercut=depthperpass,
  5031. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  5032. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz, endxy=endxy,
  5033. pp_geometry_name=ppname_g
  5034. )
  5035. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  5036. # source of gcode
  5037. job_obj.toolchange_xy_type = "geometry"
  5038. job_obj.gcode_parse()
  5039. self.app.inform.emit('[success] %s' % _("Finished G-Code processing..."))
  5040. if use_thread:
  5041. # To be run in separate thread
  5042. def job_thread(app_obj):
  5043. with self.app.proc_container.new(_("Generating CNC Code")):
  5044. app_obj.new_object("cncjob", outname, job_init, plot=plot)
  5045. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created")), outname)
  5046. # Create a promise with the name
  5047. self.app.collection.promise(outname)
  5048. # Send to worker
  5049. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  5050. else:
  5051. self.app.new_object("cncjob", outname, job_init, plot=plot)
  5052. # def on_plot_cb_click(self, *args):
  5053. # if self.muted_ui:
  5054. # return
  5055. # self.read_form_item('plot')
  5056. def scale(self, xfactor, yfactor=None, point=None):
  5057. """
  5058. Scales all geometry by a given factor.
  5059. :param xfactor: Factor by which to scale the object's geometry/
  5060. :type xfactor: float
  5061. :param yfactor: Factor by which to scale the object's geometry/
  5062. :type yfactor: float
  5063. :return: None
  5064. :rtype: None
  5065. """
  5066. log.debug("FlatCAMObj.FlatCAMGeometry.scale()")
  5067. try:
  5068. xfactor = float(xfactor)
  5069. except Exception:
  5070. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scale factor has to be a number: integer or float."))
  5071. return
  5072. if yfactor is None:
  5073. yfactor = xfactor
  5074. else:
  5075. try:
  5076. yfactor = float(yfactor)
  5077. except Exception:
  5078. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scale factor has to be a number: integer or float."))
  5079. return
  5080. if xfactor == 1 and yfactor == 1:
  5081. return
  5082. if point is None:
  5083. px = 0
  5084. py = 0
  5085. else:
  5086. px, py = point
  5087. self.geo_len = 0
  5088. self.old_disp_number = 0
  5089. self.el_count = 0
  5090. def scale_recursion(geom):
  5091. if type(geom) is list:
  5092. geoms = []
  5093. for local_geom in geom:
  5094. geoms.append(scale_recursion(local_geom))
  5095. return geoms
  5096. else:
  5097. try:
  5098. self.el_count += 1
  5099. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5100. if self.old_disp_number < disp_number <= 100:
  5101. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5102. self.old_disp_number = disp_number
  5103. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  5104. except AttributeError:
  5105. return geom
  5106. if self.multigeo is True:
  5107. for tool in self.tools:
  5108. # variables to display the percentage of work done
  5109. self.geo_len = 0
  5110. try:
  5111. self.geo_len = len(self.tools[tool]['solid_geometry'])
  5112. except TypeError:
  5113. self.geo_len = 1
  5114. self.old_disp_number = 0
  5115. self.el_count = 0
  5116. self.tools[tool]['solid_geometry'] = scale_recursion(self.tools[tool]['solid_geometry'])
  5117. try:
  5118. # variables to display the percentage of work done
  5119. self.geo_len = 0
  5120. try:
  5121. self.geo_len = len(self.solid_geometry)
  5122. except TypeError:
  5123. self.geo_len = 1
  5124. self.old_disp_number = 0
  5125. self.el_count = 0
  5126. self.solid_geometry = scale_recursion(self.solid_geometry)
  5127. except AttributeError:
  5128. self.solid_geometry = []
  5129. return
  5130. self.app.proc_container.new_text = ''
  5131. self.app.inform.emit('[success] %s' % _("Geometry Scale done."))
  5132. def offset(self, vect):
  5133. """
  5134. Offsets all geometry by a given vector/
  5135. :param vect: (x, y) vector by which to offset the object's geometry.
  5136. :type vect: tuple
  5137. :return: None
  5138. :rtype: None
  5139. """
  5140. log.debug("FlatCAMObj.FlatCAMGeometry.offset()")
  5141. try:
  5142. dx, dy = vect
  5143. except TypeError:
  5144. self.app.inform.emit('[ERROR_NOTCL] %s' %
  5145. _("An (x,y) pair of values are needed. "
  5146. "Probable you entered only one value in the Offset field.")
  5147. )
  5148. return
  5149. if dx == 0 and dy == 0:
  5150. return
  5151. self.geo_len = 0
  5152. self.old_disp_number = 0
  5153. self.el_count = 0
  5154. def translate_recursion(geom):
  5155. if type(geom) is list:
  5156. geoms = []
  5157. for local_geom in geom:
  5158. geoms.append(translate_recursion(local_geom))
  5159. return geoms
  5160. else:
  5161. try:
  5162. self.el_count += 1
  5163. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5164. if self.old_disp_number < disp_number <= 100:
  5165. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5166. self.old_disp_number = disp_number
  5167. return affinity.translate(geom, xoff=dx, yoff=dy)
  5168. except AttributeError:
  5169. return geom
  5170. if self.multigeo is True:
  5171. for tool in self.tools:
  5172. # variables to display the percentage of work done
  5173. self.geo_len = 0
  5174. try:
  5175. self.geo_len = len(self.tools[tool]['solid_geometry'])
  5176. except TypeError:
  5177. self.geo_len = 1
  5178. self.old_disp_number = 0
  5179. self.el_count = 0
  5180. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  5181. # variables to display the percentage of work done
  5182. self.geo_len = 0
  5183. try:
  5184. self.geo_len = len(self.solid_geometry)
  5185. except TypeError:
  5186. self.geo_len = 1
  5187. self.old_disp_number = 0
  5188. self.el_count = 0
  5189. self.solid_geometry = translate_recursion(self.solid_geometry)
  5190. self.app.proc_container.new_text = ''
  5191. self.app.inform.emit('[success] %s' % _("Geometry Offset done."))
  5192. def convert_units(self, units):
  5193. log.debug("FlatCAMObj.FlatCAMGeometry.convert_units()")
  5194. self.ui_disconnect()
  5195. factor = Geometry.convert_units(self, units)
  5196. self.options['cutz'] = float(self.options['cutz']) * factor
  5197. self.options['depthperpass'] = float(self.options['depthperpass']) * factor
  5198. self.options['travelz'] = float(self.options['travelz']) * factor
  5199. self.options['feedrate'] = float(self.options['feedrate']) * factor
  5200. self.options['feedrate_z'] = float(self.options['feedrate_z']) * factor
  5201. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  5202. self.options['endz'] = float(self.options['endz']) * factor
  5203. # self.options['cnctooldia'] *= factor
  5204. # self.options['painttooldia'] *= factor
  5205. # self.options['paintmargin'] *= factor
  5206. # self.options['paintoverlap'] *= factor
  5207. self.options["toolchangez"] = float(self.options["toolchangez"]) * factor
  5208. if self.app.defaults["geometry_toolchangexy"] == '':
  5209. self.options['toolchangexy'] = "0.0, 0.0"
  5210. else:
  5211. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  5212. if len(coords_xy) < 2:
  5213. self.app.inform.emit('[ERROR] %s' %
  5214. _("The Toolchange X,Y field in Edit -> Preferences "
  5215. "has to be in the format (x, y)\n"
  5216. "but now there is only one value, not two.")
  5217. )
  5218. return 'fail'
  5219. coords_xy[0] *= factor
  5220. coords_xy[1] *= factor
  5221. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  5222. if self.options['startz'] is not None:
  5223. self.options['startz'] = float(self.options['startz']) * factor
  5224. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  5225. 'endz', 'toolchangez']
  5226. if isinstance(self, FlatCAMGeometry):
  5227. temp_tools_dict = {}
  5228. tool_dia_copy = {}
  5229. data_copy = {}
  5230. for tooluid_key, tooluid_value in self.tools.items():
  5231. for dia_key, dia_value in tooluid_value.items():
  5232. if dia_key == 'tooldia':
  5233. dia_value *= factor
  5234. dia_value = float('%.*f' % (self.decimals, dia_value))
  5235. tool_dia_copy[dia_key] = dia_value
  5236. if dia_key == 'offset':
  5237. tool_dia_copy[dia_key] = dia_value
  5238. if dia_key == 'offset_value':
  5239. dia_value *= factor
  5240. tool_dia_copy[dia_key] = dia_value
  5241. # convert the value in the Custom Tool Offset entry in UI
  5242. custom_offset = None
  5243. try:
  5244. custom_offset = float(self.ui.tool_offset_entry.get_value())
  5245. except ValueError:
  5246. # try to convert comma to decimal point. if it's still not working error message and return
  5247. try:
  5248. custom_offset = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  5249. except ValueError:
  5250. self.app.inform.emit('[ERROR_NOTCL] %s' %
  5251. _("Wrong value format entered, use a number."))
  5252. return
  5253. except TypeError:
  5254. pass
  5255. if custom_offset:
  5256. custom_offset *= factor
  5257. self.ui.tool_offset_entry.set_value(custom_offset)
  5258. if dia_key == 'type':
  5259. tool_dia_copy[dia_key] = dia_value
  5260. if dia_key == 'tool_type':
  5261. tool_dia_copy[dia_key] = dia_value
  5262. if dia_key == 'data':
  5263. for data_key, data_value in dia_value.items():
  5264. # convert the form fields that are convertible
  5265. for param in param_list:
  5266. if data_key == param and data_value is not None:
  5267. data_copy[data_key] = data_value * factor
  5268. # copy the other dict entries that are not convertible
  5269. if data_key not in param_list:
  5270. data_copy[data_key] = data_value
  5271. tool_dia_copy[dia_key] = deepcopy(data_copy)
  5272. data_copy.clear()
  5273. temp_tools_dict.update({
  5274. tooluid_key: deepcopy(tool_dia_copy)
  5275. })
  5276. tool_dia_copy.clear()
  5277. self.tools.clear()
  5278. self.tools = deepcopy(temp_tools_dict)
  5279. # if there is a value in the new tool field then convert that one too
  5280. try:
  5281. self.ui.addtool_entry.returnPressed.disconnect()
  5282. except TypeError:
  5283. pass
  5284. tooldia = self.ui.addtool_entry.get_value()
  5285. if tooldia:
  5286. tooldia *= factor
  5287. tooldia = float('%.*f' % (self.decimals, tooldia))
  5288. self.ui.addtool_entry.set_value(tooldia)
  5289. self.ui.addtool_entry.returnPressed.connect(self.on_tool_add)
  5290. return factor
  5291. def plot_element(self, element, color=None, visible=None):
  5292. if color is None:
  5293. color = '#FF0000FF'
  5294. visible = visible if visible else self.options['plot']
  5295. try:
  5296. for sub_el in element:
  5297. self.plot_element(sub_el, color=color)
  5298. except TypeError: # Element is not iterable...
  5299. # if self.app.is_legacy is False:
  5300. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  5301. def plot(self, visible=None, kind=None):
  5302. """
  5303. Plot the object.
  5304. :param visible: Controls if the added shape is visible of not
  5305. :param kind: added so there is no error when a project is loaded and it has both geometry and CNCJob, because
  5306. CNCJob require the 'kind' parameter. Perhaps the FlatCAMObj.plot() has to be rewrited
  5307. :return:
  5308. """
  5309. # Does all the required setup and returns False
  5310. # if the 'ptint' option is set to False.
  5311. if not FlatCAMObj.plot(self):
  5312. return
  5313. try:
  5314. # plot solid geometries found as members of self.tools attribute dict
  5315. # for MultiGeo
  5316. if self.multigeo is True: # geo multi tool usage
  5317. for tooluid_key in self.tools:
  5318. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  5319. self.plot_element(solid_geometry, visible=visible,
  5320. color=self.app.defaults["geometry_plot_line"])
  5321. else:
  5322. # plot solid geometry that may be an direct attribute of the geometry object
  5323. # for SingleGeo
  5324. if self.solid_geometry:
  5325. self.plot_element(self.solid_geometry, visible=visible,
  5326. color=self.app.defaults["geometry_plot_line"])
  5327. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  5328. self.shapes.redraw()
  5329. except (ObjectDeleted, AttributeError):
  5330. self.shapes.clear(update=True)
  5331. def on_plot_cb_click(self, *args):
  5332. if self.muted_ui:
  5333. return
  5334. self.read_form_item('plot')
  5335. self.plot()
  5336. self.ui_disconnect()
  5337. cb_flag = self.ui.plot_cb.isChecked()
  5338. for row in range(self.ui.geo_tools_table.rowCount()):
  5339. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  5340. if cb_flag:
  5341. table_cb.setChecked(True)
  5342. else:
  5343. table_cb.setChecked(False)
  5344. self.ui_connect()
  5345. def on_plot_cb_click_table(self):
  5346. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  5347. self.ui_disconnect()
  5348. # cw = self.sender()
  5349. # cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  5350. # cw_row = cw_index.row()
  5351. check_row = 0
  5352. self.shapes.clear(update=True)
  5353. for tooluid_key in self.tools:
  5354. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  5355. # find the geo_tool_table row associated with the tooluid_key
  5356. for row in range(self.ui.geo_tools_table.rowCount()):
  5357. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  5358. if tooluid_item == int(tooluid_key):
  5359. check_row = row
  5360. break
  5361. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  5362. self.plot_element(element=solid_geometry, visible=True)
  5363. self.shapes.redraw()
  5364. # make sure that the general plot is disabled if one of the row plot's are disabled and
  5365. # if all the row plot's are enabled also enable the general plot checkbox
  5366. cb_cnt = 0
  5367. total_row = self.ui.geo_tools_table.rowCount()
  5368. for row in range(total_row):
  5369. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  5370. cb_cnt += 1
  5371. else:
  5372. cb_cnt -= 1
  5373. if cb_cnt < total_row:
  5374. self.ui.plot_cb.setChecked(False)
  5375. else:
  5376. self.ui.plot_cb.setChecked(True)
  5377. self.ui_connect()
  5378. def merge(self, geo_list, geo_final, multigeo=None):
  5379. """
  5380. Merges the geometry of objects in grb_list into
  5381. the geometry of geo_final.
  5382. :param geo_list: List of FlatCAMGerber Objects to join.
  5383. :param geo_final: Destination FlatCAMGerber object.
  5384. :param multigeo: if the merged geometry objects are of type MultiGeo
  5385. :return: None
  5386. """
  5387. if geo_final.solid_geometry is None:
  5388. geo_final.solid_geometry = []
  5389. try:
  5390. __ = iter(geo_final.solid_geometry)
  5391. except TypeError:
  5392. geo_final.solid_geometry = [geo_final.solid_geometry]
  5393. new_solid_geometry = []
  5394. new_options = {}
  5395. new_tools = {}
  5396. for geo_obj in geo_list:
  5397. for option in geo_obj.options:
  5398. if option != 'name':
  5399. try:
  5400. new_options[option] = deepcopy(geo_obj.options[option])
  5401. except Exception as e:
  5402. log.warning("Failed to copy option %s. Error: %s" % (str(option), str(e)))
  5403. # Expand lists
  5404. if type(geo_obj) is list:
  5405. FlatCAMGeometry.merge(self, geo_list=geo_obj, geo_final=geo_final)
  5406. # If not list, just append
  5407. else:
  5408. if multigeo is None or multigeo is False:
  5409. geo_final.multigeo = False
  5410. else:
  5411. geo_final.multigeo = True
  5412. try:
  5413. new_solid_geometry += deepcopy(geo_obj.solid_geometry)
  5414. except Exception as e:
  5415. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  5416. # find the tool_uid maximum value in the geo_final
  5417. try:
  5418. max_uid = max([int(i) for i in new_tools.keys()])
  5419. except ValueError:
  5420. max_uid = 0
  5421. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  5422. # to merge the obj.tools as it is likely there is none to merge.
  5423. if not isinstance(geo_obj, FlatCAMGerber) and not isinstance(geo_obj, FlatCAMExcellon):
  5424. for tool_uid in geo_obj.tools:
  5425. max_uid += 1
  5426. new_tools[max_uid] = deepcopy(geo_obj.tools[tool_uid])
  5427. geo_final.options.update(new_options)
  5428. geo_final.solid_geometry = new_solid_geometry
  5429. geo_final.tools = new_tools
  5430. @staticmethod
  5431. def get_pts(o):
  5432. """
  5433. Returns a list of all points in the object, where
  5434. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  5435. of such. Search is done recursively.
  5436. :param: geometric object
  5437. :return: List of points
  5438. :rtype: list
  5439. """
  5440. pts = []
  5441. # Iterable: descend into each item.
  5442. try:
  5443. for subo in o:
  5444. pts += FlatCAMGeometry.get_pts(subo)
  5445. # Non-iterable
  5446. except TypeError:
  5447. if o is not None:
  5448. if type(o) == MultiPolygon:
  5449. for poly in o:
  5450. pts += FlatCAMGeometry.get_pts(poly)
  5451. # ## Descend into .exerior and .interiors
  5452. elif type(o) == Polygon:
  5453. pts += FlatCAMGeometry.get_pts(o.exterior)
  5454. for i in o.interiors:
  5455. pts += FlatCAMGeometry.get_pts(i)
  5456. elif type(o) == MultiLineString:
  5457. for line in o:
  5458. pts += FlatCAMGeometry.get_pts(line)
  5459. # ## Has .coords: list them.
  5460. else:
  5461. pts += list(o.coords)
  5462. else:
  5463. return
  5464. return pts
  5465. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  5466. """
  5467. Represents G-Code.
  5468. """
  5469. optionChanged = QtCore.pyqtSignal(str)
  5470. ui_type = CNCObjectUI
  5471. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  5472. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  5473. spindlespeed=None):
  5474. log.debug("Creating CNCJob object...")
  5475. self.decimals = self.app.decimals
  5476. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  5477. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  5478. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  5479. FlatCAMObj.__init__(self, name)
  5480. self.kind = "cncjob"
  5481. self.options.update({
  5482. "plot": True,
  5483. "tooldia": 0.03937, # 0.4mm in inches
  5484. "append": "",
  5485. "prepend": "",
  5486. "dwell": False,
  5487. "dwelltime": 1,
  5488. "type": 'Geometry',
  5489. "toolchange_macro": '',
  5490. "toolchange_macro_enable": False
  5491. })
  5492. '''
  5493. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  5494. diameter of the tools and the value is another dict that will hold the data under the following form:
  5495. {tooldia: {
  5496. 'tooluid': 1,
  5497. 'offset': 'Path',
  5498. 'type_item': 'Rough',
  5499. 'tool_type': 'C1',
  5500. 'data': {} # a dict to hold the parameters
  5501. 'gcode': "" # a string with the actual GCODE
  5502. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry
  5503. (cut or move)
  5504. 'solid_geometry': []
  5505. },
  5506. ...
  5507. }
  5508. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  5509. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  5510. '''
  5511. self.cnc_tools = {}
  5512. '''
  5513. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  5514. diameter of the tools and the value is another dict that will hold the data under the following form:
  5515. {tooldia: {
  5516. 'tool': int,
  5517. 'nr_drills': int,
  5518. 'nr_slots': int,
  5519. 'offset': float,
  5520. 'data': {} # a dict to hold the parameters
  5521. 'gcode': "" # a string with the actual GCODE
  5522. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  5523. 'solid_geometry': []
  5524. },
  5525. ...
  5526. }
  5527. It is populated in the FlatCAMExcellon.on_create_cncjob_click() but actually
  5528. it's done in camlib.CNCJob.generate_from_excellon_by_tool()
  5529. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  5530. '''
  5531. self.exc_cnc_tools = {}
  5532. # flag to store if the CNCJob is part of a special group of CNCJob objects that can't be processed by the
  5533. # default engine of FlatCAM. They generated by some of tools and are special cases of CNCJob objects.
  5534. self.special_group = None
  5535. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  5536. # (like the one in the TCL Command), False
  5537. self.multitool = False
  5538. # determine if the GCode was generated out of a Excellon object or a Geometry object
  5539. self.origin_kind = None
  5540. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  5541. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  5542. self.g_x_re = re.compile(gcodex_re_string)
  5543. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  5544. self.g_y_re = re.compile(gcodey_re_string)
  5545. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  5546. self.g_z_re = re.compile(gcodez_re_string)
  5547. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  5548. self.g_f_re = re.compile(gcodef_re_string)
  5549. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  5550. self.g_t_re = re.compile(gcodet_re_string)
  5551. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  5552. self.g_nr_re = re.compile(gcodenr_re_string)
  5553. # Attributes to be included in serialization
  5554. # Always append to it because it carries contents
  5555. # from predecessors.
  5556. self.ser_attrs += ['options', 'kind', 'origin_kind', 'cnc_tools', 'exc_cnc_tools', 'multitool']
  5557. if self.app.is_legacy is False:
  5558. self.text_col = self.app.plotcanvas.new_text_collection()
  5559. self.text_col.enabled = True
  5560. self.annotation = self.app.plotcanvas.new_text_group(collection=self.text_col)
  5561. self.gcode_editor_tab = None
  5562. self.units_found = self.app.defaults['units']
  5563. def build_ui(self):
  5564. self.ui_disconnect()
  5565. FlatCAMObj.build_ui(self)
  5566. self.units = self.app.defaults['units'].upper()
  5567. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  5568. self.ui.cnc_tools_table.hide()
  5569. if self.cnc_tools:
  5570. self.ui.cnc_tools_table.show()
  5571. self.build_cnc_tools_table()
  5572. self.ui.exc_cnc_tools_table.hide()
  5573. if self.exc_cnc_tools:
  5574. self.ui.exc_cnc_tools_table.show()
  5575. self.build_excellon_cnc_tools()
  5576. #
  5577. self.ui_connect()
  5578. def build_cnc_tools_table(self):
  5579. tool_idx = 0
  5580. n = len(self.cnc_tools)
  5581. self.ui.cnc_tools_table.setRowCount(n)
  5582. for dia_key, dia_value in self.cnc_tools.items():
  5583. tool_idx += 1
  5584. row_no = tool_idx - 1
  5585. t_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  5586. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  5587. self.ui.cnc_tools_table.setItem(row_no, 0, t_id) # Tool name/id
  5588. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  5589. # There are no tool bits in MM with more than 2 decimals diameter.
  5590. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  5591. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['tooldia'])))
  5592. offset_txt = list(str(dia_value['offset']))
  5593. offset_txt[0] = offset_txt[0].upper()
  5594. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  5595. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  5596. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  5597. t_id.setFlags(QtCore.Qt.ItemIsEnabled)
  5598. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5599. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5600. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5601. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5602. # hack so the checkbox stay centered in the table cell
  5603. # used this:
  5604. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  5605. # plot_item = QtWidgets.QWidget()
  5606. # checkbox = FCCheckBox()
  5607. # checkbox.setCheckState(QtCore.Qt.Checked)
  5608. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  5609. # qhboxlayout.addWidget(checkbox)
  5610. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  5611. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  5612. plot_item = FCCheckBox()
  5613. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  5614. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  5615. if self.ui.plot_cb.isChecked():
  5616. plot_item.setChecked(True)
  5617. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  5618. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  5619. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  5620. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  5621. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  5622. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  5623. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  5624. # make the diameter column editable
  5625. # for row in range(tool_idx):
  5626. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  5627. # QtCore.Qt.ItemIsEnabled)
  5628. for row in range(tool_idx):
  5629. self.ui.cnc_tools_table.item(row, 0).setFlags(
  5630. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  5631. self.ui.cnc_tools_table.resizeColumnsToContents()
  5632. self.ui.cnc_tools_table.resizeRowsToContents()
  5633. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  5634. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  5635. vertical_header.hide()
  5636. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5637. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  5638. horizontal_header.setMinimumSectionSize(10)
  5639. horizontal_header.setDefaultSectionSize(70)
  5640. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  5641. horizontal_header.resizeSection(0, 20)
  5642. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  5643. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  5644. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  5645. horizontal_header.resizeSection(4, 40)
  5646. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  5647. horizontal_header.resizeSection(4, 17)
  5648. # horizontal_header.setStretchLastSection(True)
  5649. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5650. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  5651. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  5652. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  5653. # self.ui.geo_tools_table.setSortingEnabled(True)
  5654. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  5655. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  5656. def build_excellon_cnc_tools(self):
  5657. tool_idx = 0
  5658. n = len(self.exc_cnc_tools)
  5659. self.ui.exc_cnc_tools_table.setRowCount(n)
  5660. for tooldia_key, dia_value in self.exc_cnc_tools.items():
  5661. tool_idx += 1
  5662. row_no = tool_idx - 1
  5663. t_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  5664. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(tooldia_key)))
  5665. nr_drills_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_drills']))
  5666. nr_slots_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_slots']))
  5667. cutz_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['offset_z']) + self.z_cut))
  5668. t_id.setFlags(QtCore.Qt.ItemIsEnabled)
  5669. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5670. nr_drills_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5671. nr_slots_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5672. cutz_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5673. # hack so the checkbox stay centered in the table cell
  5674. # used this:
  5675. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  5676. # plot_item = QtWidgets.QWidget()
  5677. # checkbox = FCCheckBox()
  5678. # checkbox.setCheckState(QtCore.Qt.Checked)
  5679. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  5680. # qhboxlayout.addWidget(checkbox)
  5681. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  5682. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  5683. plot_item = FCCheckBox()
  5684. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  5685. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_value['tool']))
  5686. if self.ui.plot_cb.isChecked():
  5687. plot_item.setChecked(True)
  5688. # TODO until the feature of individual plot for an Excellon tool is implemented
  5689. plot_item.setDisabled(True)
  5690. self.ui.exc_cnc_tools_table.setItem(row_no, 0, t_id) # Tool name/id
  5691. self.ui.exc_cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  5692. self.ui.exc_cnc_tools_table.setItem(row_no, 2, nr_drills_item) # Nr of drills
  5693. self.ui.exc_cnc_tools_table.setItem(row_no, 3, nr_slots_item) # Nr of slots
  5694. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  5695. self.ui.exc_cnc_tools_table.setItem(row_no, 4, tool_uid_item) # Tool unique ID)
  5696. self.ui.exc_cnc_tools_table.setItem(row_no, 5, cutz_item)
  5697. self.ui.exc_cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  5698. for row in range(tool_idx):
  5699. self.ui.exc_cnc_tools_table.item(row, 0).setFlags(
  5700. self.ui.exc_cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  5701. self.ui.exc_cnc_tools_table.resizeColumnsToContents()
  5702. self.ui.exc_cnc_tools_table.resizeRowsToContents()
  5703. vertical_header = self.ui.exc_cnc_tools_table.verticalHeader()
  5704. vertical_header.hide()
  5705. self.ui.exc_cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5706. horizontal_header = self.ui.exc_cnc_tools_table.horizontalHeader()
  5707. horizontal_header.setMinimumSectionSize(10)
  5708. horizontal_header.setDefaultSectionSize(70)
  5709. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  5710. horizontal_header.resizeSection(0, 20)
  5711. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  5712. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  5713. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  5714. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
  5715. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  5716. # horizontal_header.setStretchLastSection(True)
  5717. self.ui.exc_cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5718. self.ui.exc_cnc_tools_table.setColumnWidth(0, 20)
  5719. self.ui.exc_cnc_tools_table.setColumnWidth(6, 17)
  5720. self.ui.exc_cnc_tools_table.setMinimumHeight(self.ui.exc_cnc_tools_table.getHeight())
  5721. self.ui.exc_cnc_tools_table.setMaximumHeight(self.ui.exc_cnc_tools_table.getHeight())
  5722. def set_ui(self, ui):
  5723. FlatCAMObj.set_ui(self, ui)
  5724. log.debug("FlatCAMCNCJob.set_ui()")
  5725. assert isinstance(self.ui, CNCObjectUI), \
  5726. "Expected a CNCObjectUI, got %s" % type(self.ui)
  5727. self.units = self.app.defaults['units'].upper()
  5728. self.units_found = self.app.defaults['units']
  5729. # this signal has to be connected to it's slot before the defaults are populated
  5730. # the decision done in the slot has to override the default value set bellow
  5731. self.ui.toolchange_cb.toggled.connect(self.on_toolchange_custom_clicked)
  5732. self.form_fields.update({
  5733. "plot": self.ui.plot_cb,
  5734. "tooldia": self.ui.tooldia_entry,
  5735. "append": self.ui.append_text,
  5736. "prepend": self.ui.prepend_text,
  5737. "toolchange_macro": self.ui.toolchange_text,
  5738. "toolchange_macro_enable": self.ui.toolchange_cb
  5739. })
  5740. # Fill form fields only on object create
  5741. self.to_form()
  5742. # this means that the object that created this CNCJob was an Excellon or Geometry
  5743. try:
  5744. if self.travel_distance:
  5745. self.ui.t_distance_label.show()
  5746. self.ui.t_distance_entry.setVisible(True)
  5747. self.ui.t_distance_entry.setDisabled(True)
  5748. self.ui.t_distance_entry.set_value('%.*f' % (self.decimals, float(self.travel_distance)))
  5749. self.ui.units_label.setText(str(self.units).lower())
  5750. self.ui.units_label.setDisabled(True)
  5751. self.ui.t_time_label.show()
  5752. self.ui.t_time_entry.setVisible(True)
  5753. self.ui.t_time_entry.setDisabled(True)
  5754. # if time is more than 1 then we have minutes, else we have seconds
  5755. if self.routing_time > 1:
  5756. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(self.routing_time))))
  5757. self.ui.units_time_label.setText('min')
  5758. else:
  5759. time_r = self.routing_time * 60
  5760. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(time_r))))
  5761. self.ui.units_time_label.setText('sec')
  5762. self.ui.units_time_label.setDisabled(True)
  5763. except AttributeError:
  5764. pass
  5765. if self.multitool is False:
  5766. self.ui.tooldia_entry.show()
  5767. self.ui.updateplot_button.show()
  5768. else:
  5769. self.ui.tooldia_entry.hide()
  5770. self.ui.updateplot_button.hide()
  5771. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  5772. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  5773. try:
  5774. self.ui.annotation_cb.stateChanged.disconnect(self.on_annotation_change)
  5775. except (TypeError, AttributeError):
  5776. pass
  5777. self.ui.annotation_cb.stateChanged.connect(self.on_annotation_change)
  5778. # set if to display text annotations
  5779. self.ui.annotation_cb.set_value(self.app.defaults["cncjob_annotation"])
  5780. # Show/Hide Advanced Options
  5781. if self.app.defaults["global_app_level"] == 'b':
  5782. self.ui.level.setText(_(
  5783. '<span style="color:green;"><b>Basic</b></span>'
  5784. ))
  5785. self.ui.cnc_frame.hide()
  5786. else:
  5787. self.ui.level.setText(_(
  5788. '<span style="color:red;"><b>Advanced</b></span>'
  5789. ))
  5790. self.ui.cnc_frame.show()
  5791. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  5792. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  5793. self.ui.modify_gcode_button.clicked.connect(self.on_edit_code_click)
  5794. self.ui.tc_variable_combo.currentIndexChanged[str].connect(self.on_cnc_custom_parameters)
  5795. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  5796. def on_cnc_custom_parameters(self, signal_text):
  5797. if signal_text == 'Parameters':
  5798. return
  5799. else:
  5800. self.ui.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5801. def ui_connect(self):
  5802. for row in range(self.ui.cnc_tools_table.rowCount()):
  5803. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  5804. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  5805. def ui_disconnect(self):
  5806. for row in range(self.ui.cnc_tools_table.rowCount()):
  5807. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  5808. try:
  5809. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  5810. except (TypeError, AttributeError):
  5811. pass
  5812. def on_updateplot_button_click(self, *args):
  5813. """
  5814. Callback for the "Updata Plot" button. Reads the form for updates
  5815. and plots the object.
  5816. """
  5817. self.read_form()
  5818. self.on_plot_kind_change()
  5819. def on_plot_kind_change(self):
  5820. kind = self.ui.cncplot_method_combo.get_value()
  5821. def worker_task():
  5822. with self.app.proc_container.new(_("Plotting...")):
  5823. self.plot(kind=kind)
  5824. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  5825. def on_exportgcode_button_click(self, *args):
  5826. """
  5827. Handler activated by a button clicked when exporting GCode.
  5828. :param args:
  5829. :return:
  5830. """
  5831. self.app.report_usage("cncjob_on_exportgcode_button")
  5832. self.read_form()
  5833. name = self.app.collection.get_active().options['name']
  5834. save_gcode = False
  5835. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5836. _filter_ = "RML1 Files .rol (*.rol);;All Files (*.*)"
  5837. elif 'hpgl' in self.pp_geometry_name:
  5838. _filter_ = "HPGL Files .plt (*.plt);;All Files (*.*)"
  5839. else:
  5840. save_gcode = True
  5841. _filter_ = self.app.defaults['cncjob_save_filters']
  5842. try:
  5843. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  5844. filename, _f = FCFileSaveDialog.get_saved_filename(
  5845. caption=_("Export Machine Code ..."),
  5846. directory=dir_file_to_save,
  5847. filter=_filter_
  5848. )
  5849. except TypeError:
  5850. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Machine Code ..."), filter=_filter_)
  5851. filename = str(filename)
  5852. if filename == '':
  5853. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export Machine Code cancelled ..."))
  5854. return
  5855. else:
  5856. if save_gcode is True:
  5857. used_extension = filename.rpartition('.')[2]
  5858. self.update_filters(last_ext=used_extension, filter_string='cncjob_save_filters')
  5859. new_name = os.path.split(str(filename))[1].rpartition('.')[0]
  5860. self.ui.name_entry.set_value(new_name)
  5861. self.on_name_activate(silent=True)
  5862. preamble = str(self.ui.prepend_text.get_value())
  5863. postamble = str(self.ui.append_text.get_value())
  5864. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  5865. if gc == 'fail':
  5866. return
  5867. if self.app.defaults["global_open_style"] is False:
  5868. self.app.file_opened.emit("gcode", filename)
  5869. self.app.file_saved.emit("gcode", filename)
  5870. self.app.inform.emit('[success] %s: %s' % (_("Machine Code file saved to"), filename))
  5871. def on_edit_code_click(self, *args):
  5872. """
  5873. Handler activated by a button clicked when editing GCode.
  5874. :param args:
  5875. :return:
  5876. """
  5877. self.app.proc_container.view.set_busy(_("Loading..."))
  5878. preamble = str(self.ui.prepend_text.get_value())
  5879. postamble = str(self.ui.append_text.get_value())
  5880. gco = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  5881. if gco == 'fail':
  5882. return
  5883. else:
  5884. self.app.gcode_edited = gco
  5885. self.gcode_editor_tab = TextEditor(app=self.app, plain_text=True)
  5886. # add the tab if it was closed
  5887. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Code Editor"))
  5888. self.gcode_editor_tab.setObjectName('code_editor_tab')
  5889. # delete the absolute and relative position and messages in the infobar
  5890. self.app.ui.position_label.setText("")
  5891. self.app.ui.rel_position_label.setText("")
  5892. # first clear previous text in text editor (if any)
  5893. self.gcode_editor_tab.code_editor.clear()
  5894. self.gcode_editor_tab.code_editor.setReadOnly(False)
  5895. self.gcode_editor_tab.code_editor.completer_enable = False
  5896. self.gcode_editor_tab.buttonRun.hide()
  5897. # Switch plot_area to CNCJob tab
  5898. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  5899. self.gcode_editor_tab.t_frame.hide()
  5900. # then append the text from GCode to the text editor
  5901. try:
  5902. self.gcode_editor_tab.code_editor.setPlainText(self.app.gcode_edited.getvalue())
  5903. # for line in self.app.gcode_edited:
  5904. # QtWidgets.QApplication.processEvents()
  5905. #
  5906. # proc_line = str(line).strip('\n')
  5907. # self.gcode_editor_tab.code_editor.append(proc_line)
  5908. except Exception as e:
  5909. log.debug('FlatCAMCNNJob.on_edit_code_click() -->%s' % str(e))
  5910. self.app.inform.emit('[ERROR] %s %s' % ('FlatCAMCNNJob.on_edit_code_click() -->', str(e)))
  5911. return
  5912. self.gcode_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5913. self.gcode_editor_tab.handleTextChanged()
  5914. self.gcode_editor_tab.t_frame.show()
  5915. self.app.proc_container.view.set_idle()
  5916. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  5917. def gcode_header(self, comment_start_symbol=None, comment_stop_symbol=None):
  5918. """
  5919. Will create a header to be added to all GCode files generated by FlatCAM
  5920. :param comment_start_symbol: A symbol to be used as the first symbol in a comment
  5921. :param comment_stop_symbol: A symbol to be used as the last symbol in a comment
  5922. :return: A string with a GCode header
  5923. """
  5924. log.debug("FlatCAMCNCJob.gcode_header()")
  5925. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5926. marlin = False
  5927. hpgl = False
  5928. probe_pp = False
  5929. start_comment = comment_start_symbol if comment_start_symbol is not None else '('
  5930. stop_comment = comment_stop_symbol if comment_stop_symbol is not None else ')'
  5931. try:
  5932. for key in self.cnc_tools:
  5933. ppg = self.cnc_tools[key]['data']['ppname_g']
  5934. if 'marlin' in ppg.lower() or 'repetier' in ppg.lower():
  5935. marlin = True
  5936. break
  5937. if ppg == 'hpgl':
  5938. hpgl = True
  5939. break
  5940. if "toolchange_probe" in ppg.lower():
  5941. probe_pp = True
  5942. break
  5943. except KeyError:
  5944. # log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  5945. pass
  5946. try:
  5947. if 'marlin' in self.options['ppname_e'].lower() or 'repetier' in self.options['ppname_e'].lower():
  5948. marlin = True
  5949. except KeyError:
  5950. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  5951. pass
  5952. try:
  5953. if "toolchange_probe" in self.options['ppname_e'].lower():
  5954. probe_pp = True
  5955. except KeyError:
  5956. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  5957. pass
  5958. if marlin is True:
  5959. gcode = ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5960. (str(self.app.version), str(self.app.version_date)) + '\n'
  5961. gcode += ';Name: ' + str(self.options['name']) + '\n'
  5962. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  5963. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5964. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5965. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  5966. gcode += ';Created on ' + time_str + '\n' + '\n'
  5967. elif hpgl is True:
  5968. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  5969. (str(self.app.version), str(self.app.version_date)) + '";\n'
  5970. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  5971. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  5972. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5973. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5974. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  5975. gcode += 'CO "Created on ' + time_str + '";\n'
  5976. elif probe_pp is True:
  5977. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  5978. (str(self.app.version), str(self.app.version_date)) + '\n'
  5979. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  5980. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  5981. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  5982. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  5983. 'Then zero the Z axis.)\n' + '\n'
  5984. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  5985. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  5986. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5987. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5988. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  5989. gcode += '(Created on ' + time_str + ')\n' + '\n'
  5990. else:
  5991. gcode = '%sG-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s%s\n' % \
  5992. (start_comment, str(self.app.version), str(self.app.version_date), stop_comment) + '\n'
  5993. gcode += '%sName: ' % start_comment + str(self.options['name']) + '%s\n' % stop_comment
  5994. gcode += '%sType: ' % start_comment + "G-code from " + str(self.options['type']) + '%s\n' % stop_comment
  5995. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5996. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5997. gcode += '%sUnits: ' % start_comment + self.units.upper() + '%s\n' % stop_comment + "\n"
  5998. gcode += '%sCreated on ' % start_comment + time_str + '%s\n' % stop_comment + '\n'
  5999. return gcode
  6000. def gcode_footer(self, end_command=None):
  6001. """
  6002. Will add the M02 to the end of GCode, if requested.
  6003. :param end_command: 'M02' or 'M30' - String
  6004. :return:
  6005. """
  6006. if end_command:
  6007. return end_command
  6008. else:
  6009. return 'M02'
  6010. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  6011. """
  6012. This will save the GCode from the Gcode object to a file on the OS filesystem
  6013. :param filename: filename for the GCode file
  6014. :param preamble: a custom Gcode block to be added at the beginning of the Gcode file
  6015. :param postamble: a custom Gcode block to be added at the end of the Gcode file
  6016. :param to_file: if False then no actual file is saved but the app will know that a file was created
  6017. :return: None
  6018. """
  6019. # gcode = ''
  6020. # roland = False
  6021. # hpgl = False
  6022. # isel_icp = False
  6023. include_header = True
  6024. try:
  6025. if self.special_group:
  6026. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  6027. (_("This CNCJob object can't be processed because it is a"),
  6028. str(self.special_group),
  6029. _("CNCJob object")))
  6030. return 'fail'
  6031. except AttributeError:
  6032. pass
  6033. # if this dict is not empty then the object is a Geometry object
  6034. if self.cnc_tools:
  6035. first_key = next(iter(self.cnc_tools))
  6036. include_header = self.app.preprocessors[self.cnc_tools[first_key]['data']['ppname_g']].include_header
  6037. # if this dict is not empty then the object is an Excellon object
  6038. if self.exc_cnc_tools:
  6039. first_key = next(iter(self.exc_cnc_tools))
  6040. include_header = self.app.preprocessors[self.exc_cnc_tools[first_key]['data']['ppname_e']].include_header
  6041. # # detect if using Roland preprocessor
  6042. # try:
  6043. # for key in self.cnc_tools:
  6044. # if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  6045. # roland = True
  6046. # break
  6047. # except Exception:
  6048. # try:
  6049. # for key in self.cnc_tools:
  6050. # if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  6051. # roland = True
  6052. # break
  6053. # except Exception:
  6054. # pass
  6055. #
  6056. # # detect if using HPGL preprocessor
  6057. # try:
  6058. # for key in self.cnc_tools:
  6059. # if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  6060. # hpgl = True
  6061. # break
  6062. # except Exception:
  6063. # try:
  6064. # for key in self.cnc_tools:
  6065. # if self.cnc_tools[key]['data']['ppname_e'] == 'hpgl':
  6066. # hpgl = True
  6067. # break
  6068. # except Exception:
  6069. # pass
  6070. #
  6071. # # detect if using ISEL_ICP_CNC preprocessor
  6072. # try:
  6073. # for key in self.cnc_tools:
  6074. # if 'ISEL_ICP' in self.cnc_tools[key]['data']['ppname_g'].upper():
  6075. # isel_icp = True
  6076. # break
  6077. # except Exception:
  6078. # try:
  6079. # for key in self.cnc_tools:
  6080. # if 'ISEL_ICP' in self.cnc_tools[key]['data']['ppname_e'].upper():
  6081. # isel_icp = True
  6082. # break
  6083. # except Exception:
  6084. # pass
  6085. # do not add gcode_header when using the Roland preprocessor, add it for every other preprocessor
  6086. # if roland is False and hpgl is False and isel_icp is False:
  6087. # gcode = self.gcode_header()
  6088. # do not add gcode_header when using the Roland, HPGL or ISEP_ICP_CNC preprocessor (or any other preprocessor
  6089. # that has the include_header attribute set as False, add it for every other preprocessor
  6090. # if include_header:
  6091. # gcode = self.gcode_header()
  6092. # else:
  6093. # gcode = ''
  6094. # # detect if using multi-tool and make the Gcode summation correctly for each case
  6095. # if self.multitool is True:
  6096. # for tooluid_key in self.cnc_tools:
  6097. # for key, value in self.cnc_tools[tooluid_key].items():
  6098. # if key == 'gcode':
  6099. # gcode += value
  6100. # break
  6101. # else:
  6102. # gcode += self.gcode
  6103. # if roland is True:
  6104. # g = preamble + gcode + postamble
  6105. # elif hpgl is True:
  6106. # g = self.gcode_header() + preamble + gcode + postamble
  6107. # else:
  6108. # # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  6109. # g_idx = gcode.rfind('G20')
  6110. #
  6111. # # if it did not find 'G20' then search for 'G21'
  6112. # if g_idx == -1:
  6113. # g_idx = gcode.rfind('G21')
  6114. #
  6115. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  6116. # # but only when the preprocessor is not ISEL_ICP who is allowed not to have the G20/G21 command
  6117. # if g_idx == -1 and isel_icp is False:
  6118. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  6119. # return
  6120. #
  6121. # footer = self.app.defaults['cncjob_footer']
  6122. # end_gcode = self.gcode_footer() if footer is True else ''
  6123. # g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble + end_gcode
  6124. gcode = ''
  6125. if include_header is False:
  6126. g = preamble
  6127. # detect if using multi-tool and make the Gcode summation correctly for each case
  6128. if self.multitool is True:
  6129. for tooluid_key in self.cnc_tools:
  6130. for key, value in self.cnc_tools[tooluid_key].items():
  6131. if key == 'gcode':
  6132. gcode += value
  6133. break
  6134. else:
  6135. gcode += self.gcode
  6136. g = g + gcode + postamble
  6137. else:
  6138. # search for the GCode beginning which is usually a G20 or G21
  6139. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  6140. # g_idx = gcode.rfind('G20')
  6141. #
  6142. # # if it did not find 'G20' then search for 'G21'
  6143. # if g_idx == -1:
  6144. # g_idx = gcode.rfind('G21')
  6145. #
  6146. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  6147. # if g_idx == -1:
  6148. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  6149. # return
  6150. # detect if using multi-tool and make the Gcode summation correctly for each case
  6151. if self.multitool is True:
  6152. for tooluid_key in self.cnc_tools:
  6153. for key, value in self.cnc_tools[tooluid_key].items():
  6154. if key == 'gcode':
  6155. gcode += value
  6156. break
  6157. else:
  6158. gcode += self.gcode
  6159. end_gcode = self.gcode_footer() if self.app.defaults['cncjob_footer'] is True else ''
  6160. # detect if using a HPGL preprocessor
  6161. hpgl = False
  6162. if self.cnc_tools:
  6163. for key in self.cnc_tools:
  6164. if 'ppname_g' in self.cnc_tools[key]['data']:
  6165. if 'hpgl' in self.cnc_tools[key]['data']['ppname_g']:
  6166. hpgl = True
  6167. break
  6168. elif self.exc_cnc_tools:
  6169. for key in self.cnc_tools:
  6170. if 'ppname_e' in self.cnc_tools[key]['data']:
  6171. if 'hpgl' in self.cnc_tools[key]['data']['ppname_e']:
  6172. hpgl = True
  6173. break
  6174. if hpgl:
  6175. processed_gcode = ''
  6176. pa_re = re.compile(r"^PA\s*(-?\d+\.\d*),?\s*(-?\d+\.\d*)*;?$")
  6177. for gline in gcode.splitlines():
  6178. match = pa_re.search(gline)
  6179. if match:
  6180. x_int = int(float(match.group(1)))
  6181. y_int = int(float(match.group(2)))
  6182. new_line = 'PA%d,%d;\n' % (x_int, y_int)
  6183. processed_gcode += new_line
  6184. else:
  6185. processed_gcode += gline + '\n'
  6186. gcode = processed_gcode
  6187. g = self.gcode_header() + '\n' + preamble + '\n' + gcode + postamble + end_gcode
  6188. else:
  6189. try:
  6190. g_idx = gcode.index('G94')
  6191. g = self.gcode_header() + gcode[:g_idx + 3] + '\n\n' + preamble + '\n' + \
  6192. gcode[(g_idx + 3):] + postamble + end_gcode
  6193. except ValueError:
  6194. self.app.inform.emit('[ERROR_NOTCL] %s' %
  6195. _("G-code does not have a G94 code and we will not include the code in the "
  6196. "'Prepend to GCode' text box"))
  6197. g = self.gcode_header() + '\n' + gcode + postamble + end_gcode
  6198. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  6199. if self.ui.toolchange_cb.get_value() is True:
  6200. # match = self.re_toolchange.search(g)
  6201. if 'M6' in g:
  6202. m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  6203. if m6_code is None or m6_code == '':
  6204. self.app.inform.emit(
  6205. '[ERROR_NOTCL] %s' % _("Cancelled. The Toolchange Custom code is enabled but it's empty.")
  6206. )
  6207. return 'fail'
  6208. g = g.replace('M6', m6_code)
  6209. self.app.inform.emit('[success] %s' % _("Toolchange G-code was replaced by a custom code."))
  6210. lines = StringIO(g)
  6211. # Write
  6212. if filename is not None:
  6213. try:
  6214. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  6215. if force_windows_line_endings and sys.platform != 'win32':
  6216. with open(filename, 'w', newline='\r\n') as f:
  6217. for line in lines:
  6218. f.write(line)
  6219. else:
  6220. with open(filename, 'w') as f:
  6221. for line in lines:
  6222. f.write(line)
  6223. except FileNotFoundError:
  6224. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  6225. return
  6226. except PermissionError:
  6227. self.app.inform.emit(
  6228. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  6229. "Most likely another app is holding the file open and not accessible.")
  6230. )
  6231. return 'fail'
  6232. elif to_file is False:
  6233. # Just for adding it to the recent files list.
  6234. if self.app.defaults["global_open_style"] is False:
  6235. self.app.file_opened.emit("cncjob", filename)
  6236. self.app.file_saved.emit("cncjob", filename)
  6237. self.app.inform.emit('[success] %s: %s' % (_("Saved to"), filename))
  6238. else:
  6239. return lines
  6240. def on_toolchange_custom_clicked(self, signal):
  6241. """
  6242. Handler for clicking toolchange custom.
  6243. :param signal:
  6244. :return:
  6245. """
  6246. try:
  6247. if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  6248. if self.ui.toolchange_cb.get_value():
  6249. self.ui.toolchange_cb.set_value(False)
  6250. self.app.inform.emit('[WARNING_NOTCL] %s' %
  6251. _("The used preprocessor file has to have in it's name: 'toolchange_custom'"))
  6252. except KeyError:
  6253. try:
  6254. for key in self.cnc_tools:
  6255. ppg = self.cnc_tools[key]['data']['ppname_g']
  6256. if 'toolchange_custom' not in str(ppg).lower():
  6257. print(ppg)
  6258. if self.ui.toolchange_cb.get_value():
  6259. self.ui.toolchange_cb.set_value(False)
  6260. self.app.inform.emit('[WARNING_NOTCL] %s' %
  6261. _("The used preprocessor file has to have in it's name: "
  6262. "'toolchange_custom'"))
  6263. except KeyError:
  6264. self.app.inform.emit('[ERROR] %s' % _("There is no preprocessor file."))
  6265. def get_gcode(self, preamble='', postamble=''):
  6266. """
  6267. We need this to be able to get_gcode separately for shell command export_gcode
  6268. :param preamble: Extra GCode added to the beginning of the GCode
  6269. :param postamble: Extra GCode added at the end of the GCode
  6270. :return: The modified GCode
  6271. """
  6272. return preamble + '\n' + self.gcode + "\n" + postamble
  6273. def get_svg(self):
  6274. # we need this to be able get_svg separately for shell command export_svg
  6275. pass
  6276. def on_plot_cb_click(self, *args):
  6277. """
  6278. Handler for clicking on the Plot checkbox.
  6279. :param args:
  6280. :return:
  6281. """
  6282. if self.muted_ui:
  6283. return
  6284. kind = self.ui.cncplot_method_combo.get_value()
  6285. self.plot(kind=kind)
  6286. self.read_form_item('plot')
  6287. self.ui_disconnect()
  6288. cb_flag = self.ui.plot_cb.isChecked()
  6289. for row in range(self.ui.cnc_tools_table.rowCount()):
  6290. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  6291. if cb_flag:
  6292. table_cb.setChecked(True)
  6293. else:
  6294. table_cb.setChecked(False)
  6295. self.ui_connect()
  6296. def on_plot_cb_click_table(self):
  6297. """
  6298. Handler for clicking the plot checkboxes added into a Table on each row. Purpose: toggle visibility for the
  6299. tool/aperture found on that row.
  6300. :return:
  6301. """
  6302. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  6303. self.ui_disconnect()
  6304. # cw = self.sender()
  6305. # cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  6306. # cw_row = cw_index.row()
  6307. kind = self.ui.cncplot_method_combo.get_value()
  6308. self.shapes.clear(update=True)
  6309. for tooluid_key in self.cnc_tools:
  6310. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  6311. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  6312. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  6313. for r in range(self.ui.cnc_tools_table.rowCount()):
  6314. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  6315. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  6316. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  6317. self.shapes.redraw()
  6318. # make sure that the general plot is disabled if one of the row plot's are disabled and
  6319. # if all the row plot's are enabled also enable the general plot checkbox
  6320. cb_cnt = 0
  6321. total_row = self.ui.cnc_tools_table.rowCount()
  6322. for row in range(total_row):
  6323. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  6324. cb_cnt += 1
  6325. else:
  6326. cb_cnt -= 1
  6327. if cb_cnt < total_row:
  6328. self.ui.plot_cb.setChecked(False)
  6329. else:
  6330. self.ui.plot_cb.setChecked(True)
  6331. self.ui_connect()
  6332. def plot(self, visible=None, kind='all'):
  6333. """
  6334. # Does all the required setup and returns False
  6335. # if the 'ptint' option is set to False.
  6336. :param visible: Boolean to decide if the object will be plotted as visible or disabled on canvas
  6337. :param kind: String. Can be "all" or "travel" or "cut". For CNCJob plotting
  6338. :return: None
  6339. """
  6340. if not FlatCAMObj.plot(self):
  6341. return
  6342. visible = visible if visible else self.options['plot']
  6343. if self.app.is_legacy is False:
  6344. if self.ui.annotation_cb.get_value() and self.ui.plot_cb.get_value():
  6345. self.text_col.enabled = True
  6346. else:
  6347. self.text_col.enabled = False
  6348. self.annotation.redraw()
  6349. try:
  6350. if self.multitool is False: # single tool usage
  6351. try:
  6352. dia_plot = float(self.options["tooldia"])
  6353. except ValueError:
  6354. # we may have a tuple with only one element and a comma
  6355. dia_plot = [float(el) for el in self.options["tooldia"].split(',') if el != ''][0]
  6356. self.plot2(dia_plot, obj=self, visible=visible, kind=kind)
  6357. else:
  6358. # multiple tools usage
  6359. if self.cnc_tools:
  6360. for tooluid_key in self.cnc_tools:
  6361. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  6362. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  6363. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  6364. # TODO: until the gcode parsed will be stored on each Excellon tool this will not get executed
  6365. if self.exc_cnc_tools:
  6366. for tooldia_key in self.exc_cnc_tools:
  6367. tooldia = float('%.*f' % (self.decimals, float(tooldia_key)))
  6368. # gcode_parsed = self.cnc_tools[tooldia_key]['gcode_parsed']
  6369. gcode_parsed = self.gcode_parsed
  6370. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  6371. self.shapes.redraw()
  6372. except (ObjectDeleted, AttributeError):
  6373. self.shapes.clear(update=True)
  6374. if self.app.is_legacy is False:
  6375. self.annotation.clear(update=True)
  6376. def on_annotation_change(self):
  6377. """
  6378. Handler for toggling the annotation display by clicking a checkbox.
  6379. :return:
  6380. """
  6381. if self.app.is_legacy is False:
  6382. if self.ui.annotation_cb.get_value():
  6383. self.text_col.enabled = True
  6384. else:
  6385. self.text_col.enabled = False
  6386. # kind = self.ui.cncplot_method_combo.get_value()
  6387. # self.plot(kind=kind)
  6388. self.annotation.redraw()
  6389. else:
  6390. kind = self.ui.cncplot_method_combo.get_value()
  6391. self.plot(kind=kind)
  6392. def convert_units(self, units):
  6393. """
  6394. Units conversion used by the CNCJob objects.
  6395. :param units: Can be "MM" or "IN"
  6396. :return:
  6397. """
  6398. log.debug("FlatCAMObj.FlatCAMECNCjob.convert_units()")
  6399. factor = CNCjob.convert_units(self, units)
  6400. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  6401. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  6402. 'endz', 'toolchangez']
  6403. temp_tools_dict = {}
  6404. tool_dia_copy = {}
  6405. data_copy = {}
  6406. for tooluid_key, tooluid_value in self.cnc_tools.items():
  6407. for dia_key, dia_value in tooluid_value.items():
  6408. if dia_key == 'tooldia':
  6409. dia_value *= factor
  6410. dia_value = float('%.*f' % (self.decimals, dia_value))
  6411. tool_dia_copy[dia_key] = dia_value
  6412. if dia_key == 'offset':
  6413. tool_dia_copy[dia_key] = dia_value
  6414. if dia_key == 'offset_value':
  6415. dia_value *= factor
  6416. tool_dia_copy[dia_key] = dia_value
  6417. if dia_key == 'type':
  6418. tool_dia_copy[dia_key] = dia_value
  6419. if dia_key == 'tool_type':
  6420. tool_dia_copy[dia_key] = dia_value
  6421. if dia_key == 'data':
  6422. for data_key, data_value in dia_value.items():
  6423. # convert the form fields that are convertible
  6424. for param in param_list:
  6425. if data_key == param and data_value is not None:
  6426. data_copy[data_key] = data_value * factor
  6427. # copy the other dict entries that are not convertible
  6428. if data_key not in param_list:
  6429. data_copy[data_key] = data_value
  6430. tool_dia_copy[dia_key] = deepcopy(data_copy)
  6431. data_copy.clear()
  6432. if dia_key == 'gcode':
  6433. tool_dia_copy[dia_key] = dia_value
  6434. if dia_key == 'gcode_parsed':
  6435. tool_dia_copy[dia_key] = dia_value
  6436. if dia_key == 'solid_geometry':
  6437. tool_dia_copy[dia_key] = dia_value
  6438. # if dia_key == 'solid_geometry':
  6439. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  6440. # if dia_key == 'gcode_parsed':
  6441. # for g in dia_value:
  6442. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  6443. #
  6444. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  6445. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  6446. temp_tools_dict.update({
  6447. tooluid_key: deepcopy(tool_dia_copy)
  6448. })
  6449. tool_dia_copy.clear()
  6450. self.cnc_tools.clear()
  6451. self.cnc_tools = deepcopy(temp_tools_dict)
  6452. class FlatCAMScript(FlatCAMObj):
  6453. """
  6454. Represents a TCL script object.
  6455. """
  6456. optionChanged = QtCore.pyqtSignal(str)
  6457. ui_type = ScriptObjectUI
  6458. def __init__(self, name):
  6459. self.decimals = self.app.decimals
  6460. log.debug("Creating a FlatCAMScript object...")
  6461. FlatCAMObj.__init__(self, name)
  6462. self.kind = "script"
  6463. self.options.update({
  6464. "plot": True,
  6465. "type": 'Script',
  6466. "source_file": '',
  6467. })
  6468. self.units = ''
  6469. self.ser_attrs = ['options', 'kind', 'source_file']
  6470. self.source_file = ''
  6471. self.script_code = ''
  6472. self.units_found = self.app.defaults['units']
  6473. # self.script_editor_tab = TextEditor(app=self.app, plain_text=True)
  6474. self.script_editor_tab = TextEditor(app=self.app, plain_text=True)
  6475. def set_ui(self, ui):
  6476. """
  6477. Sets the Object UI in Selected Tab for the FlatCAM Script type of object.
  6478. :param ui:
  6479. :return:
  6480. """
  6481. FlatCAMObj.set_ui(self, ui)
  6482. log.debug("FlatCAMScript.set_ui()")
  6483. assert isinstance(self.ui, ScriptObjectUI), \
  6484. "Expected a ScriptObjectUI, got %s" % type(self.ui)
  6485. self.units = self.app.defaults['units'].upper()
  6486. self.units_found = self.app.defaults['units']
  6487. # Fill form fields only on object create
  6488. self.to_form()
  6489. # Show/Hide Advanced Options
  6490. if self.app.defaults["global_app_level"] == 'b':
  6491. self.ui.level.setText(_(
  6492. '<span style="color:green;"><b>Basic</b></span>'
  6493. ))
  6494. else:
  6495. self.ui.level.setText(_(
  6496. '<span style="color:red;"><b>Advanced</b></span>'
  6497. ))
  6498. # tab_here = False
  6499. # # try to not add too many times a tab that it is already installed
  6500. # for idx in range(self.app.ui.plot_tab_area.count()):
  6501. # if self.app.ui.plot_tab_area.widget(idx).objectName() == self.options['name']:
  6502. # tab_here = True
  6503. # break
  6504. #
  6505. # # add the tab if it is not already added
  6506. # if tab_here is False:
  6507. # self.app.ui.plot_tab_area.addTab(self.script_editor_tab, '%s' % _("Script Editor"))
  6508. # self.script_editor_tab.setObjectName(self.options['name'])
  6509. self.app.ui.plot_tab_area.addTab(self.script_editor_tab, '%s' % _("Script Editor"))
  6510. self.script_editor_tab.setObjectName(self.options['name'])
  6511. # first clear previous text in text editor (if any)
  6512. # self.script_editor_tab.code_editor.clear()
  6513. # self.script_editor_tab.code_editor.setReadOnly(False)
  6514. self.ui.autocomplete_cb.set_value(self.app.defaults['script_autocompleter'])
  6515. self.on_autocomplete_changed(state=self.app.defaults['script_autocompleter'])
  6516. self.script_editor_tab.buttonRun.show()
  6517. # Switch plot_area to CNCJob tab
  6518. self.app.ui.plot_tab_area.setCurrentWidget(self.script_editor_tab)
  6519. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6520. self.script_editor_tab.buttonOpen.clicked.disconnect()
  6521. self.script_editor_tab.buttonOpen.clicked.connect(lambda: self.script_editor_tab.handleOpen(filt=flt))
  6522. self.script_editor_tab.buttonSave.clicked.disconnect()
  6523. self.script_editor_tab.buttonSave.clicked.connect(lambda: self.script_editor_tab.handleSaveGCode(filt=flt))
  6524. self.script_editor_tab.buttonRun.clicked.connect(self.handle_run_code)
  6525. self.script_editor_tab.handleTextChanged()
  6526. self.ui.autocomplete_cb.stateChanged.connect(self.on_autocomplete_changed)
  6527. self.ser_attrs = ['options', 'kind', 'source_file']
  6528. # ---------------------------------------------------- #
  6529. # ----------- LOAD THE TEXT SOURCE FILE -------------- #
  6530. # ---------------------------------------------------- #
  6531. self.app.proc_container.view.set_busy(_("Loading..."))
  6532. self.script_editor_tab.t_frame.hide()
  6533. try:
  6534. self.script_editor_tab.code_editor.setPlainText(self.source_file)
  6535. # for line in self.source_file.splitlines():
  6536. # QtWidgets.QApplication.processEvents()
  6537. # self.script_editor_tab.code_editor.append(line)
  6538. except Exception as e:
  6539. log.debug("FlatCAMScript.set_ui() --> %s" % str(e))
  6540. self.script_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.End)
  6541. self.script_editor_tab.t_frame.show()
  6542. self.app.proc_container.view.set_idle()
  6543. self.build_ui()
  6544. def build_ui(self):
  6545. FlatCAMObj.build_ui(self)
  6546. def handle_run_code(self):
  6547. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  6548. # tries to print on a hidden widget, therefore show the dock if hidden
  6549. if self.app.ui.shell_dock.isHidden():
  6550. self.app.ui.shell_dock.show()
  6551. self.script_code = deepcopy(self.script_editor_tab.code_editor.toPlainText())
  6552. old_line = ''
  6553. for tcl_command_line in self.script_code.splitlines():
  6554. # do not process lines starting with '#' = comment and empty lines
  6555. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  6556. # id FlatCAM is run in Windows then replace all the slashes with
  6557. # the UNIX style slash that TCL understands
  6558. if sys.platform == 'win32':
  6559. if "open" in tcl_command_line:
  6560. tcl_command_line = tcl_command_line.replace('\\', '/')
  6561. if old_line != '':
  6562. new_command = old_line + tcl_command_line + '\n'
  6563. else:
  6564. new_command = tcl_command_line
  6565. # execute the actual Tcl command
  6566. try:
  6567. self.app.shell.open_processing() # Disables input box.
  6568. result = self.app.tcl.eval(str(new_command))
  6569. if result != 'None':
  6570. self.app.shell.append_output(result + '\n')
  6571. old_line = ''
  6572. except tk.TclError:
  6573. old_line = old_line + tcl_command_line + '\n'
  6574. except Exception as e:
  6575. log.debug("FlatCAMScript.handleRunCode() --> %s" % str(e))
  6576. if old_line != '':
  6577. # it means that the script finished with an error
  6578. result = self.app.tcl.eval("set errorInfo")
  6579. log.error("Exec command Exception: %s" % (result + '\n'))
  6580. self.app.shell.append_error('ERROR: ' + result + '\n')
  6581. self.app.shell.close_processing()
  6582. def on_autocomplete_changed(self, state):
  6583. if state:
  6584. self.script_editor_tab.code_editor.completer_enable = True
  6585. else:
  6586. self.script_editor_tab.code_editor.completer_enable = False
  6587. def to_dict(self):
  6588. """
  6589. Returns a representation of the object as a dictionary.
  6590. Attributes to include are listed in ``self.ser_attrs``.
  6591. :return: A dictionary-encoded copy of the object.
  6592. :rtype: dict
  6593. """
  6594. d = {}
  6595. for attr in self.ser_attrs:
  6596. d[attr] = getattr(self, attr)
  6597. return d
  6598. def from_dict(self, d):
  6599. """
  6600. Sets object's attributes from a dictionary.
  6601. Attributes to include are listed in ``self.ser_attrs``.
  6602. This method will look only for only and all the
  6603. attributes in ``self.ser_attrs``. They must all
  6604. be present. Use only for deserializing saved
  6605. objects.
  6606. :param d: Dictionary of attributes to set in the object.
  6607. :type d: dict
  6608. :return: None
  6609. """
  6610. for attr in self.ser_attrs:
  6611. setattr(self, attr, d[attr])
  6612. class FlatCAMDocument(FlatCAMObj):
  6613. """
  6614. Represents a Document object.
  6615. """
  6616. optionChanged = QtCore.pyqtSignal(str)
  6617. ui_type = DocumentObjectUI
  6618. def __init__(self, name):
  6619. self.decimals = self.app.decimals
  6620. log.debug("Creating a Document object...")
  6621. FlatCAMObj.__init__(self, name)
  6622. self.kind = "document"
  6623. self.units = ''
  6624. self.ser_attrs = ['options', 'kind', 'source_file']
  6625. self.source_file = ''
  6626. self.doc_code = ''
  6627. self.font_name = None
  6628. self.font_italic = None
  6629. self.font_bold = None
  6630. self.font_underline = None
  6631. self.document_editor_tab = None
  6632. self._read_only = False
  6633. self.units_found = self.app.defaults['units']
  6634. def set_ui(self, ui):
  6635. FlatCAMObj.set_ui(self, ui)
  6636. log.debug("FlatCAMDocument.set_ui()")
  6637. assert isinstance(self.ui, DocumentObjectUI), \
  6638. "Expected a DocumentObjectUI, got %s" % type(self.ui)
  6639. self.units = self.app.defaults['units'].upper()
  6640. self.units_found = self.app.defaults['units']
  6641. # Fill form fields only on object create
  6642. self.to_form()
  6643. # Show/Hide Advanced Options
  6644. if self.app.defaults["global_app_level"] == 'b':
  6645. self.ui.level.setText(_(
  6646. '<span style="color:green;"><b>Basic</b></span>'
  6647. ))
  6648. else:
  6649. self.ui.level.setText(_(
  6650. '<span style="color:red;"><b>Advanced</b></span>'
  6651. ))
  6652. self.document_editor_tab = TextEditor(app=self.app)
  6653. stylesheet = """
  6654. QTextEdit {selection-background-color:%s;
  6655. selection-color:white;
  6656. }
  6657. """ % self.app.defaults["document_sel_color"]
  6658. self.document_editor_tab.code_editor.setStyleSheet(stylesheet)
  6659. # first clear previous text in text editor (if any)
  6660. self.document_editor_tab.code_editor.clear()
  6661. self.document_editor_tab.code_editor.setReadOnly(self._read_only)
  6662. self.document_editor_tab.buttonRun.hide()
  6663. self.ui.autocomplete_cb.set_value(self.app.defaults['document_autocompleter'])
  6664. self.on_autocomplete_changed(state=self.app.defaults['document_autocompleter'])
  6665. self.on_tab_size_change(val=self.app.defaults['document_tab_size'])
  6666. flt = "FlatCAM Docs (*.FlatDoc);;All Files (*.*)"
  6667. # ######################################################################
  6668. # ######################## SIGNALS #####################################
  6669. # ######################################################################
  6670. self.document_editor_tab.buttonOpen.clicked.disconnect()
  6671. self.document_editor_tab.buttonOpen.clicked.connect(lambda: self.document_editor_tab.handleOpen(filt=flt))
  6672. self.document_editor_tab.buttonSave.clicked.disconnect()
  6673. self.document_editor_tab.buttonSave.clicked.connect(lambda: self.document_editor_tab.handleSaveGCode(filt=flt))
  6674. self.document_editor_tab.code_editor.textChanged.connect(self.on_text_changed)
  6675. self.ui.font_type_cb.currentFontChanged.connect(self.font_family)
  6676. self.ui.font_size_cb.activated.connect(self.font_size)
  6677. self.ui.font_bold_tb.clicked.connect(self.on_bold_button)
  6678. self.ui.font_italic_tb.clicked.connect(self.on_italic_button)
  6679. self.ui.font_under_tb.clicked.connect(self.on_underline_button)
  6680. self.ui.font_color_entry.editingFinished.connect(self.on_font_color_entry)
  6681. self.ui.font_color_button.clicked.connect(self.on_font_color_button)
  6682. self.ui.sel_color_entry.editingFinished.connect(self.on_selection_color_entry)
  6683. self.ui.sel_color_button.clicked.connect(self.on_selection_color_button)
  6684. self.ui.al_left_tb.clicked.connect(lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignLeft))
  6685. self.ui.al_center_tb.clicked.connect(lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignCenter))
  6686. self.ui.al_right_tb.clicked.connect(lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignRight))
  6687. self.ui.al_justify_tb.clicked.connect(
  6688. lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignJustify)
  6689. )
  6690. self.ui.autocomplete_cb.stateChanged.connect(self.on_autocomplete_changed)
  6691. self.ui.tab_size_spinner.returnPressed.connect(self.on_tab_size_change)
  6692. # #######################################################################
  6693. self.ui.font_color_entry.set_value(self.app.defaults['document_font_color'])
  6694. self.ui.font_color_button.setStyleSheet(
  6695. "background-color:%s" % str(self.app.defaults['document_font_color']))
  6696. self.ui.sel_color_entry.set_value(self.app.defaults['document_sel_color'])
  6697. self.ui.sel_color_button.setStyleSheet(
  6698. "background-color:%s" % self.app.defaults['document_sel_color'])
  6699. self.ui.font_size_cb.setCurrentIndex(int(self.app.defaults['document_font_size']))
  6700. self.document_editor_tab.handleTextChanged()
  6701. self.ser_attrs = ['options', 'kind', 'source_file']
  6702. if Qt.mightBeRichText(self.source_file):
  6703. self.document_editor_tab.code_editor.setHtml(self.source_file)
  6704. else:
  6705. for line in self.source_file.splitlines():
  6706. self.document_editor_tab.code_editor.append(line)
  6707. self.build_ui()
  6708. @property
  6709. def read_only(self):
  6710. return self._read_only
  6711. @read_only.setter
  6712. def read_only(self, val):
  6713. if val:
  6714. self._read_only = True
  6715. else:
  6716. self._read_only = False
  6717. def build_ui(self):
  6718. FlatCAMObj.build_ui(self)
  6719. tab_here = False
  6720. # try to not add too many times a tab that it is already installed
  6721. for idx in range(self.app.ui.plot_tab_area.count()):
  6722. if self.app.ui.plot_tab_area.widget(idx).objectName() == self.options['name']:
  6723. tab_here = True
  6724. break
  6725. # add the tab if it is not already added
  6726. if tab_here is False:
  6727. self.app.ui.plot_tab_area.addTab(self.document_editor_tab, '%s' % _("Document Editor"))
  6728. self.document_editor_tab.setObjectName(self.options['name'])
  6729. # Switch plot_area to CNCJob tab
  6730. self.app.ui.plot_tab_area.setCurrentWidget(self.document_editor_tab)
  6731. def on_autocomplete_changed(self, state):
  6732. if state:
  6733. self.document_editor_tab.code_editor.completer_enable = True
  6734. else:
  6735. self.document_editor_tab.code_editor.completer_enable = False
  6736. def on_tab_size_change(self, val=None):
  6737. try:
  6738. self.ui.tab_size_spinner.returnPressed.disconnect(self.on_tab_size_change)
  6739. except TypeError:
  6740. pass
  6741. if val:
  6742. self.ui.tab_size_spinner.set_value(val)
  6743. tab_balue = int(self.ui.tab_size_spinner.get_value())
  6744. self.document_editor_tab.code_editor.setTabStopWidth(tab_balue)
  6745. self.app.defaults['document_tab_size'] = tab_balue
  6746. self.ui.tab_size_spinner.returnPressed.connect(self.on_tab_size_change)
  6747. def on_text_changed(self):
  6748. self.source_file = self.document_editor_tab.code_editor.toHtml()
  6749. # print(self.source_file)
  6750. def font_family(self, font):
  6751. # self.document_editor_tab.code_editor.selectAll()
  6752. font.setPointSize(float(self.ui.font_size_cb.get_value()))
  6753. self.document_editor_tab.code_editor.setCurrentFont(font)
  6754. self.font_name = self.ui.font_type_cb.currentFont().family()
  6755. def font_size(self):
  6756. # self.document_editor_tab.code_editor.selectAll()
  6757. self.document_editor_tab.code_editor.setFontPointSize(float(self.ui.font_size_cb.get_value()))
  6758. def on_bold_button(self):
  6759. if self.ui.font_bold_tb.isChecked():
  6760. self.document_editor_tab.code_editor.setFontWeight(QtGui.QFont.Bold)
  6761. self.font_bold = True
  6762. else:
  6763. self.document_editor_tab.code_editor.setFontWeight(QtGui.QFont.Normal)
  6764. self.font_bold = False
  6765. def on_italic_button(self):
  6766. if self.ui.font_italic_tb.isChecked():
  6767. self.document_editor_tab.code_editor.setFontItalic(True)
  6768. self.font_italic = True
  6769. else:
  6770. self.document_editor_tab.code_editor.setFontItalic(False)
  6771. self.font_italic = False
  6772. def on_underline_button(self):
  6773. if self.ui.font_under_tb.isChecked():
  6774. self.document_editor_tab.code_editor.setFontUnderline(True)
  6775. self.font_underline = True
  6776. else:
  6777. self.document_editor_tab.code_editor.setFontUnderline(False)
  6778. self.font_underline = False
  6779. # Setting font colors handlers
  6780. def on_font_color_entry(self):
  6781. self.app.defaults['document_font_color'] = self.ui.font_color_entry.get_value()
  6782. self.ui.font_color_button.setStyleSheet("background-color:%s" % str(self.app.defaults['document_font_color']))
  6783. def on_font_color_button(self):
  6784. current_color = QtGui.QColor(self.app.defaults['document_font_color'])
  6785. c_dialog = QtWidgets.QColorDialog()
  6786. font_color = c_dialog.getColor(initial=current_color)
  6787. if font_color.isValid() is False:
  6788. return
  6789. self.document_editor_tab.code_editor.setTextColor(font_color)
  6790. self.ui.font_color_button.setStyleSheet("background-color:%s" % str(font_color.name()))
  6791. new_val = str(font_color.name())
  6792. self.ui.font_color_entry.set_value(new_val)
  6793. self.app.defaults['document_font_color'] = new_val
  6794. # Setting selection colors handlers
  6795. def on_selection_color_entry(self):
  6796. self.app.defaults['document_sel_color'] = self.ui.sel_color_entry.get_value()
  6797. self.ui.sel_color_button.setStyleSheet("background-color:%s" % str(self.app.defaults['document_sel_color']))
  6798. def on_selection_color_button(self):
  6799. current_color = QtGui.QColor(self.app.defaults['document_sel_color'])
  6800. c_dialog = QtWidgets.QColorDialog()
  6801. sel_color = c_dialog.getColor(initial=current_color)
  6802. if sel_color.isValid() is False:
  6803. return
  6804. p = QtGui.QPalette()
  6805. p.setColor(QtGui.QPalette.Highlight, sel_color)
  6806. p.setColor(QtGui.QPalette.HighlightedText, QtGui.QColor('white'))
  6807. self.document_editor_tab.code_editor.setPalette(p)
  6808. self.ui.sel_color_button.setStyleSheet("background-color:%s" % str(sel_color.name()))
  6809. new_val = str(sel_color.name())
  6810. self.ui.sel_color_entry.set_value(new_val)
  6811. self.app.defaults['document_sel_color'] = new_val
  6812. def to_dict(self):
  6813. """
  6814. Returns a representation of the object as a dictionary.
  6815. Attributes to include are listed in ``self.ser_attrs``.
  6816. :return: A dictionary-encoded copy of the object.
  6817. :rtype: dict
  6818. """
  6819. d = {}
  6820. for attr in self.ser_attrs:
  6821. d[attr] = getattr(self, attr)
  6822. return d
  6823. def from_dict(self, d):
  6824. """
  6825. Sets object's attributes from a dictionary.
  6826. Attributes to include are listed in ``self.ser_attrs``.
  6827. This method will look only for only and all the
  6828. attributes in ``self.ser_attrs``. They must all
  6829. be present. Use only for deserializing saved
  6830. objects.
  6831. :param d: Dictionary of attributes to set in the object.
  6832. :type d: dict
  6833. :return: None
  6834. """
  6835. for attr in self.ser_attrs:
  6836. setattr(self, attr, d[attr])
  6837. # end of file