FlatCAMObj.py 232 KB

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