FlatCAMObj.py 300 KB

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