FlatCAMObj.py 239 KB

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