FlatCAMObj.py 328 KB

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