FlatCAMObj.py 239 KB

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