FlatCAMObj.py 239 KB

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