FlatCAMObj.py 236 KB

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