FlatCAMObj.py 231 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543
  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. # Attributes to be included in serialization
  1086. # Always append to it because it carries contents
  1087. # from predecessors.
  1088. self.ser_attrs += ['options', 'kind']
  1089. @staticmethod
  1090. def merge(exc_list, exc_final):
  1091. """
  1092. Merge Excellon objects found in exc_list parameter into exc_final object.
  1093. Options are always copied from source .
  1094. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  1095. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  1096. tool_name to be used in the final Excellon object, exc_final.
  1097. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  1098. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  1099. :param exc_final: Destination FlatCAMExcellon object.
  1100. :return: None
  1101. """
  1102. # flag to signal that we need to reorder the tools dictionary and drills and slots lists
  1103. flag_order = False
  1104. try:
  1105. flattened_list = list(itertools.chain(*exc_list))
  1106. except TypeError:
  1107. flattened_list = exc_list
  1108. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  1109. # values will be list of Shapely Points; for drills
  1110. custom_dict_drills = {}
  1111. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  1112. # values will be list of Shapely Points; for slots
  1113. custom_dict_slots = {}
  1114. for exc in flattened_list:
  1115. # copy options of the current excellon obj to the final excellon obj
  1116. for option in exc.options:
  1117. if option is not 'name':
  1118. try:
  1119. exc_final.options[option] = exc.options[option]
  1120. except:
  1121. exc.app.log.warning("Failed to copy option.", option)
  1122. for drill in exc.drills:
  1123. exc_tool_dia = float('%.3f' % exc.tools[drill['tool']]['C'])
  1124. if exc_tool_dia not in custom_dict_drills:
  1125. custom_dict_drills[exc_tool_dia] = [drill['point']]
  1126. else:
  1127. custom_dict_drills[exc_tool_dia].append(drill['point'])
  1128. for slot in exc.slots:
  1129. exc_tool_dia = float('%.3f' % exc.tools[slot['tool']]['C'])
  1130. if exc_tool_dia not in custom_dict_slots:
  1131. custom_dict_slots[exc_tool_dia] = [[slot['start'], slot['stop']]]
  1132. else:
  1133. custom_dict_slots[exc_tool_dia].append([slot['start'], slot['stop']])
  1134. # add the zeros and units to the exc_final object
  1135. exc_final.zeros = exc.zeros
  1136. exc_final.units = exc.units
  1137. # variable to make tool_name for the tools
  1138. current_tool = 0
  1139. # Here we add data to the exc_final object
  1140. # the tools diameter are now the keys in the drill_dia dict and the values are the Shapely Points in case of
  1141. # drills
  1142. for tool_dia in custom_dict_drills:
  1143. # we create a tool name for each key in the drill_dia dict (the key is a unique drill diameter)
  1144. current_tool += 1
  1145. tool_name = str(current_tool)
  1146. spec = {"C": float(tool_dia)}
  1147. exc_final.tools[tool_name] = spec
  1148. # rebuild the drills list of dict's that belong to the exc_final object
  1149. for point in custom_dict_drills[tool_dia]:
  1150. exc_final.drills.append(
  1151. {
  1152. "point": point,
  1153. "tool": str(current_tool)
  1154. }
  1155. )
  1156. # Here we add data to the exc_final object
  1157. # the tools diameter are now the keys in the drill_dia dict and the values are a list ([start, stop])
  1158. # of two Shapely Points in case of slots
  1159. for tool_dia in custom_dict_slots:
  1160. # we create a tool name for each key in the slot_dia dict (the key is a unique slot diameter)
  1161. # but only if there are no drills
  1162. if not exc_final.tools:
  1163. current_tool += 1
  1164. tool_name = str(current_tool)
  1165. spec = {"C": float(tool_dia)}
  1166. exc_final.tools[tool_name] = spec
  1167. else:
  1168. dia_list = []
  1169. for v in exc_final.tools.values():
  1170. dia_list.append(float(v["C"]))
  1171. if tool_dia not in dia_list:
  1172. flag_order = True
  1173. current_tool = len(dia_list) + 1
  1174. tool_name = str(current_tool)
  1175. spec = {"C": float(tool_dia)}
  1176. exc_final.tools[tool_name] = spec
  1177. else:
  1178. for k, v in exc_final.tools.items():
  1179. if v["C"] == tool_dia:
  1180. current_tool = int(k)
  1181. break
  1182. # rebuild the slots list of dict's that belong to the exc_final object
  1183. for point in custom_dict_slots[tool_dia]:
  1184. exc_final.slots.append(
  1185. {
  1186. "start": point[0],
  1187. "stop": point[1],
  1188. "tool": str(current_tool)
  1189. }
  1190. )
  1191. # flag_order == True means that there was an slot diameter not in the tools and we also have drills
  1192. # and the new tool was added to self.tools therefore we need to reorder the tools and drills and slots
  1193. current_tool = 0
  1194. if flag_order is True:
  1195. dia_list = []
  1196. temp_drills = []
  1197. temp_slots = []
  1198. temp_tools = {}
  1199. for v in exc_final.tools.values():
  1200. dia_list.append(float(v["C"]))
  1201. dia_list.sort()
  1202. for ordered_dia in dia_list:
  1203. current_tool += 1
  1204. tool_name_temp = str(current_tool)
  1205. spec_temp = {"C": float(ordered_dia)}
  1206. temp_tools[tool_name_temp] = spec_temp
  1207. for drill in exc_final.drills:
  1208. exc_tool_dia = float('%.3f' % exc_final.tools[drill['tool']]['C'])
  1209. if exc_tool_dia == ordered_dia:
  1210. temp_drills.append(
  1211. {
  1212. "point": drill["point"],
  1213. "tool": str(current_tool)
  1214. }
  1215. )
  1216. for slot in exc_final.slots:
  1217. slot_tool_dia = float('%.3f' % exc_final.tools[slot['tool']]['C'])
  1218. if slot_tool_dia == ordered_dia:
  1219. temp_slots.append(
  1220. {
  1221. "start": slot["start"],
  1222. "stop": slot["stop"],
  1223. "tool": str(current_tool)
  1224. }
  1225. )
  1226. # delete the exc_final tools, drills and slots
  1227. exc_final.tools = dict()
  1228. exc_final.drills[:] = []
  1229. exc_final.slots[:] = []
  1230. # update the exc_final tools, drills and slots with the ordered values
  1231. exc_final.tools = temp_tools
  1232. exc_final.drills[:] = temp_drills
  1233. exc_final.slots[:] = temp_slots
  1234. # create the geometry for the exc_final object
  1235. exc_final.create_geometry()
  1236. def build_ui(self):
  1237. FlatCAMObj.build_ui(self)
  1238. try:
  1239. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1240. self.ui.tools_table.itemChanged.disconnect()
  1241. except:
  1242. pass
  1243. n = len(self.tools)
  1244. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  1245. self.ui.tools_table.setRowCount(n + 2)
  1246. self.tot_drill_cnt = 0
  1247. self.tot_slot_cnt = 0
  1248. self.tool_row = 0
  1249. sort = []
  1250. for k, v in list(self.tools.items()):
  1251. sort.append((k, v.get('C')))
  1252. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1253. tools = [i[0] for i in sorted_tools]
  1254. for tool_no in tools:
  1255. drill_cnt = 0 # variable to store the nr of drills per tool
  1256. slot_cnt = 0 # variable to store the nr of slots per tool
  1257. # Find no of drills for the current tool
  1258. for drill in self.drills:
  1259. if drill['tool'] == tool_no:
  1260. drill_cnt += 1
  1261. self.tot_drill_cnt += drill_cnt
  1262. # Find no of slots for the current tool
  1263. for slot in self.slots:
  1264. if slot['tool'] == tool_no:
  1265. slot_cnt += 1
  1266. self.tot_slot_cnt += slot_cnt
  1267. id = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  1268. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1269. self.ui.tools_table.setItem(self.tool_row, 0, id) # Tool name/id
  1270. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  1271. # There are no drill bits in MM with more than 3 decimals diameter
  1272. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  1273. if self.units == 'MM':
  1274. dia = QtWidgets.QTableWidgetItem('%.2f' % (self.tools[tool_no]['C']))
  1275. else:
  1276. dia = QtWidgets.QTableWidgetItem('%.3f' % (self.tools[tool_no]['C']))
  1277. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  1278. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  1279. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1280. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  1281. if slot_cnt > 0:
  1282. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  1283. else:
  1284. slot_count = QtWidgets.QTableWidgetItem('')
  1285. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1286. try:
  1287. if self.units == 'MM':
  1288. t_offset = self.tool_offset[float('%.2f' % float(self.tools[tool_no]['C']))]
  1289. else:
  1290. t_offset = self.tool_offset[float('%.3f' % float(self.tools[tool_no]['C']))]
  1291. except KeyError:
  1292. t_offset = self.app.defaults['excellon_offset']
  1293. tool_offset_item = QtWidgets.QTableWidgetItem('%s' % str(t_offset))
  1294. plot_item = FCCheckBox()
  1295. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  1296. if self.ui.plot_cb.isChecked():
  1297. plot_item.setChecked(True)
  1298. self.ui.tools_table.setItem(self.tool_row, 1, dia) # Diameter
  1299. self.ui.tools_table.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  1300. self.ui.tools_table.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  1301. self.ui.tools_table.setItem(self.tool_row, 4, tool_offset_item) # Tool offset
  1302. self.ui.tools_table.setCellWidget(self.tool_row, 5, plot_item)
  1303. self.tool_row += 1
  1304. # add a last row with the Total number of drills
  1305. empty = QtWidgets.QTableWidgetItem('')
  1306. empty.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1307. empty_1 = QtWidgets.QTableWidgetItem('')
  1308. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1309. label_tot_drill_count = QtWidgets.QTableWidgetItem('Total Drills')
  1310. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  1311. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1312. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1313. self.ui.tools_table.setItem(self.tool_row, 0, empty)
  1314. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  1315. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  1316. self.ui.tools_table.setItem(self.tool_row, 3, empty_1) # Total number of drills
  1317. font = QtGui.QFont()
  1318. font.setBold(True)
  1319. font.setWeight(75)
  1320. for k in [1, 2]:
  1321. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  1322. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  1323. self.tool_row += 1
  1324. # add a last row with the Total number of slots
  1325. empty_2 = QtWidgets.QTableWidgetItem('')
  1326. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1327. empty_3 = QtWidgets.QTableWidgetItem('')
  1328. empty_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1329. label_tot_slot_count = QtWidgets.QTableWidgetItem('Total Slots')
  1330. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  1331. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1332. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1333. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  1334. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  1335. self.ui.tools_table.setItem(self.tool_row, 2, empty_3)
  1336. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  1337. for kl in [1, 2, 3]:
  1338. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  1339. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  1340. # sort the tool diameter column
  1341. # self.ui.tools_table.sortItems(1)
  1342. # all the tools are selected by default
  1343. self.ui.tools_table.selectColumn(0)
  1344. #
  1345. self.ui.tools_table.resizeColumnsToContents()
  1346. self.ui.tools_table.resizeRowsToContents()
  1347. vertical_header = self.ui.tools_table.verticalHeader()
  1348. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1349. vertical_header.hide()
  1350. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1351. horizontal_header = self.ui.tools_table.horizontalHeader()
  1352. horizontal_header.setMinimumSectionSize(10)
  1353. horizontal_header.setDefaultSectionSize(70)
  1354. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  1355. horizontal_header.resizeSection(0, 20)
  1356. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1357. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1358. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1359. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
  1360. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  1361. horizontal_header.resizeSection(5, 17)
  1362. self.ui.tools_table.setColumnWidth(5, 17)
  1363. # horizontal_header.setStretchLastSection(True)
  1364. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  1365. # horizontal_header.setStretchLastSection(True)
  1366. self.ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1367. self.ui.tools_table.setSortingEnabled(False)
  1368. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  1369. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  1370. if not self.drills:
  1371. self.ui.tdlabel.hide()
  1372. self.ui.tooldia_entry.hide()
  1373. self.ui.generate_milling_button.hide()
  1374. else:
  1375. self.ui.tdlabel.show()
  1376. self.ui.tooldia_entry.show()
  1377. self.ui.generate_milling_button.show()
  1378. if not self.slots:
  1379. self.ui.stdlabel.hide()
  1380. self.ui.slot_tooldia_entry.hide()
  1381. self.ui.generate_milling_slots_button.hide()
  1382. else:
  1383. self.ui.stdlabel.show()
  1384. self.ui.slot_tooldia_entry.show()
  1385. self.ui.generate_milling_slots_button.show()
  1386. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1387. self.ui.tools_table.itemChanged.connect(self.on_tool_offset_edit)
  1388. self.ui_connect()
  1389. def set_ui(self, ui):
  1390. """
  1391. Configures the user interface for this object.
  1392. Connects options to form fields.
  1393. :param ui: User interface object.
  1394. :type ui: ExcellonObjectUI
  1395. :return: None
  1396. """
  1397. FlatCAMObj.set_ui(self, ui)
  1398. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  1399. self.form_fields.update({
  1400. "plot": self.ui.plot_cb,
  1401. "solid": self.ui.solid_cb,
  1402. "drillz": self.ui.cutz_entry,
  1403. "travelz": self.ui.travelz_entry,
  1404. "feedrate": self.ui.feedrate_entry,
  1405. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  1406. "tooldia": self.ui.tooldia_entry,
  1407. "slot_tooldia": self.ui.slot_tooldia_entry,
  1408. "toolchange": self.ui.toolchange_cb,
  1409. "toolchangez": self.ui.toolchangez_entry,
  1410. "spindlespeed": self.ui.spindlespeed_entry,
  1411. "dwell": self.ui.dwell_cb,
  1412. "dwelltime": self.ui.dwelltime_entry,
  1413. "startz": self.ui.estartz_entry,
  1414. "endz": self.ui.eendz_entry,
  1415. "ppname_e": self.ui.pp_excellon_name_cb,
  1416. "z_pdepth": self.ui.pdepth_entry,
  1417. "feedrate_probe": self.ui.feedrate_probe_entry,
  1418. "gcode_type": self.ui.excellon_gcode_type_radio
  1419. })
  1420. for name in list(self.app.postprocessors.keys()):
  1421. # the HPGL postprocessor is only for Geometry not for Excellon job therefore don't add it
  1422. if name == 'hpgl':
  1423. continue
  1424. self.ui.pp_excellon_name_cb.addItem(name)
  1425. # Fill form fields
  1426. self.to_form()
  1427. # initialize the dict that holds the tools offset
  1428. t_default_offset = self.app.defaults["excellon_offset"]
  1429. if not self.tool_offset:
  1430. for value in self.tools.values():
  1431. if self.units == 'MM':
  1432. dia = float('%.2f' % float(value['C']))
  1433. else:
  1434. dia = float('%.3f' % float(value['C']))
  1435. self.tool_offset[dia] = t_default_offset
  1436. # Show/Hide Advanced Options
  1437. if self.app.defaults["global_app_level"] == 'b':
  1438. self.ui.level.setText('<span style="color:green;"><b>Basic</b></span>')
  1439. self.ui.tools_table.setColumnHidden(4, True)
  1440. self.ui.estartz_label.hide()
  1441. self.ui.estartz_entry.hide()
  1442. self.ui.eendz_label.hide()
  1443. self.ui.eendz_entry.hide()
  1444. self.ui.feedrate_rapid_label.hide()
  1445. self.ui.feedrate_rapid_entry.hide()
  1446. self.ui.pdepth_label.hide()
  1447. self.ui.pdepth_entry.hide()
  1448. self.ui.feedrate_probe_label.hide()
  1449. self.ui.feedrate_probe_entry.hide()
  1450. else:
  1451. self.ui.level.setText('<span style="color:red;"><b>Advanced</b></span>')
  1452. assert isinstance(self.ui, ExcellonObjectUI), \
  1453. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  1454. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1455. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  1456. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  1457. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  1458. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  1459. self.ui.pp_excellon_name_cb.activated.connect(self.on_pp_changed)
  1460. def ui_connect(self):
  1461. for row in range(self.ui.tools_table.rowCount() - 2):
  1462. self.ui.tools_table.cellWidget(row, 5).clicked.connect(self.on_plot_cb_click_table)
  1463. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1464. def ui_disconnect(self):
  1465. for row in range(self.ui.tools_table.rowCount()):
  1466. try:
  1467. self.ui.tools_table.cellWidget(row, 5).clicked.disconnect()
  1468. except:
  1469. pass
  1470. try:
  1471. self.ui.plot_cb.stateChanged.disconnect()
  1472. except:
  1473. pass
  1474. def on_tool_offset_edit(self):
  1475. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1476. self.ui.tools_table.itemChanged.disconnect()
  1477. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  1478. self.is_modified = True
  1479. row_of_item_changed = self.ui.tools_table.currentRow()
  1480. if self.units == 'MM':
  1481. dia = float('%.2f' % float(self.ui.tools_table.item(row_of_item_changed, 1).text()))
  1482. else:
  1483. dia = float('%.3f' % float(self.ui.tools_table.item(row_of_item_changed, 1).text()))
  1484. current_table_offset_edited = None
  1485. if self.ui.tools_table.currentItem() is not None:
  1486. try:
  1487. current_table_offset_edited = float(self.ui.tools_table.currentItem().text())
  1488. except ValueError:
  1489. # try to convert comma to decimal point. if it's still not working error message and return
  1490. try:
  1491. current_table_offset_edited = float(self.ui.tools_table.currentItem().text().replace(',', '.'))
  1492. self.ui.tools_table.currentItem().setText(
  1493. self.ui.tools_table.currentItem().text().replace(',', '.'))
  1494. except ValueError:
  1495. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  1496. "use a number.")
  1497. self.ui.tools_table.currentItem().setText(str(self.tool_offset[dia]))
  1498. return
  1499. self.tool_offset[dia] = current_table_offset_edited
  1500. # we reactivate the signals after the after the tool editing
  1501. self.ui.tools_table.itemChanged.connect(self.on_tool_offset_edit)
  1502. def get_selected_tools_list(self):
  1503. """
  1504. Returns the keys to the self.tools dictionary corresponding
  1505. to the selections on the tool list in the GUI.
  1506. :return: List of tools.
  1507. :rtype: list
  1508. """
  1509. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  1510. def get_selected_tools_table_items(self):
  1511. """
  1512. Returns a list of lists, each list in the list is made out of row elements
  1513. :return: List of table_tools items.
  1514. :rtype: list
  1515. """
  1516. table_tools_items = []
  1517. for x in self.ui.tools_table.selectedItems():
  1518. # from the columnCount we subtract a value of 1 which represent the last column (plot column)
  1519. # which does not have text
  1520. table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  1521. for column in range(0, self.ui.tools_table.columnCount() - 1)])
  1522. for item in table_tools_items:
  1523. item[0] = str(item[0])
  1524. return table_tools_items
  1525. def export_excellon(self, whole, fract, e_zeros=None, form='dec', factor=1):
  1526. """
  1527. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  1528. :return: has_slots and Excellon_code
  1529. """
  1530. excellon_code = ''
  1531. # store here if the file has slots, return 1 if any slots, 0 if only drills
  1532. has_slots = 0
  1533. # drills processing
  1534. try:
  1535. if self.drills:
  1536. length = whole + fract
  1537. for tool in self.tools:
  1538. excellon_code += 'T0%s\n' % str(tool) if int(tool) < 10 else 'T%s\n' % str(tool)
  1539. for drill in self.drills:
  1540. if form == 'dec' and tool == drill['tool']:
  1541. drill_x = drill['point'].x * factor
  1542. drill_y = drill['point'].y * factor
  1543. excellon_code += "X{:.{dec}f}Y{:.{dec}f}\n".format(drill_x, drill_y, dec=fract)
  1544. elif e_zeros == 'LZ' and tool == drill['tool']:
  1545. drill_x = drill['point'].x * factor
  1546. drill_y = drill['point'].y * factor
  1547. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract)
  1548. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract)
  1549. # extract whole part and decimal part
  1550. exc_x_formatted = exc_x_formatted.partition('.')
  1551. exc_y_formatted = exc_y_formatted.partition('.')
  1552. # left padd the 'whole' part with zeros
  1553. x_whole = exc_x_formatted[0].rjust(whole, '0')
  1554. y_whole = exc_y_formatted[0].rjust(whole, '0')
  1555. # restore the coordinate padded in the left with 0 and added the decimal part
  1556. # without the decinal dot
  1557. exc_x_formatted = x_whole + exc_x_formatted[2]
  1558. exc_y_formatted = y_whole + exc_y_formatted[2]
  1559. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  1560. yform=exc_y_formatted)
  1561. elif tool == drill['tool']:
  1562. drill_x = drill['point'].x * factor
  1563. drill_y = drill['point'].y * factor
  1564. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract).replace('.', '')
  1565. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract).replace('.', '')
  1566. # pad with rear zeros
  1567. exc_x_formatted.ljust(length, '0')
  1568. exc_y_formatted.ljust(length, '0')
  1569. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  1570. yform=exc_y_formatted)
  1571. except Exception as e:
  1572. log.debug(str(e))
  1573. # slots processing
  1574. try:
  1575. if self.slots:
  1576. has_slots = 1
  1577. for tool in self.tools:
  1578. if int(tool) < 10:
  1579. excellon_code += 'T0' + str(tool) + '\n'
  1580. else:
  1581. excellon_code += 'T' + str(tool) + '\n'
  1582. for slot in self.slots:
  1583. if form == 'dec' and tool == slot['tool']:
  1584. start_slot_x = slot['start'].x * factor
  1585. start_slot_y = slot['start'].y * factor
  1586. stop_slot_x = slot['stop'].x * factor
  1587. stop_slot_y = slot['stop'].y * factor
  1588. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM15\n".format(start_slot_x,
  1589. start_slot_y,
  1590. dec=fract)
  1591. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM16\n".format(stop_slot_x,
  1592. stop_slot_y,
  1593. dec=fract)
  1594. elif e_zeros == 'LZ' and tool == slot['tool']:
  1595. start_slot_x = slot['start'].x * factor
  1596. start_slot_y = slot['start'].y * factor
  1597. stop_slot_x = slot['stop'].x * factor
  1598. stop_slot_y = slot['stop'].y * factor
  1599. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  1600. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  1601. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  1602. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  1603. # extract whole part and decimal part
  1604. start_slot_x_formatted = start_slot_x_formatted.partition('.')
  1605. start_slot_y_formatted = start_slot_y_formatted.partition('.')
  1606. stop_slot_x_formatted = stop_slot_x_formatted.partition('.')
  1607. stop_slot_y_formatted = stop_slot_y_formatted.partition('.')
  1608. # left padd the 'whole' part with zeros
  1609. start_x_whole = start_slot_x_formatted[0].rjust(whole, '0')
  1610. start_y_whole = start_slot_y_formatted[0].rjust(whole, '0')
  1611. stop_x_whole = stop_slot_x_formatted[0].rjust(whole, '0')
  1612. stop_y_whole = stop_slot_y_formatted[0].rjust(whole, '0')
  1613. # restore the coordinate padded in the left with 0 and added the decimal part
  1614. # without the decinal dot
  1615. start_slot_x_formatted = start_x_whole + start_slot_x_formatted[2]
  1616. start_slot_y_formatted = start_y_whole + start_slot_y_formatted[2]
  1617. stop_slot_x_formatted = stop_x_whole + stop_slot_x_formatted[2]
  1618. stop_slot_y_formatted = stop_y_whole + stop_slot_y_formatted[2]
  1619. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  1620. ystart=start_slot_y_formatted)
  1621. excellon_code += "G00X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  1622. ystop=stop_slot_y_formatted)
  1623. elif tool == slot['tool']:
  1624. start_slot_x = slot['start'].x * factor
  1625. start_slot_y = slot['start'].y * factor
  1626. stop_slot_x = slot['stop'].x * factor
  1627. stop_slot_y = slot['stop'].y * factor
  1628. length = whole + fract
  1629. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  1630. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  1631. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  1632. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  1633. # pad with rear zeros
  1634. start_slot_x_formatted.ljust(length, '0')
  1635. start_slot_y_formatted.ljust(length, '0')
  1636. stop_slot_x_formatted.ljust(length, '0')
  1637. stop_slot_y_formatted.ljust(length, '0')
  1638. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  1639. ystart=start_slot_y_formatted)
  1640. excellon_code += "G00X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  1641. ystop=stop_slot_y_formatted)
  1642. except Exception as e:
  1643. log.debug(str(e))
  1644. if not self.drills and not self.slots:
  1645. log.debug("FlatCAMObj.FlatCAMExcellon.export_excellon() --> Excellon Object is empty: no drills, no slots.")
  1646. return 'fail'
  1647. return has_slots, excellon_code
  1648. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1649. """
  1650. Note: This method is a good template for generic operations as
  1651. it takes it's options from parameters or otherwise from the
  1652. object's options and returns a (success, msg) tuple as feedback
  1653. for shell operations.
  1654. :return: Success/failure condition tuple (bool, str).
  1655. :rtype: tuple
  1656. """
  1657. # Get the tools from the list. These are keys
  1658. # to self.tools
  1659. if tools is None:
  1660. tools = self.get_selected_tools_list()
  1661. if outname is None:
  1662. outname = self.options["name"] + "_mill"
  1663. if tooldia is None:
  1664. tooldia = float(self.options["tooldia"])
  1665. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1666. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1667. sort = []
  1668. for k, v in self.tools.items():
  1669. sort.append((k, v.get('C')))
  1670. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1671. if tools == "all":
  1672. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1673. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1674. if len(tools) == 0:
  1675. self.app.inform.emit("[ERROR_NOTCL]Please select one or more tools from the list and try again.")
  1676. return False, "Error: No tools."
  1677. for tool in tools:
  1678. if tooldia > self.tools[tool]["C"]:
  1679. self.app.inform.emit("[ERROR_NOTCL] Milling tool for DRILLS is larger than hole size. Cancelled.")
  1680. return False, "Error: Milling tool is larger than hole."
  1681. def geo_init(geo_obj, app_obj):
  1682. assert isinstance(geo_obj, FlatCAMGeometry), \
  1683. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1684. app_obj.progress.emit(20)
  1685. ### Add properties to the object
  1686. # get the tool_table items in a list of row items
  1687. tool_table_items = self.get_selected_tools_table_items()
  1688. # insert an information only element in the front
  1689. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1690. geo_obj.options['Tools_in_use'] = tool_table_items
  1691. geo_obj.options['type'] = 'Excellon Geometry'
  1692. geo_obj.solid_geometry = []
  1693. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1694. # for FlatCAM is 6 decimals,
  1695. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1696. for hole in self.drills:
  1697. if hole['tool'] in tools:
  1698. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  1699. if buffer_value == 0:
  1700. geo_obj.solid_geometry.append(
  1701. Point(hole['point']).buffer(0.0000001).exterior)
  1702. else:
  1703. geo_obj.solid_geometry.append(
  1704. Point(hole['point']).buffer(buffer_value).exterior)
  1705. if use_thread:
  1706. def geo_thread(app_obj):
  1707. app_obj.new_object("geometry", outname, geo_init)
  1708. app_obj.progress.emit(100)
  1709. # Create a promise with the new name
  1710. self.app.collection.promise(outname)
  1711. # Send to worker
  1712. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1713. else:
  1714. self.app.new_object("geometry", outname, geo_init)
  1715. return True, ""
  1716. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1717. """
  1718. Note: This method is a good template for generic operations as
  1719. it takes it's options from parameters or otherwise from the
  1720. object's options and returns a (success, msg) tuple as feedback
  1721. for shell operations.
  1722. :return: Success/failure condition tuple (bool, str).
  1723. :rtype: tuple
  1724. """
  1725. # Get the tools from the list. These are keys
  1726. # to self.tools
  1727. if tools is None:
  1728. tools = self.get_selected_tools_list()
  1729. if outname is None:
  1730. outname = self.options["name"] + "_mill"
  1731. if tooldia is None:
  1732. tooldia = float(self.options["slot_tooldia"])
  1733. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1734. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1735. sort = []
  1736. for k, v in self.tools.items():
  1737. sort.append((k, v.get('C')))
  1738. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1739. if tools == "all":
  1740. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1741. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1742. if len(tools) == 0:
  1743. self.app.inform.emit("[ERROR_NOTCL]Please select one or more tools from the list and try again.")
  1744. return False, "Error: No tools."
  1745. for tool in tools:
  1746. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  1747. adj_toolstable_tooldia = float('%.4f' % float(tooldia))
  1748. adj_file_tooldia = float('%.4f' % float(self.tools[tool]["C"]))
  1749. if adj_toolstable_tooldia > adj_file_tooldia + 0.0001:
  1750. self.app.inform.emit("[ERROR_NOTCL] Milling tool for SLOTS is larger than hole size. Cancelled.")
  1751. return False, "Error: Milling tool is larger than hole."
  1752. def geo_init(geo_obj, app_obj):
  1753. assert isinstance(geo_obj, FlatCAMGeometry), \
  1754. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1755. app_obj.progress.emit(20)
  1756. ### Add properties to the object
  1757. # get the tool_table items in a list of row items
  1758. tool_table_items = self.get_selected_tools_table_items()
  1759. # insert an information only element in the front
  1760. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1761. geo_obj.options['Tools_in_use'] = tool_table_items
  1762. geo_obj.options['type'] = 'Excellon Geometry'
  1763. geo_obj.solid_geometry = []
  1764. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1765. # for FlatCAM is 6 decimals,
  1766. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1767. for slot in self.slots:
  1768. if slot['tool'] in tools:
  1769. toolstable_tool = float('%.4f' % float(tooldia))
  1770. file_tool = float('%.4f' % float(self.tools[tool]["C"]))
  1771. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  1772. # for the file_tool (tooldia actually)
  1773. buffer_value = float(file_tool / 2) - float(toolstable_tool / 2) + 0.0001
  1774. if buffer_value == 0:
  1775. start = slot['start']
  1776. stop = slot['stop']
  1777. lines_string = LineString([start, stop])
  1778. poly = lines_string.buffer(0.0000001, int(self.geo_steps_per_circle)).exterior
  1779. geo_obj.solid_geometry.append(poly)
  1780. else:
  1781. start = slot['start']
  1782. stop = slot['stop']
  1783. lines_string = LineString([start, stop])
  1784. poly = lines_string.buffer(buffer_value, int(self.geo_steps_per_circle)).exterior
  1785. geo_obj.solid_geometry.append(poly)
  1786. if use_thread:
  1787. def geo_thread(app_obj):
  1788. app_obj.new_object("geometry", outname + '_slot', geo_init)
  1789. app_obj.progress.emit(100)
  1790. # Create a promise with the new name
  1791. self.app.collection.promise(outname)
  1792. # Send to worker
  1793. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1794. else:
  1795. self.app.new_object("geometry", outname + '_slot', geo_init)
  1796. return True, ""
  1797. def on_generate_milling_button_click(self, *args):
  1798. self.app.report_usage("excellon_on_create_milling_drills button")
  1799. self.read_form()
  1800. self.generate_milling_drills(use_thread=False)
  1801. def on_generate_milling_slots_button_click(self, *args):
  1802. self.app.report_usage("excellon_on_create_milling_slots_button")
  1803. self.read_form()
  1804. self.generate_milling_slots(use_thread=False)
  1805. def on_pp_changed(self):
  1806. current_pp = self.ui.pp_excellon_name_cb.get_value()
  1807. if "toolchange_probe" in current_pp.lower():
  1808. self.ui.pdepth_entry.setVisible(True)
  1809. self.ui.pdepth_label.show()
  1810. self.ui.feedrate_probe_entry.setVisible(True)
  1811. self.ui.feedrate_probe_label.show()
  1812. else:
  1813. self.ui.pdepth_entry.setVisible(False)
  1814. self.ui.pdepth_label.hide()
  1815. self.ui.feedrate_probe_entry.setVisible(False)
  1816. self.ui.feedrate_probe_label.hide()
  1817. def on_create_cncjob_button_click(self, *args):
  1818. self.app.report_usage("excellon_on_create_cncjob_button")
  1819. self.read_form()
  1820. # Get the tools from the list
  1821. tools = self.get_selected_tools_list()
  1822. if len(tools) == 0:
  1823. # if there is a single tool in the table (remember that the last 2 rows are for totals and do not count in
  1824. # tool number) it means that there are 3 rows (1 tool and 2 totals).
  1825. # in this case regardless of the selection status of that tool, use it.
  1826. if self.ui.tools_table.rowCount() == 3:
  1827. tools.append(self.ui.tools_table.item(0, 0).text())
  1828. else:
  1829. self.app.inform.emit("[ERROR_NOTCL]Please select one or more tools from the list and try again.")
  1830. return
  1831. xmin = self.options['xmin']
  1832. ymin = self.options['ymin']
  1833. xmax = self.options['xmax']
  1834. ymax = self.options['ymax']
  1835. job_name = self.options["name"] + "_cnc"
  1836. pp_excellon_name = self.options["ppname_e"]
  1837. # Object initialization function for app.new_object()
  1838. def job_init(job_obj, app_obj):
  1839. assert isinstance(job_obj, FlatCAMCNCjob), \
  1840. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  1841. # get the tool_table items in a list of row items
  1842. tool_table_items = self.get_selected_tools_table_items()
  1843. # insert an information only element in the front
  1844. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1845. ### Add properties to the object
  1846. job_obj.options['Tools_in_use'] = tool_table_items
  1847. job_obj.options['type'] = 'Excellon'
  1848. job_obj.options['ppname_e'] = pp_excellon_name
  1849. app_obj.progress.emit(20)
  1850. job_obj.z_cut = float(self.options["drillz"])
  1851. job_obj.tool_offset = self.tool_offset
  1852. job_obj.z_move = float(self.options["travelz"])
  1853. job_obj.feedrate = float(self.options["feedrate"])
  1854. job_obj.feedrate_rapid = float(self.options["feedrate_rapid"])
  1855. job_obj.spindlespeed = float(self.options["spindlespeed"]) if self.options["spindlespeed"] else None
  1856. job_obj.dwell = self.options["dwell"]
  1857. job_obj.dwelltime = float(self.options["dwelltime"])
  1858. job_obj.pp_excellon_name = pp_excellon_name
  1859. job_obj.toolchange_xy_type = "excellon"
  1860. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  1861. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  1862. job_obj.options['xmin'] = xmin
  1863. job_obj.options['ymin'] = ymin
  1864. job_obj.options['xmax'] = xmax
  1865. job_obj.options['ymax'] = ymax
  1866. try:
  1867. job_obj.z_pdepth = float(self.options["z_pdepth"])
  1868. except ValueError:
  1869. # try to convert comma to decimal point. if it's still not working error message and return
  1870. try:
  1871. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  1872. except ValueError:
  1873. self.app.inform.emit(
  1874. '[ERROR_NOTCL]Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]')
  1875. try:
  1876. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  1877. except ValueError:
  1878. # try to convert comma to decimal point. if it's still not working error message and return
  1879. try:
  1880. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  1881. except ValueError:
  1882. self.app.inform.emit(
  1883. '[ERROR_NOTCL]Wrong value format for self.defaults["feedrate_probe"] '
  1884. 'or self.options["feedrate_probe"]')
  1885. # There could be more than one drill size...
  1886. # job_obj.tooldia = # TODO: duplicate variable!
  1887. # job_obj.options["tooldia"] =
  1888. tools_csv = ','.join(tools)
  1889. ret_val = job_obj.generate_from_excellon_by_tool(self, tools_csv,
  1890. drillz=float(self.options['drillz']),
  1891. toolchange=float(self.options["toolchange"]),
  1892. toolchangexy=self.app.defaults["excellon_toolchangexy"],
  1893. toolchangez=float(self.options["toolchangez"]),
  1894. startz=float(self.options["startz"]) if
  1895. self.options["startz"] else None,
  1896. endz=float(self.options["endz"]),
  1897. excellon_optimization_type=self.app.defaults[
  1898. "excellon_optimization_type"])
  1899. if ret_val == 'fail':
  1900. return 'fail'
  1901. app_obj.progress.emit(50)
  1902. job_obj.gcode_parse()
  1903. app_obj.progress.emit(60)
  1904. job_obj.create_geometry()
  1905. app_obj.progress.emit(80)
  1906. # To be run in separate thread
  1907. def job_thread(app_obj):
  1908. with self.app.proc_container.new("Generating CNC Code"):
  1909. app_obj.new_object("cncjob", job_name, job_init)
  1910. app_obj.progress.emit(100)
  1911. # Create promise for the new name.
  1912. self.app.collection.promise(job_name)
  1913. # Send to worker
  1914. # self.app.worker.add_task(job_thread, [self.app])
  1915. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1916. def convert_units(self, units):
  1917. factor = Excellon.convert_units(self, units)
  1918. self.options['drillz'] = float(self.options['drillz']) * factor
  1919. self.options['travelz'] = float(self.options['travelz']) * factor
  1920. self.options['feedrate'] = float(self.options['feedrate']) * factor
  1921. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  1922. self.options['toolchangez'] = float(self.options['toolchangez']) * factor
  1923. if self.app.defaults["excellon_toolchangexy"] == '':
  1924. self.options['toolchangexy'] = "0.0, 0.0"
  1925. else:
  1926. coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  1927. if len(coords_xy) < 2:
  1928. self.app.inform.emit("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  1929. "in the format (x, y) \nbut now there is only one value, not two. ")
  1930. return 'fail'
  1931. coords_xy[0] *= factor
  1932. coords_xy[1] *= factor
  1933. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  1934. if self.options['startz'] is not None:
  1935. self.options['startz'] = float(self.options['startz']) * factor
  1936. self.options['endz'] = float(self.options['endz']) * factor
  1937. def on_solid_cb_click(self, *args):
  1938. if self.muted_ui:
  1939. return
  1940. self.read_form_item('solid')
  1941. self.plot()
  1942. def on_plot_cb_click(self, *args):
  1943. if self.muted_ui:
  1944. return
  1945. self.plot()
  1946. self.read_form_item('plot')
  1947. self.ui_disconnect()
  1948. cb_flag = self.ui.plot_cb.isChecked()
  1949. for row in range(self.ui.tools_table.rowCount() - 2):
  1950. table_cb = self.ui.tools_table.cellWidget(row, 5)
  1951. if cb_flag:
  1952. table_cb.setChecked(True)
  1953. else:
  1954. table_cb.setChecked(False)
  1955. self.ui_connect()
  1956. def on_plot_cb_click_table(self):
  1957. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  1958. self.ui_disconnect()
  1959. # cw = self.sender()
  1960. # cw_index = self.ui.tools_table.indexAt(cw.pos())
  1961. # cw_row = cw_index.row()
  1962. check_row = 0
  1963. self.shapes.clear(update=True)
  1964. for tool_key in self.tools:
  1965. solid_geometry = self.tools[tool_key]['solid_geometry']
  1966. # find the geo_tool_table row associated with the tool_key
  1967. for row in range(self.ui.tools_table.rowCount()):
  1968. tool_item = int(self.ui.tools_table.item(row, 0).text())
  1969. if tool_item == int(tool_key):
  1970. check_row = row
  1971. break
  1972. if self.ui.tools_table.cellWidget(check_row, 5).isChecked():
  1973. self.options['plot'] = True
  1974. # self.plot_element(element=solid_geometry, visible=True)
  1975. # Plot excellon (All polygons?)
  1976. if self.options["solid"]:
  1977. for geo in solid_geometry:
  1978. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  1979. visible=self.options['plot'],
  1980. layer=2)
  1981. else:
  1982. for geo in solid_geometry:
  1983. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1984. for ints in geo.interiors:
  1985. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1986. self.shapes.redraw()
  1987. # make sure that the general plot is disabled if one of the row plot's are disabled and
  1988. # if all the row plot's are enabled also enable the general plot checkbox
  1989. cb_cnt = 0
  1990. total_row = self.ui.tools_table.rowCount()
  1991. for row in range(total_row - 2):
  1992. if self.ui.tools_table.cellWidget(row, 5).isChecked():
  1993. cb_cnt += 1
  1994. else:
  1995. cb_cnt -= 1
  1996. if cb_cnt < total_row - 2:
  1997. self.ui.plot_cb.setChecked(False)
  1998. else:
  1999. self.ui.plot_cb.setChecked(True)
  2000. self.ui_connect()
  2001. # def plot_element(self, element, color='red', visible=None, layer=None):
  2002. #
  2003. # visible = visible if visible else self.options['plot']
  2004. #
  2005. # try:
  2006. # for sub_el in element:
  2007. # self.plot_element(sub_el)
  2008. #
  2009. # except TypeError: # Element is not iterable...
  2010. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  2011. def plot(self):
  2012. # Does all the required setup and returns False
  2013. # if the 'ptint' option is set to False.
  2014. if not FlatCAMObj.plot(self):
  2015. return
  2016. try:
  2017. # Plot excellon (All polygons?)
  2018. if self.options["solid"]:
  2019. for tool in self.tools:
  2020. for geo in self.tools[tool]['solid_geometry']:
  2021. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  2022. visible=self.options['plot'],
  2023. layer=2)
  2024. else:
  2025. for tool in self.tools:
  2026. for geo in self.tools[tool]['solid_geometry']:
  2027. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2028. for ints in geo.interiors:
  2029. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  2030. self.shapes.redraw()
  2031. return
  2032. except (ObjectDeleted, AttributeError, KeyError):
  2033. self.shapes.clear(update=True)
  2034. # this stays for compatibility reasons, in case we try to open old projects
  2035. try:
  2036. _ = iter(self.solid_geometry)
  2037. except TypeError:
  2038. self.solid_geometry = [self.solid_geometry]
  2039. try:
  2040. # Plot excellon (All polygons?)
  2041. if self.options["solid"]:
  2042. for geo in self.solid_geometry:
  2043. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF', visible=self.options['plot'],
  2044. layer=2)
  2045. else:
  2046. for geo in self.solid_geometry:
  2047. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2048. for ints in geo.interiors:
  2049. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  2050. self.shapes.redraw()
  2051. except (ObjectDeleted, AttributeError):
  2052. self.shapes.clear(update=True)
  2053. # try:
  2054. # # Plot excellon (All polygons?)
  2055. # if self.options["solid"]:
  2056. # for geo_type in self.solid_geometry:
  2057. # if geo_type is not None:
  2058. # if type(geo_type) is dict:
  2059. # for tooldia in geo_type:
  2060. # geo_list = geo_type[tooldia]
  2061. # for geo in geo_list:
  2062. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  2063. # visible=self.options['plot'],
  2064. # layer=2)
  2065. # else:
  2066. # self.add_shape(shape=geo_type, color='#750000BF', face_color='#C40000BF',
  2067. # visible=self.options['plot'],
  2068. # layer=2)
  2069. # else:
  2070. # for geo_type in self.solid_geometry:
  2071. # if geo_type is not None:
  2072. # if type(geo_type) is dict:
  2073. # for tooldia in geo_type:
  2074. # geo_list = geo_type[tooldia]
  2075. # for geo in geo_list:
  2076. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2077. # for ints in geo.interiors:
  2078. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  2079. # else:
  2080. # self.add_shape(shape=geo_type.exterior, color='red', visible=self.options['plot'])
  2081. # for ints in geo_type.interiors:
  2082. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  2083. # self.shapes.redraw()
  2084. # except (ObjectDeleted, AttributeError):
  2085. # self.shapes.clear(update=True)
  2086. class FlatCAMGeometry(FlatCAMObj, Geometry):
  2087. """
  2088. Geometric object not associated with a specific
  2089. format.
  2090. """
  2091. optionChanged = QtCore.pyqtSignal(str)
  2092. ui_type = GeometryObjectUI
  2093. @staticmethod
  2094. def merge(geo_list, geo_final, multigeo=None):
  2095. """
  2096. Merges the geometry of objects in grb_list into
  2097. the geometry of geo_final.
  2098. :param geo_list: List of FlatCAMGerber Objects to join.
  2099. :param geo_final: Destination FlatCAMGerber object.
  2100. :return: None
  2101. """
  2102. if geo_final.solid_geometry is None:
  2103. geo_final.solid_geometry = []
  2104. if type(geo_final.solid_geometry) is not list:
  2105. geo_final.solid_geometry = [geo_final.solid_geometry]
  2106. for geo in geo_list:
  2107. for option in geo.options:
  2108. if option is not 'name':
  2109. try:
  2110. geo_final.options[option] = geo.options[option]
  2111. except:
  2112. log.warning("Failed to copy option.", option)
  2113. # Expand lists
  2114. if type(geo) is list:
  2115. FlatCAMGeometry.merge(geo, geo_final)
  2116. # If not list, just append
  2117. else:
  2118. # merge solid_geometry, useful for singletool geometry, for multitool each is empty
  2119. if multigeo is None or multigeo == False:
  2120. geo_final.multigeo = False
  2121. try:
  2122. geo_final.solid_geometry.append(geo.solid_geometry)
  2123. except Exception as e:
  2124. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  2125. else:
  2126. geo_final.multigeo = True
  2127. # if multigeo the solid_geometry is empty in the object attributes because it now lives in the
  2128. # tools object attribute, as a key value
  2129. geo_final.solid_geometry = []
  2130. # find the tool_uid maximum value in the geo_final
  2131. geo_final_uid_list = []
  2132. for key in geo_final.tools:
  2133. geo_final_uid_list.append(int(key))
  2134. try:
  2135. max_uid = max(geo_final_uid_list, key=int)
  2136. except ValueError:
  2137. max_uid = 0
  2138. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  2139. # to merge the obj.tools as it is likely there is none to merge.
  2140. if not isinstance(geo, FlatCAMGerber) and not isinstance(geo, FlatCAMExcellon):
  2141. for tool_uid in geo.tools:
  2142. max_uid += 1
  2143. geo_final.tools[max_uid] = copy.deepcopy(geo.tools[tool_uid])
  2144. @staticmethod
  2145. def get_pts(o):
  2146. """
  2147. Returns a list of all points in the object, where
  2148. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  2149. of such. Search is done recursively.
  2150. :param: geometric object
  2151. :return: List of points
  2152. :rtype: list
  2153. """
  2154. pts = []
  2155. ## Iterable: descend into each item.
  2156. try:
  2157. for subo in o:
  2158. pts += FlatCAMGeometry.get_pts(subo)
  2159. ## Non-iterable
  2160. except TypeError:
  2161. if o is not None:
  2162. if type(o) == MultiPolygon:
  2163. for poly in o:
  2164. pts += FlatCAMGeometry.get_pts(poly)
  2165. ## Descend into .exerior and .interiors
  2166. elif type(o) == Polygon:
  2167. pts += FlatCAMGeometry.get_pts(o.exterior)
  2168. for i in o.interiors:
  2169. pts += FlatCAMGeometry.get_pts(i)
  2170. elif type(o) == MultiLineString:
  2171. for line in o:
  2172. pts += FlatCAMGeometry.get_pts(line)
  2173. ## Has .coords: list them.
  2174. else:
  2175. pts += list(o.coords)
  2176. else:
  2177. return
  2178. return pts
  2179. def __init__(self, name):
  2180. FlatCAMObj.__init__(self, name)
  2181. Geometry.__init__(self, geo_steps_per_circle=int(self.app.defaults["geometry_circle_steps"]))
  2182. self.kind = "geometry"
  2183. self.options.update({
  2184. "plot": True,
  2185. "cutz": -0.002,
  2186. "vtipdia": 0.1,
  2187. "vtipangle": 30,
  2188. "travelz": 0.1,
  2189. "feedrate": 5.0,
  2190. "feedrate_z": 5.0,
  2191. "feedrate_rapid": 5.0,
  2192. "spindlespeed": None,
  2193. "dwell": True,
  2194. "dwelltime": 1000,
  2195. "multidepth": False,
  2196. "depthperpass": 0.002,
  2197. "extracut": False,
  2198. "endz": 2.0,
  2199. "toolchange": False,
  2200. "toolchangez": 1.0,
  2201. "toolchangexy": "0.0, 0.0",
  2202. "startz": None,
  2203. "ppname_g": 'default',
  2204. "z_pdepth": -0.02,
  2205. "feedrate_probe": 3.0,
  2206. })
  2207. if "cnctooldia" not in self.options:
  2208. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  2209. self.options["startz"] = self.app.defaults["geometry_startz"]
  2210. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  2211. self.tooluid = 0
  2212. '''
  2213. self.tools = {}
  2214. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  2215. tool_id of the tools and the value is another dict that will hold the data under the following form:
  2216. {tooluid: {
  2217. 'tooldia': 1,
  2218. 'offset': 'Path',
  2219. 'offset_value': 0.0
  2220. 'type': 'Rough',
  2221. 'tool_type': 'C1',
  2222. 'data': self.default_tool_data
  2223. 'solid_geometry': []
  2224. }
  2225. }
  2226. '''
  2227. self.tools = {}
  2228. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  2229. # those elements are the ones used for generating GCode
  2230. self.sel_tools = {}
  2231. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  2232. self.type_item_options = ["Iso", "Rough", "Finish"]
  2233. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  2234. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  2235. self.v_tool_type = None
  2236. # flag to store if the Geometry is type 'multi-geometry' meaning that each tool has it's own geometry
  2237. # the default value is False
  2238. self.multigeo = False
  2239. # flag to store if the geometry is part of a special group of geometries that can't be processed by the default
  2240. # engine of FlatCAM. Most likely are generated by some of tools and are special cases of geometries.
  2241. self. special_group = None
  2242. # Attributes to be included in serialization
  2243. # Always append to it because it carries contents
  2244. # from predecessors.
  2245. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  2246. def build_ui(self):
  2247. self.ui_disconnect()
  2248. FlatCAMObj.build_ui(self)
  2249. offset = 0
  2250. tool_idx = 0
  2251. n = len(self.tools)
  2252. self.ui.geo_tools_table.setRowCount(n)
  2253. for tooluid_key, tooluid_value in self.tools.items():
  2254. tool_idx += 1
  2255. row_no = tool_idx - 1
  2256. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  2257. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2258. self.ui.geo_tools_table.setItem(row_no, 0, id) # Tool name/id
  2259. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  2260. # There are no tool bits in MM with more than 3 decimals diameter.
  2261. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  2262. if self.units == 'MM':
  2263. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(tooluid_value['tooldia']))
  2264. else:
  2265. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(tooluid_value['tooldia']))
  2266. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2267. offset_item = QtWidgets.QComboBox()
  2268. for item in self.offset_item_options:
  2269. offset_item.addItem(item)
  2270. offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  2271. idx = offset_item.findText(tooluid_value['offset'])
  2272. offset_item.setCurrentIndex(idx)
  2273. type_item = QtWidgets.QComboBox()
  2274. for item in self.type_item_options:
  2275. type_item.addItem(item)
  2276. type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2277. idx = type_item.findText(tooluid_value['type'])
  2278. type_item.setCurrentIndex(idx)
  2279. tool_type_item = QtWidgets.QComboBox()
  2280. for item in self.tool_type_item_options:
  2281. tool_type_item.addItem(item)
  2282. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2283. idx = tool_type_item.findText(tooluid_value['tool_type'])
  2284. tool_type_item.setCurrentIndex(idx)
  2285. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  2286. plot_item = FCCheckBox()
  2287. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  2288. if self.ui.plot_cb.isChecked():
  2289. plot_item.setChecked(True)
  2290. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  2291. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  2292. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  2293. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  2294. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  2295. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  2296. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  2297. try:
  2298. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  2299. except:
  2300. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools")
  2301. # make the diameter column editable
  2302. for row in range(tool_idx):
  2303. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  2304. QtCore.Qt.ItemIsEditable |
  2305. QtCore.Qt.ItemIsEnabled)
  2306. # sort the tool diameter column
  2307. # self.ui.geo_tools_table.sortItems(1)
  2308. # all the tools are selected by default
  2309. # self.ui.geo_tools_table.selectColumn(0)
  2310. self.ui.geo_tools_table.resizeColumnsToContents()
  2311. self.ui.geo_tools_table.resizeRowsToContents()
  2312. vertical_header = self.ui.geo_tools_table.verticalHeader()
  2313. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  2314. vertical_header.hide()
  2315. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2316. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  2317. horizontal_header.setMinimumSectionSize(10)
  2318. horizontal_header.setDefaultSectionSize(70)
  2319. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  2320. horizontal_header.resizeSection(0, 20)
  2321. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  2322. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  2323. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  2324. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  2325. horizontal_header.resizeSection(4, 40)
  2326. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  2327. horizontal_header.resizeSection(4, 17)
  2328. # horizontal_header.setStretchLastSection(True)
  2329. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2330. self.ui.geo_tools_table.setColumnWidth(0, 20)
  2331. self.ui.geo_tools_table.setColumnWidth(4, 40)
  2332. self.ui.geo_tools_table.setColumnWidth(6, 17)
  2333. # self.ui.geo_tools_table.setSortingEnabled(True)
  2334. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  2335. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  2336. # update UI for all rows - useful after units conversion but only if there is at least one row
  2337. row_cnt = self.ui.geo_tools_table.rowCount()
  2338. if row_cnt > 0:
  2339. for r in range(row_cnt):
  2340. self.update_ui(r)
  2341. # select only the first tool / row
  2342. selected_row = 0
  2343. try:
  2344. self.select_tools_table_row(selected_row, clearsel=True)
  2345. # update the Geometry UI
  2346. self.update_ui()
  2347. except Exception as e:
  2348. # when the tools table is empty there will be this error but once the table is populated it will go away
  2349. log.debug(str(e))
  2350. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  2351. # and can create some problems
  2352. if self.multigeo is False:
  2353. self.ui.geo_tools_table.setColumnHidden(6, True)
  2354. else:
  2355. self.ui.geo_tools_table.setColumnHidden(6, False)
  2356. self.set_tool_offset_visibility(selected_row)
  2357. self.ui_connect()
  2358. def set_ui(self, ui):
  2359. FlatCAMObj.set_ui(self, ui)
  2360. log.debug("FlatCAMGeometry.set_ui()")
  2361. assert isinstance(self.ui, GeometryObjectUI), \
  2362. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  2363. # populate postprocessor names in the combobox
  2364. for name in list(self.app.postprocessors.keys()):
  2365. self.ui.pp_geometry_name_cb.addItem(name)
  2366. self.form_fields.update({
  2367. "plot": self.ui.plot_cb,
  2368. "cutz": self.ui.cutz_entry,
  2369. "vtipdia": self.ui.tipdia_entry,
  2370. "vtipangle": self.ui.tipangle_entry,
  2371. "travelz": self.ui.travelz_entry,
  2372. "feedrate": self.ui.cncfeedrate_entry,
  2373. "feedrate_z": self.ui.cncplunge_entry,
  2374. "feedrate_rapid": self.ui.cncfeedrate_rapid_entry,
  2375. "spindlespeed": self.ui.cncspindlespeed_entry,
  2376. "dwell": self.ui.dwell_cb,
  2377. "dwelltime": self.ui.dwelltime_entry,
  2378. "multidepth": self.ui.mpass_cb,
  2379. "ppname_g": self.ui.pp_geometry_name_cb,
  2380. "z_pdepth": self.ui.pdepth_entry,
  2381. "feedrate_probe": self.ui.feedrate_probe_entry,
  2382. "depthperpass": self.ui.maxdepth_entry,
  2383. "extracut": self.ui.extracut_cb,
  2384. "toolchange": self.ui.toolchangeg_cb,
  2385. "toolchangez": self.ui.toolchangez_entry,
  2386. "endz": self.ui.gendz_entry,
  2387. })
  2388. # Fill form fields only on object create
  2389. self.to_form()
  2390. self.ui.tipdialabel.hide()
  2391. self.ui.tipdia_entry.hide()
  2392. self.ui.tipanglelabel.hide()
  2393. self.ui.tipangle_entry.hide()
  2394. self.ui.cutz_entry.setDisabled(False)
  2395. # store here the default data for Geometry Data
  2396. self.default_data = {}
  2397. self.default_data.update({
  2398. "name": None,
  2399. "plot": None,
  2400. "cutz": None,
  2401. "vtipdia": None,
  2402. "vtipangle": None,
  2403. "travelz": None,
  2404. "feedrate": None,
  2405. "feedrate_z": None,
  2406. "feedrate_rapid": None,
  2407. "dwell": None,
  2408. "dwelltime": None,
  2409. "multidepth": None,
  2410. "ppname_g": None,
  2411. "depthperpass": None,
  2412. "extracut": None,
  2413. "toolchange": None,
  2414. "toolchangez": None,
  2415. "endz": None,
  2416. "spindlespeed": None,
  2417. "toolchangexy": None,
  2418. "startz": None
  2419. })
  2420. # fill in self.default_data values from self.options
  2421. for def_key in self.default_data:
  2422. for opt_key, opt_val in self.options.items():
  2423. if def_key == opt_key:
  2424. self.default_data[def_key] = opt_val
  2425. self.tooluid += 1
  2426. if not self.tools:
  2427. self.tools.update({
  2428. self.tooluid: {
  2429. 'tooldia': float(self.options["cnctooldia"]),
  2430. 'offset': 'Path',
  2431. 'offset_value': 0.0,
  2432. 'type': 'Rough',
  2433. 'tool_type': 'C1',
  2434. 'data': self.default_data,
  2435. 'solid_geometry': self.solid_geometry
  2436. }
  2437. })
  2438. else:
  2439. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  2440. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  2441. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  2442. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  2443. # following convoluted way of changing the keys from string to float type
  2444. temp_tools = {}
  2445. new_key = 0.0
  2446. for tooluid_key in self.tools:
  2447. val = copy.deepcopy(self.tools[tooluid_key])
  2448. new_key = copy.deepcopy(int(tooluid_key))
  2449. temp_tools[new_key] = val
  2450. self.tools.clear()
  2451. self.tools = copy.deepcopy(temp_tools)
  2452. self.ui.tool_offset_entry.hide()
  2453. self.ui.tool_offset_lbl.hide()
  2454. # used to store the state of the mpass_cb if the selected postproc for geometry is hpgl
  2455. self.old_pp_state = self.default_data['multidepth']
  2456. self.old_toolchangeg_state = self.default_data['toolchange']
  2457. if not isinstance(self.ui, GeometryObjectUI):
  2458. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  2459. return
  2460. self.ui.geo_tools_table.setupContextMenu()
  2461. self.ui.geo_tools_table.addContextMenu(
  2462. "Copy", self.on_tool_copy, icon=QtGui.QIcon("share/copy16.png"))
  2463. self.ui.geo_tools_table.addContextMenu(
  2464. "Delete", lambda: self.on_tool_delete(all=None), icon=QtGui.QIcon("share/delete32.png"))
  2465. # Show/Hide Advanced Options
  2466. if self.app.defaults["global_app_level"] == 'b':
  2467. self.ui.level.setText('<span style="color:green;"><b>Basic</b></span>')
  2468. self.ui.geo_tools_table.setColumnHidden(2, True)
  2469. self.ui.geo_tools_table.setColumnHidden(3, True)
  2470. self.ui.geo_tools_table.setColumnHidden(4, True)
  2471. self.ui.addtool_entry_lbl.hide()
  2472. self.ui.addtool_entry.hide()
  2473. self.ui.addtool_btn.hide()
  2474. self.ui.copytool_btn.hide()
  2475. self.ui.deltool_btn.hide()
  2476. self.ui.endzlabel.hide()
  2477. self.ui.gendz_entry.hide()
  2478. self.ui.fr_rapidlabel.hide()
  2479. self.ui.cncfeedrate_rapid_entry.hide()
  2480. self.ui.extracut_cb.hide()
  2481. self.ui.pdepth_label.hide()
  2482. self.ui.pdepth_entry.hide()
  2483. self.ui.feedrate_probe_label.hide()
  2484. self.ui.feedrate_probe_entry.hide()
  2485. else:
  2486. self.ui.level.setText('<span style="color:red;"><b>Advanced</b></span>')
  2487. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2488. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  2489. self.ui.paint_tool_button.clicked.connect(self.app.paint_tool.run)
  2490. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  2491. def set_tool_offset_visibility(self, current_row):
  2492. if current_row is None:
  2493. return
  2494. try:
  2495. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  2496. if tool_offset is not None:
  2497. tool_offset_txt = tool_offset.currentText()
  2498. if tool_offset_txt == 'Custom':
  2499. self.ui.tool_offset_entry.show()
  2500. self.ui.tool_offset_lbl.show()
  2501. else:
  2502. self.ui.tool_offset_entry.hide()
  2503. self.ui.tool_offset_lbl.hide()
  2504. except Exception as e:
  2505. log.debug("set_tool_offset_visibility() --> " + str(e))
  2506. return
  2507. def on_offset_value_edited(self):
  2508. '''
  2509. This will save the offset_value into self.tools storage whenever the oofset value is edited
  2510. :return:
  2511. '''
  2512. for current_row in self.ui.geo_tools_table.selectedItems():
  2513. # sometime the header get selected and it has row number -1
  2514. # we don't want to do anything with the header :)
  2515. if current_row.row() < 0:
  2516. continue
  2517. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2518. self.set_tool_offset_visibility(current_row.row())
  2519. for tooluid_key, tooluid_value in self.tools.items():
  2520. if int(tooluid_key) == tool_uid:
  2521. try:
  2522. tooluid_value['offset_value'] = float(self.ui.tool_offset_entry.get_value())
  2523. except ValueError:
  2524. # try to convert comma to decimal point. if it's still not working error message and return
  2525. try:
  2526. tooluid_value['offset_value'] = float(
  2527. self.ui.tool_offset_entry.get_value().replace(',', '.')
  2528. )
  2529. except ValueError:
  2530. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2531. "use a number.")
  2532. return
  2533. def ui_connect(self):
  2534. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  2535. # changes in geometry UI
  2536. for i in range(self.ui.grid3.count()):
  2537. try:
  2538. # works for CheckBoxes
  2539. self.ui.grid3.itemAt(i).widget().stateChanged.connect(self.gui_form_to_storage)
  2540. except:
  2541. # works for ComboBoxes
  2542. try:
  2543. self.ui.grid3.itemAt(i).widget().currentIndexChanged.connect(self.gui_form_to_storage)
  2544. except:
  2545. # works for Entry
  2546. try:
  2547. self.ui.grid3.itemAt(i).widget().editingFinished.connect(self.gui_form_to_storage)
  2548. except:
  2549. pass
  2550. for row in range(self.ui.geo_tools_table.rowCount()):
  2551. for col in [2, 3, 4]:
  2552. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  2553. self.on_tooltable_cellwidget_change)
  2554. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  2555. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  2556. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  2557. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  2558. self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  2559. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  2560. self.ui.tool_offset_entry.editingFinished.connect(self.on_offset_value_edited)
  2561. for row in range(self.ui.geo_tools_table.rowCount()):
  2562. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  2563. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2564. def ui_disconnect(self):
  2565. try:
  2566. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  2567. # changes in geometry UI
  2568. for i in range(self.ui.grid3.count()):
  2569. if isinstance(self.ui.grid3.itemAt(i).widget(), FCCheckBox):
  2570. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect()
  2571. if isinstance(self.ui.grid3.itemAt(i).widget(), FCComboBox):
  2572. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect()
  2573. if isinstance(self.ui.grid3.itemAt(i).widget(), LengthEntry) or \
  2574. isinstance(self.ui.grid3.itemAt(i).widget(), IntEntry) or \
  2575. isinstance(self.ui.grid3.itemAt(i).widget(), FCEntry):
  2576. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect()
  2577. except:
  2578. pass
  2579. try:
  2580. for row in range(self.ui.geo_tools_table.rowCount()):
  2581. for col in [2, 3, 4]:
  2582. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  2583. except:
  2584. pass
  2585. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  2586. try:
  2587. self.ui.addtool_btn.clicked.disconnect()
  2588. except:
  2589. pass
  2590. try:
  2591. self.ui.copytool_btn.clicked.disconnect()
  2592. except:
  2593. pass
  2594. try:
  2595. self.ui.deltool_btn.clicked.disconnect()
  2596. except:
  2597. pass
  2598. try:
  2599. self.ui.geo_tools_table.currentItemChanged.disconnect()
  2600. except:
  2601. pass
  2602. try:
  2603. self.ui.geo_tools_table.itemChanged.disconnect()
  2604. except:
  2605. pass
  2606. try:
  2607. self.ui.tool_offset_entry.editingFinished.disconnect()
  2608. except:
  2609. pass
  2610. for row in range(self.ui.geo_tools_table.rowCount()):
  2611. try:
  2612. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  2613. except:
  2614. pass
  2615. try:
  2616. self.ui.plot_cb.stateChanged.disconnect()
  2617. except:
  2618. pass
  2619. def on_tool_add(self, dia=None):
  2620. self.ui_disconnect()
  2621. last_offset = None
  2622. last_offset_value = None
  2623. last_type = None
  2624. last_tool_type = None
  2625. last_data = None
  2626. last_solid_geometry = []
  2627. # if a Tool diameter entered is a char instead a number the final message of Tool adding is changed
  2628. # because the Default value for Tool is used.
  2629. change_message = False
  2630. if dia is not None:
  2631. tooldia = dia
  2632. else:
  2633. try:
  2634. tooldia = float(self.ui.addtool_entry.get_value())
  2635. except ValueError:
  2636. # try to convert comma to decimal point. if it's still not working error message and return
  2637. try:
  2638. tooldia = float(self.ui.addtool_entry.get_value().replace(',', '.'))
  2639. except ValueError:
  2640. change_message = True
  2641. tooldia = float(self.app.defaults["geometry_cnctooldia"])
  2642. if tooldia is None:
  2643. self.build_ui()
  2644. self.app.inform.emit("[ERROR_NOTCL] Please enter the desired tool diameter in Float format.")
  2645. return
  2646. # construct a list of all 'tooluid' in the self.tools
  2647. tool_uid_list = []
  2648. for tooluid_key in self.tools:
  2649. tool_uid_item = int(tooluid_key)
  2650. tool_uid_list.append(tool_uid_item)
  2651. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2652. if not tool_uid_list:
  2653. max_uid = 0
  2654. else:
  2655. max_uid = max(tool_uid_list)
  2656. self.tooluid = max_uid + 1
  2657. if self.units == 'IN':
  2658. tooldia = float('%.4f' % tooldia)
  2659. else:
  2660. tooldia = float('%.2f' % tooldia)
  2661. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  2662. # otherwise we add a tool with data copied from last tool
  2663. if not self.tools:
  2664. self.tools.update({
  2665. self.tooluid: {
  2666. 'tooldia': tooldia,
  2667. 'offset': 'Path',
  2668. 'offset_value': 0.0,
  2669. 'type': 'Rough',
  2670. 'tool_type': 'C1',
  2671. 'data': copy.deepcopy(self.default_data),
  2672. 'solid_geometry': self.solid_geometry
  2673. }
  2674. })
  2675. else:
  2676. # print("LAST", self.tools[maxuid])
  2677. last_data = self.tools[max_uid]['data']
  2678. last_offset = self.tools[max_uid]['offset']
  2679. last_offset_value = self.tools[max_uid]['offset_value']
  2680. last_type = self.tools[max_uid]['type']
  2681. last_tool_type = self.tools[max_uid]['tool_type']
  2682. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  2683. # if previous geometry was empty (it may happen for the first tool added)
  2684. # then copy the object.solid_geometry
  2685. if not last_solid_geometry:
  2686. last_solid_geometry = self.solid_geometry
  2687. self.tools.update({
  2688. self.tooluid: {
  2689. 'tooldia': tooldia,
  2690. 'offset': last_offset,
  2691. 'offset_value': last_offset_value,
  2692. 'type': last_type,
  2693. 'tool_type': last_tool_type,
  2694. 'data': copy.deepcopy(last_data),
  2695. 'solid_geometry': copy.deepcopy(last_solid_geometry)
  2696. }
  2697. })
  2698. # print("CURRENT", self.tools[-1])
  2699. self.ui.tool_offset_entry.hide()
  2700. self.ui.tool_offset_lbl.hide()
  2701. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2702. try:
  2703. self.ser_attrs.remove('tools')
  2704. except:
  2705. pass
  2706. self.ser_attrs.append('tools')
  2707. if change_message is False:
  2708. self.app.inform.emit("[success] Tool added in Tool Table.")
  2709. else:
  2710. change_message = False
  2711. self.app.inform.emit("[ERROR_NOTCL]Default Tool added. Wrong value format entered.")
  2712. self.build_ui()
  2713. def on_tool_copy(self, all=None):
  2714. self.ui_disconnect()
  2715. # find the tool_uid maximum value in the self.tools
  2716. uid_list = []
  2717. for key in self.tools:
  2718. uid_list.append(int(key))
  2719. try:
  2720. max_uid = max(uid_list, key=int)
  2721. except ValueError:
  2722. max_uid = 0
  2723. if all is None:
  2724. if self.ui.geo_tools_table.selectedItems():
  2725. for current_row in self.ui.geo_tools_table.selectedItems():
  2726. # sometime the header get selected and it has row number -1
  2727. # we don't want to do anything with the header :)
  2728. if current_row.row() < 0:
  2729. continue
  2730. try:
  2731. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2732. self.set_tool_offset_visibility(current_row.row())
  2733. max_uid += 1
  2734. self.tools[int(max_uid)] = copy.deepcopy(self.tools[tooluid_copy])
  2735. except AttributeError:
  2736. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to copy.")
  2737. self.build_ui()
  2738. return
  2739. except Exception as e:
  2740. log.debug("on_tool_copy() --> " + str(e))
  2741. # deselect the table
  2742. # self.ui.geo_tools_table.clearSelection()
  2743. else:
  2744. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to copy.")
  2745. self.build_ui()
  2746. return
  2747. else:
  2748. # we copy all tools in geo_tools_table
  2749. try:
  2750. temp_tools = copy.deepcopy(self.tools)
  2751. max_uid += 1
  2752. for tooluid in temp_tools:
  2753. self.tools[int(max_uid)] = copy.deepcopy(temp_tools[tooluid])
  2754. temp_tools.clear()
  2755. except Exception as e:
  2756. log.debug("on_tool_copy() --> " + str(e))
  2757. # if there are no more tools in geo tools table then hide the tool offset
  2758. if not self.tools:
  2759. self.ui.tool_offset_entry.hide()
  2760. self.ui.tool_offset_lbl.hide()
  2761. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2762. try:
  2763. self.ser_attrs.remove('tools')
  2764. except:
  2765. pass
  2766. self.ser_attrs.append('tools')
  2767. self.build_ui()
  2768. self.app.inform.emit("[success] Tool was copied in Tool Table.")
  2769. def on_tool_edit(self, current_item):
  2770. self.ui_disconnect()
  2771. current_row = current_item.row()
  2772. try:
  2773. d = float(self.ui.geo_tools_table.item(current_row, 1).text())
  2774. except ValueError:
  2775. # try to convert comma to decimal point. if it's still not working error message and return
  2776. try:
  2777. d = float(self.ui.geo_tools_table.item(current_row, 1).text().replace(',', '.'))
  2778. except ValueError:
  2779. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2780. "use a number.")
  2781. return
  2782. tool_dia = float('%.4f' % d)
  2783. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2784. self.tools[tooluid]['tooldia'] = tool_dia
  2785. try:
  2786. self.ser_attrs.remove('tools')
  2787. self.ser_attrs.append('tools')
  2788. except:
  2789. pass
  2790. self.app.inform.emit("[success] Tool was edited in Tool Table.")
  2791. self.build_ui()
  2792. def on_tool_delete(self, all=None):
  2793. self.ui_disconnect()
  2794. if all is None:
  2795. if self.ui.geo_tools_table.selectedItems():
  2796. for current_row in self.ui.geo_tools_table.selectedItems():
  2797. # sometime the header get selected and it has row number -1
  2798. # we don't want to do anything with the header :)
  2799. if current_row.row() < 0:
  2800. continue
  2801. try:
  2802. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2803. self.set_tool_offset_visibility(current_row.row())
  2804. temp_tools = copy.deepcopy(self.tools)
  2805. for tooluid_key in self.tools:
  2806. if int(tooluid_key) == tooluid_del:
  2807. # if the self.tools has only one tool and we delete it then we move the solid_geometry
  2808. # as a property of the object otherwise there will be nothing to hold it
  2809. if len(self.tools) == 1:
  2810. self.solid_geometry = copy.deepcopy(self.tools[tooluid_key]['solid_geometry'])
  2811. temp_tools.pop(tooluid_del, None)
  2812. self.tools = copy.deepcopy(temp_tools)
  2813. temp_tools.clear()
  2814. except AttributeError:
  2815. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to delete.")
  2816. self.build_ui()
  2817. return
  2818. except Exception as e:
  2819. log.debug("on_tool_delete() --> " + str(e))
  2820. # deselect the table
  2821. # self.ui.geo_tools_table.clearSelection()
  2822. else:
  2823. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to delete.")
  2824. self.build_ui()
  2825. return
  2826. else:
  2827. # we delete all tools in geo_tools_table
  2828. self.tools.clear()
  2829. self.app.plot_all()
  2830. # if there are no more tools in geo tools table then hide the tool offset
  2831. if not self.tools:
  2832. self.ui.tool_offset_entry.hide()
  2833. self.ui.tool_offset_lbl.hide()
  2834. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2835. try:
  2836. self.ser_attrs.remove('tools')
  2837. except:
  2838. pass
  2839. self.ser_attrs.append('tools')
  2840. self.build_ui()
  2841. self.app.inform.emit("[success] Tool was deleted in Tool Table.")
  2842. obj_active = self.app.collection.get_active()
  2843. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  2844. # we make it back SingleGeo
  2845. if self.ui.geo_tools_table.rowCount() <= 0:
  2846. obj_active.multigeo = False
  2847. obj_active.options['xmin'] = 0
  2848. obj_active.options['ymin'] = 0
  2849. obj_active.options['xmax'] = 0
  2850. obj_active.options['ymax'] = 0
  2851. if obj_active.multigeo is True:
  2852. try:
  2853. xmin, ymin, xmax, ymax = obj_active.bounds()
  2854. obj_active.options['xmin'] = xmin
  2855. obj_active.options['ymin'] = ymin
  2856. obj_active.options['xmax'] = xmax
  2857. obj_active.options['ymax'] = ymax
  2858. except:
  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. def on_row_selection_change(self):
  2864. self.update_ui()
  2865. def update_ui(self, row=None):
  2866. self.ui_disconnect()
  2867. if row is None:
  2868. try:
  2869. current_row = self.ui.geo_tools_table.currentRow()
  2870. except:
  2871. current_row = 0
  2872. else:
  2873. current_row = row
  2874. if current_row < 0:
  2875. current_row = 0
  2876. self.set_tool_offset_visibility(current_row)
  2877. # populate the form with the data from the tool associated with the row parameter
  2878. try:
  2879. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2880. except Exception as e:
  2881. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2882. return
  2883. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  2884. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  2885. try:
  2886. tool_type_txt = self.ui.geo_tools_table.cellWidget(current_row, 4).currentText()
  2887. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  2888. except Exception as e:
  2889. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2890. return
  2891. try:
  2892. # set the form with data from the newly selected tool
  2893. for tooluid_key, tooluid_value in self.tools.items():
  2894. if int(tooluid_key) == tooluid:
  2895. for key, value in tooluid_value.items():
  2896. if key == 'data':
  2897. form_value_storage = tooluid_value[key]
  2898. self.update_form(form_value_storage)
  2899. if key == 'offset_value':
  2900. # update the offset value in the entry even if the entry is hidden
  2901. self.ui.tool_offset_entry.set_value(tooluid_value[key])
  2902. if key == 'tool_type' and value == 'V':
  2903. self.update_cutz()
  2904. except Exception as e:
  2905. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  2906. self.ui_connect()
  2907. def ui_update_v_shape(self, tool_type_txt):
  2908. if tool_type_txt == 'V':
  2909. self.ui.tipdialabel.show()
  2910. self.ui.tipdia_entry.show()
  2911. self.ui.tipanglelabel.show()
  2912. self.ui.tipangle_entry.show()
  2913. self.ui.cutz_entry.setDisabled(True)
  2914. self.update_cutz()
  2915. else:
  2916. self.ui.tipdialabel.hide()
  2917. self.ui.tipdia_entry.hide()
  2918. self.ui.tipanglelabel.hide()
  2919. self.ui.tipangle_entry.hide()
  2920. self.ui.cutz_entry.setDisabled(False)
  2921. def update_cutz(self):
  2922. try:
  2923. vdia = float(self.ui.tipdia_entry.get_value())
  2924. except ValueError:
  2925. # try to convert comma to decimal point. if it's still not working error message and return
  2926. try:
  2927. vdia = float(self.ui.tipdia_entry.get_value().replace(',', '.'))
  2928. except ValueError:
  2929. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2930. "use a number.")
  2931. return
  2932. try:
  2933. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  2934. except ValueError:
  2935. # try to convert comma to decimal point. if it's still not working error message and return
  2936. try:
  2937. half_vangle = float(self.ui.tipangle_entry.get_value().replace(',', '.')) / 2
  2938. except ValueError:
  2939. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2940. "use a number.")
  2941. return
  2942. row = self.ui.geo_tools_table.currentRow()
  2943. tool_uid = int(self.ui.geo_tools_table.item(row, 5).text())
  2944. tooldia = float(self.ui.geo_tools_table.item(row, 1).text())
  2945. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  2946. new_cutz = float('%.4f' % -new_cutz)
  2947. self.ui.cutz_entry.set_value(new_cutz)
  2948. # store the new CutZ value into storage (self.tools)
  2949. for tooluid_key, tooluid_value in self.tools.items():
  2950. if int(tooluid_key) == tool_uid:
  2951. tooluid_value['data']['cutz'] = new_cutz
  2952. def on_tooltable_cellwidget_change(self):
  2953. cw = self.sender()
  2954. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  2955. cw_row = cw_index.row()
  2956. cw_col = cw_index.column()
  2957. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  2958. # store the text of the cellWidget that changed it's index in the self.tools
  2959. for tooluid_key, tooluid_value in self.tools.items():
  2960. if int(tooluid_key) == current_uid:
  2961. cb_txt = cw.currentText()
  2962. if cw_col == 2:
  2963. tooluid_value['offset'] = cb_txt
  2964. if cb_txt == 'Custom':
  2965. self.ui.tool_offset_entry.show()
  2966. self.ui.tool_offset_lbl.show()
  2967. else:
  2968. self.ui.tool_offset_entry.hide()
  2969. self.ui.tool_offset_lbl.hide()
  2970. # reset the offset_value in storage self.tools
  2971. tooluid_value['offset_value'] = 0.0
  2972. elif cw_col == 3:
  2973. # force toolpath type as 'Iso' if the tool type is V-Shape
  2974. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  2975. tooluid_value['type'] = 'Iso'
  2976. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2977. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2978. else:
  2979. tooluid_value['type'] = cb_txt
  2980. elif cw_col == 4:
  2981. tooluid_value['tool_type'] = cb_txt
  2982. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  2983. if cb_txt == 'V':
  2984. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2985. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2986. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  2987. def update_form(self, dict_storage):
  2988. for form_key in self.form_fields:
  2989. for storage_key in dict_storage:
  2990. if form_key == storage_key:
  2991. try:
  2992. self.form_fields[form_key].set_value(dict_storage[form_key])
  2993. except Exception as e:
  2994. log.debug(str(e))
  2995. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  2996. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  2997. self.ui.ois_dwell_geo.on_cb_change()
  2998. self.ui.ois_mpass_geo.on_cb_change()
  2999. self.ui.ois_tcz_geo.on_cb_change()
  3000. def gui_form_to_storage(self):
  3001. self.ui_disconnect()
  3002. widget_changed = self.sender()
  3003. try:
  3004. widget_idx = self.ui.grid3.indexOf(widget_changed)
  3005. except:
  3006. return
  3007. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  3008. if widget_idx == 1 or widget_idx == 3:
  3009. self.update_cutz()
  3010. # the original connect() function of the OptionalInpuSelection is no longer working because of the
  3011. # ui_diconnect() so I use this 'hack'
  3012. if isinstance(widget_changed, FCCheckBox):
  3013. if widget_changed.text() == 'Multi-Depth:':
  3014. self.ui.ois_mpass_geo.on_cb_change()
  3015. if widget_changed.text() == 'Tool change':
  3016. self.ui.ois_tcz_geo.on_cb_change()
  3017. if widget_changed.text() == 'Dwell:':
  3018. self.ui.ois_dwell_geo.on_cb_change()
  3019. row = self.ui.geo_tools_table.currentRow()
  3020. if row < 0:
  3021. row = 0
  3022. # store all the data associated with the row parameter to the self.tools storage
  3023. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  3024. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  3025. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  3026. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  3027. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  3028. try:
  3029. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  3030. except ValueError:
  3031. # try to convert comma to decimal point. if it's still not working error message and return
  3032. try:
  3033. offset_value_item = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3034. )
  3035. except ValueError:
  3036. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  3037. "use a number.")
  3038. return
  3039. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  3040. temp_tools = {}
  3041. temp_dia = {}
  3042. temp_data = {}
  3043. for tooluid_key, tooluid_value in self.tools.items():
  3044. if int(tooluid_key) == tooluid_item:
  3045. for key, value in tooluid_value.items():
  3046. if key == 'tooldia':
  3047. temp_dia[key] = tooldia_item
  3048. # update the 'offset', 'type' and 'tool_type' sections
  3049. if key == 'offset':
  3050. temp_dia[key] = offset_item
  3051. if key == 'type':
  3052. temp_dia[key] = type_item
  3053. if key == 'tool_type':
  3054. temp_dia[key] = tool_type_item
  3055. if key == 'offset_value':
  3056. temp_dia[key] = offset_value_item
  3057. if key == 'data':
  3058. # update the 'data' section
  3059. for data_key in tooluid_value[key].keys():
  3060. for form_key, form_value in self.form_fields.items():
  3061. if form_key == data_key:
  3062. temp_data[data_key] = form_value.get_value()
  3063. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  3064. # updated from self.app.defaults
  3065. if data_key not in self.form_fields:
  3066. temp_data[data_key] = value[data_key]
  3067. temp_dia[key] = copy.deepcopy(temp_data)
  3068. temp_data.clear()
  3069. if key == 'solid_geometry':
  3070. temp_dia[key] = copy.deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3071. temp_tools[tooluid_key] = copy.deepcopy(temp_dia)
  3072. else:
  3073. temp_tools[tooluid_key] = copy.deepcopy(tooluid_value)
  3074. self.tools.clear()
  3075. self.tools = copy.deepcopy(temp_tools)
  3076. temp_tools.clear()
  3077. self.ui_connect()
  3078. def select_tools_table_row(self, row, clearsel=None):
  3079. if clearsel:
  3080. self.ui.geo_tools_table.clearSelection()
  3081. if self.ui.geo_tools_table.rowCount() > 0:
  3082. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  3083. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  3084. def export_dxf(self):
  3085. units = self.app.ui.general_options_form.general_app_group.units_radio.get_value().upper()
  3086. dwg = None
  3087. try:
  3088. dwg = ezdxf.new('R2010')
  3089. msp = dwg.modelspace()
  3090. def g2dxf(dxf_space, geo):
  3091. if isinstance(geo, MultiPolygon):
  3092. for poly in geo:
  3093. ext_points = list(poly.exterior.coords)
  3094. dxf_space.add_lwpolyline(ext_points)
  3095. for interior in poly.interiors:
  3096. dxf_space.add_lwpolyline(list(interior.coords))
  3097. if isinstance(geo, Polygon):
  3098. ext_points = list(geo.exterior.coords)
  3099. dxf_space.add_lwpolyline(ext_points)
  3100. for interior in geo.interiors:
  3101. dxf_space.add_lwpolyline(list(interior.coords))
  3102. if isinstance(geo, MultiLineString):
  3103. for line in geo:
  3104. dxf_space.add_lwpolyline(list(line.coords))
  3105. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  3106. dxf_space.add_lwpolyline(list(geo.coords))
  3107. multigeo_solid_geometry = []
  3108. if self.multigeo:
  3109. for tool in self.tools:
  3110. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  3111. else:
  3112. multigeo_solid_geometry = self.solid_geometry
  3113. for geo in multigeo_solid_geometry:
  3114. if type(geo) == list:
  3115. for g in geo:
  3116. g2dxf(msp, g)
  3117. else:
  3118. g2dxf(msp, geo)
  3119. # points = FlatCAMGeometry.get_pts(geo)
  3120. # msp.add_lwpolyline(points)
  3121. except Exception as e:
  3122. log.debug(str(e))
  3123. return dwg
  3124. def get_selected_tools_table_items(self):
  3125. """
  3126. Returns a list of lists, each list in the list is made out of row elements
  3127. :return: List of table_tools items.
  3128. :rtype: list
  3129. """
  3130. table_tools_items = []
  3131. if self.multigeo:
  3132. for x in self.ui.geo_tools_table.selectedItems():
  3133. table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  3134. for column in range(0, self.ui.geo_tools_table.columnCount())])
  3135. else:
  3136. for x in self.ui.geo_tools_table.selectedItems():
  3137. r = []
  3138. # the last 2 columns for single-geo geometry are irrelevant and create problems reading
  3139. # so we don't read them
  3140. for column in range(0, self.ui.geo_tools_table.columnCount() - 2):
  3141. # the columns have items that have text but also have items that are widgets
  3142. # for which the text they hold has to be read differently
  3143. try:
  3144. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  3145. except AttributeError:
  3146. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  3147. except:
  3148. pass
  3149. r.append(txt)
  3150. table_tools_items.append(r)
  3151. for item in table_tools_items:
  3152. item[0] = str(item[0])
  3153. return table_tools_items
  3154. def on_pp_changed(self):
  3155. current_pp = self.ui.pp_geometry_name_cb.get_value()
  3156. if current_pp == 'hpgl':
  3157. self.old_pp_state = self.ui.mpass_cb.get_value()
  3158. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  3159. self.ui.mpass_cb.set_value(False)
  3160. self.ui.mpass_cb.setDisabled(True)
  3161. self.ui.toolchangeg_cb.set_value(True)
  3162. self.ui.toolchangeg_cb.setDisabled(True)
  3163. else:
  3164. self.ui.mpass_cb.set_value(self.old_pp_state)
  3165. self.ui.mpass_cb.setDisabled(False)
  3166. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  3167. self.ui.toolchangeg_cb.setDisabled(False)
  3168. if "toolchange_probe" in current_pp.lower():
  3169. self.ui.pdepth_entry.setVisible(True)
  3170. self.ui.pdepth_label.show()
  3171. self.ui.feedrate_probe_entry.setVisible(True)
  3172. self.ui.feedrate_probe_label.show()
  3173. else:
  3174. self.ui.pdepth_entry.setVisible(False)
  3175. self.ui.pdepth_label.hide()
  3176. self.ui.feedrate_probe_entry.setVisible(False)
  3177. self.ui.feedrate_probe_label.hide()
  3178. def on_generatecnc_button_click(self, *args):
  3179. self.app.report_usage("geometry_on_generatecnc_button")
  3180. self.read_form()
  3181. self.sel_tools = {}
  3182. try:
  3183. if self.special_group:
  3184. self.app.inform.emit("[WARNING_NOTCL]This Geometry can't be processed because it is %s geometry." %
  3185. str(self.special_group))
  3186. return
  3187. except AttributeError:
  3188. pass
  3189. # test to see if we have tools available in the tool table
  3190. if self.ui.geo_tools_table.selectedItems():
  3191. for x in self.ui.geo_tools_table.selectedItems():
  3192. try:
  3193. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  3194. except ValueError:
  3195. # try to convert comma to decimal point. if it's still not working error message and return
  3196. try:
  3197. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text().replace(',', '.'))
  3198. except ValueError:
  3199. self.app.inform.emit("[ERROR_NOTCL]Wrong Tool Dia value format entered, "
  3200. "use a number.")
  3201. return
  3202. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  3203. for tooluid_key, tooluid_value in self.tools.items():
  3204. if int(tooluid_key) == tooluid:
  3205. self.sel_tools.update({
  3206. tooluid: copy.deepcopy(tooluid_value)
  3207. })
  3208. self.mtool_gen_cncjob()
  3209. self.ui.geo_tools_table.clearSelection()
  3210. elif self.ui.geo_tools_table.rowCount() == 1:
  3211. tooluid = int(self.ui.geo_tools_table.item(0, 5).text())
  3212. for tooluid_key, tooluid_value in self.tools.items():
  3213. if int(tooluid_key) == tooluid:
  3214. self.sel_tools.update({
  3215. tooluid: copy.deepcopy(tooluid_value)
  3216. })
  3217. self.mtool_gen_cncjob()
  3218. self.ui.geo_tools_table.clearSelection()
  3219. else:
  3220. self.app.inform.emit("[ERROR_NOTCL] Failed. No tool selected in the tool table ...")
  3221. def mtool_gen_cncjob(self, segx=None, segy=None, use_thread=True):
  3222. """
  3223. Creates a multi-tool CNCJob out of this Geometry object.
  3224. The actual work is done by the target FlatCAMCNCjob object's
  3225. `generate_from_geometry_2()` method.
  3226. :param z_cut: Cut depth (negative)
  3227. :param z_move: Hight of the tool when travelling (not cutting)
  3228. :param feedrate: Feed rate while cutting on X - Y plane
  3229. :param feedrate_z: Feed rate while cutting on Z plane
  3230. :param feedrate_rapid: Feed rate while moving with rapids
  3231. :param tooldia: Tool diameter
  3232. :param outname: Name of the new object
  3233. :param spindlespeed: Spindle speed (RPM)
  3234. :param ppname_g Name of the postprocessor
  3235. :return: None
  3236. """
  3237. offset_str = ''
  3238. multitool_gcode = ''
  3239. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  3240. outname = "%s_%s" % (self.options["name"], 'cnc')
  3241. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  3242. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  3243. try:
  3244. xmin = self.options['xmin']
  3245. ymin = self.options['ymin']
  3246. xmax = self.options['xmax']
  3247. ymax = self.options['ymax']
  3248. except Exception as e:
  3249. log.debug("FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s\n" % str(e))
  3250. msg = "[ERROR] An internal error has ocurred. See shell.\n"
  3251. msg += 'FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s' % str(e)
  3252. msg += traceback.format_exc()
  3253. self.app.inform.emit(msg)
  3254. return
  3255. # Object initialization function for app.new_object()
  3256. # RUNNING ON SEPARATE THREAD!
  3257. def job_init_single_geometry(job_obj, app_obj):
  3258. assert isinstance(job_obj, FlatCAMCNCjob), \
  3259. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3260. # count the tools
  3261. tool_cnt = 0
  3262. dia_cnc_dict = {}
  3263. # this turn on the FlatCAMCNCJob plot for multiple tools
  3264. job_obj.multitool = True
  3265. job_obj.multigeo = False
  3266. job_obj.cnc_tools.clear()
  3267. # job_obj.create_geometry()
  3268. job_obj.options['Tools_in_use'] = self.get_selected_tools_table_items()
  3269. job_obj.segx = segx
  3270. job_obj.segy = segy
  3271. try:
  3272. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3273. except ValueError:
  3274. # try to convert comma to decimal point. if it's still not working error message and return
  3275. try:
  3276. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3277. except ValueError:
  3278. self.app.inform.emit(
  3279. '[ERROR_NOTCL]Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]')
  3280. try:
  3281. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3282. except ValueError:
  3283. # try to convert comma to decimal point. if it's still not working error message and return
  3284. try:
  3285. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3286. except ValueError:
  3287. self.app.inform.emit(
  3288. '[ERROR_NOTCL]Wrong value format for self.defaults["feedrate_probe"] '
  3289. 'or self.options["feedrate_probe"]')
  3290. for tooluid_key in self.sel_tools:
  3291. tool_cnt += 1
  3292. app_obj.progress.emit(20)
  3293. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3294. if diadict_key == 'tooldia':
  3295. tooldia_val = float('%.4f' % float(diadict_value))
  3296. dia_cnc_dict.update({
  3297. diadict_key: tooldia_val
  3298. })
  3299. if diadict_key == 'offset':
  3300. o_val = diadict_value.lower()
  3301. dia_cnc_dict.update({
  3302. diadict_key: o_val
  3303. })
  3304. if diadict_key == 'type':
  3305. t_val = diadict_value
  3306. dia_cnc_dict.update({
  3307. diadict_key: t_val
  3308. })
  3309. if diadict_key == 'tool_type':
  3310. tt_val = diadict_value
  3311. dia_cnc_dict.update({
  3312. diadict_key: tt_val
  3313. })
  3314. if diadict_key == 'data':
  3315. for data_key, data_value in diadict_value.items():
  3316. if data_key == "multidepth":
  3317. multidepth = data_value
  3318. if data_key == "depthperpass":
  3319. depthpercut = data_value
  3320. if data_key == "extracut":
  3321. extracut = data_value
  3322. if data_key == "startz":
  3323. startz = data_value
  3324. if data_key == "endz":
  3325. endz = data_value
  3326. if data_key == "toolchangez":
  3327. toolchangez =data_value
  3328. if data_key == "toolchangexy":
  3329. toolchangexy = data_value
  3330. if data_key == "toolchange":
  3331. toolchange = data_value
  3332. if data_key == "cutz":
  3333. z_cut = data_value
  3334. if data_key == "travelz":
  3335. z_move = data_value
  3336. if data_key == "feedrate":
  3337. feedrate = data_value
  3338. if data_key == "feedrate_z":
  3339. feedrate_z = data_value
  3340. if data_key == "feedrate_rapid":
  3341. feedrate_rapid = data_value
  3342. if data_key == "ppname_g":
  3343. pp_geometry_name = data_value
  3344. if data_key == "spindlespeed":
  3345. spindlespeed = data_value
  3346. if data_key == "dwell":
  3347. dwell = data_value
  3348. if data_key == "dwelltime":
  3349. dwelltime = data_value
  3350. datadict = copy.deepcopy(diadict_value)
  3351. dia_cnc_dict.update({
  3352. diadict_key: datadict
  3353. })
  3354. if dia_cnc_dict['offset'] == 'in':
  3355. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3356. offset_str = 'inside'
  3357. elif dia_cnc_dict['offset'].lower() == 'out':
  3358. tool_offset = dia_cnc_dict['tooldia'] / 2
  3359. offset_str = 'outside'
  3360. elif dia_cnc_dict['offset'].lower() == 'path':
  3361. offset_str = 'onpath'
  3362. tool_offset = 0.0
  3363. else:
  3364. offset_str = 'custom'
  3365. try:
  3366. offset_value = float(self.ui.tool_offset_entry.get_value())
  3367. except ValueError:
  3368. # try to convert comma to decimal point. if it's still not working error message and return
  3369. try:
  3370. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3371. )
  3372. except ValueError:
  3373. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  3374. "use a number.")
  3375. return
  3376. if offset_value:
  3377. tool_offset = float(offset_value)
  3378. else:
  3379. self.app.inform.emit(
  3380. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3381. "Add a Tool Offset or change the Offset Type."
  3382. )
  3383. return
  3384. dia_cnc_dict.update({
  3385. 'offset_value': tool_offset
  3386. })
  3387. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3388. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3389. # Propagate options
  3390. job_obj.options["tooldia"] = tooldia_val
  3391. job_obj.options['type'] = 'Geometry'
  3392. job_obj.options['tool_dia'] = tooldia_val
  3393. job_obj.options['xmin'] = xmin
  3394. job_obj.options['ymin'] = ymin
  3395. job_obj.options['xmax'] = xmax
  3396. job_obj.options['ymax'] = ymax
  3397. app_obj.progress.emit(40)
  3398. res = job_obj.generate_from_geometry_2(
  3399. self, tooldia=tooldia_val, offset=tool_offset, tolerance=0.0005,
  3400. z_cut=z_cut, z_move=z_move,
  3401. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3402. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  3403. multidepth=multidepth, depthpercut=depthpercut,
  3404. extracut=extracut, startz=startz, endz=endz,
  3405. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3406. pp_geometry_name=pp_geometry_name,
  3407. tool_no=tool_cnt)
  3408. if res == 'fail':
  3409. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3410. return 'fail'
  3411. else:
  3412. dia_cnc_dict['gcode'] = res
  3413. app_obj.progress.emit(50)
  3414. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3415. # object is the source of gcode
  3416. job_obj.toolchange_xy_type = "geometry"
  3417. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3418. # TODO this serve for bounding box creation only; should be optimized
  3419. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3420. app_obj.progress.emit(80)
  3421. job_obj.cnc_tools.update({
  3422. tooluid_key: copy.deepcopy(dia_cnc_dict)
  3423. })
  3424. dia_cnc_dict.clear()
  3425. # Object initialization function for app.new_object()
  3426. # RUNNING ON SEPARATE THREAD!
  3427. def job_init_multi_geometry(job_obj, app_obj):
  3428. assert isinstance(job_obj, FlatCAMCNCjob), \
  3429. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3430. # count the tools
  3431. tool_cnt = 0
  3432. dia_cnc_dict = {}
  3433. current_uid = int(1)
  3434. # this turn on the FlatCAMCNCJob plot for multiple tools
  3435. job_obj.multitool = True
  3436. job_obj.multigeo = True
  3437. job_obj.cnc_tools.clear()
  3438. job_obj.options['xmin'] = xmin
  3439. job_obj.options['ymin'] = ymin
  3440. job_obj.options['xmax'] = xmax
  3441. job_obj.options['ymax'] = ymax
  3442. try:
  3443. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3444. except ValueError:
  3445. # try to convert comma to decimal point. if it's still not working error message and return
  3446. try:
  3447. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3448. except ValueError:
  3449. self.app.inform.emit(
  3450. '[ERROR_NOTCL]Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]')
  3451. try:
  3452. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3453. except ValueError:
  3454. # try to convert comma to decimal point. if it's still not working error message and return
  3455. try:
  3456. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3457. except ValueError:
  3458. self.app.inform.emit(
  3459. '[ERROR_NOTCL]Wrong value format for self.defaults["feedrate_probe"] '
  3460. 'or self.options["feedrate_probe"]')
  3461. # make sure that trying to make a CNCJob from an empty file is not creating an app crash
  3462. if not self.solid_geometry:
  3463. a = 0
  3464. for tooluid_key in self.tools:
  3465. if self.tools[tooluid_key]['solid_geometry'] is None:
  3466. a += 1
  3467. if a == len(self.tools):
  3468. self.app.inform.emit('[ERROR_NOTCL]Cancelled. Empty file, it has no geometry...')
  3469. return 'fail'
  3470. for tooluid_key in self.sel_tools:
  3471. tool_cnt += 1
  3472. app_obj.progress.emit(20)
  3473. # find the tool_dia associated with the tooluid_key
  3474. sel_tool_dia = self.sel_tools[tooluid_key]['tooldia']
  3475. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  3476. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  3477. for k, v in self.tools.items():
  3478. if float('%.4f' % float(v['tooldia'])) == float('%.4f' % float(sel_tool_dia)):
  3479. current_uid = int(k)
  3480. break
  3481. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3482. if diadict_key == 'tooldia':
  3483. tooldia_val = float('%.4f' % float(diadict_value))
  3484. dia_cnc_dict.update({
  3485. diadict_key: tooldia_val
  3486. })
  3487. if diadict_key == 'offset':
  3488. o_val = diadict_value.lower()
  3489. dia_cnc_dict.update({
  3490. diadict_key: o_val
  3491. })
  3492. if diadict_key == 'type':
  3493. t_val = diadict_value
  3494. dia_cnc_dict.update({
  3495. diadict_key: t_val
  3496. })
  3497. if diadict_key == 'tool_type':
  3498. tt_val = diadict_value
  3499. dia_cnc_dict.update({
  3500. diadict_key: tt_val
  3501. })
  3502. if diadict_key == 'data':
  3503. for data_key, data_value in diadict_value.items():
  3504. if data_key == "multidepth":
  3505. multidepth = data_value
  3506. if data_key == "depthperpass":
  3507. depthpercut = data_value
  3508. if data_key == "extracut":
  3509. extracut = data_value
  3510. if data_key == "startz":
  3511. startz = data_value
  3512. if data_key == "endz":
  3513. endz = data_value
  3514. if data_key == "toolchangez":
  3515. toolchangez =data_value
  3516. if data_key == "toolchangexy":
  3517. toolchangexy = data_value
  3518. if data_key == "toolchange":
  3519. toolchange = data_value
  3520. if data_key == "cutz":
  3521. z_cut = data_value
  3522. if data_key == "travelz":
  3523. z_move = data_value
  3524. if data_key == "feedrate":
  3525. feedrate = data_value
  3526. if data_key == "feedrate_z":
  3527. feedrate_z = data_value
  3528. if data_key == "feedrate_rapid":
  3529. feedrate_rapid = data_value
  3530. if data_key == "ppname_g":
  3531. pp_geometry_name = data_value
  3532. if data_key == "spindlespeed":
  3533. spindlespeed = data_value
  3534. if data_key == "dwell":
  3535. dwell = data_value
  3536. if data_key == "dwelltime":
  3537. dwelltime = data_value
  3538. datadict = copy.deepcopy(diadict_value)
  3539. dia_cnc_dict.update({
  3540. diadict_key: datadict
  3541. })
  3542. if dia_cnc_dict['offset'] == 'in':
  3543. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3544. offset_str = 'inside'
  3545. elif dia_cnc_dict['offset'].lower() == 'out':
  3546. tool_offset = dia_cnc_dict['tooldia'] / 2
  3547. offset_str = 'outside'
  3548. elif dia_cnc_dict['offset'].lower() == 'path':
  3549. offset_str = 'onpath'
  3550. tool_offset = 0.0
  3551. else:
  3552. offset_str = 'custom'
  3553. try:
  3554. offset_value = float(self.ui.tool_offset_entry.get_value())
  3555. except ValueError:
  3556. # try to convert comma to decimal point. if it's still not working error message and return
  3557. try:
  3558. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3559. )
  3560. except ValueError:
  3561. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  3562. "use a number.")
  3563. return
  3564. if offset_value:
  3565. tool_offset = float(offset_value)
  3566. else:
  3567. self.app.inform.emit(
  3568. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3569. "Add a Tool Offset or change the Offset Type."
  3570. )
  3571. return
  3572. dia_cnc_dict.update({
  3573. 'offset_value': tool_offset
  3574. })
  3575. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3576. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3577. # Propagate options
  3578. job_obj.options["tooldia"] = tooldia_val
  3579. job_obj.options['type'] = 'Geometry'
  3580. job_obj.options['tool_dia'] = tooldia_val
  3581. app_obj.progress.emit(40)
  3582. tool_solid_geometry = self.tools[current_uid]['solid_geometry']
  3583. res = job_obj.generate_from_multitool_geometry(
  3584. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  3585. tolerance=0.0005, z_cut=z_cut, z_move=z_move,
  3586. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3587. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  3588. multidepth=multidepth, depthpercut=depthpercut,
  3589. extracut=extracut, startz=startz, endz=endz,
  3590. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3591. pp_geometry_name=pp_geometry_name,
  3592. tool_no=tool_cnt)
  3593. if res == 'fail':
  3594. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3595. return 'fail'
  3596. else:
  3597. dia_cnc_dict['gcode'] = res
  3598. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3599. # TODO this serve for bounding box creation only; should be optimized
  3600. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3601. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3602. # object is the source of gcode
  3603. job_obj.toolchange_xy_type = "geometry"
  3604. app_obj.progress.emit(80)
  3605. job_obj.cnc_tools.update({
  3606. tooluid_key: copy.deepcopy(dia_cnc_dict)
  3607. })
  3608. dia_cnc_dict.clear()
  3609. if use_thread:
  3610. # To be run in separate thread
  3611. # The idea is that if there is a solid_geometry in the file "root" then most likely thare are no
  3612. # separate solid_geometry in the self.tools dictionary
  3613. def job_thread(app_obj):
  3614. if self.solid_geometry:
  3615. with self.app.proc_container.new("Generating CNC Code"):
  3616. if app_obj.new_object("cncjob", outname, job_init_single_geometry) != 'fail':
  3617. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  3618. app_obj.progress.emit(100)
  3619. else:
  3620. with self.app.proc_container.new("Generating CNC Code"):
  3621. if app_obj.new_object("cncjob", outname, job_init_multi_geometry) != 'fail':
  3622. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  3623. app_obj.progress.emit(100)
  3624. # Create a promise with the name
  3625. self.app.collection.promise(outname)
  3626. # Send to worker
  3627. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3628. else:
  3629. if self.solid_geometry:
  3630. self.app.new_object("cncjob", outname, job_init_single_geometry)
  3631. else:
  3632. self.app.new_object("cncjob", outname, job_init_multi_geometry)
  3633. def generatecncjob(self, outname=None,
  3634. tooldia=None, offset=None,
  3635. z_cut=None, z_move=None,
  3636. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  3637. spindlespeed=None, dwell=None, dwelltime=None,
  3638. multidepth=None, depthperpass=None,
  3639. toolchange=None, toolchangez=None, toolchangexy=None,
  3640. extracut=None, startz=None, endz=None,
  3641. ppname_g=None,
  3642. segx=None,
  3643. segy=None,
  3644. use_thread=True):
  3645. """
  3646. Only used for TCL Command.
  3647. Creates a CNCJob out of this Geometry object. The actual
  3648. work is done by the target FlatCAMCNCjob object's
  3649. `generate_from_geometry_2()` method.
  3650. :param z_cut: Cut depth (negative)
  3651. :param z_move: Hight of the tool when travelling (not cutting)
  3652. :param feedrate: Feed rate while cutting on X - Y plane
  3653. :param feedrate_z: Feed rate while cutting on Z plane
  3654. :param feedrate_rapid: Feed rate while moving with rapids
  3655. :param tooldia: Tool diameter
  3656. :param outname: Name of the new object
  3657. :param spindlespeed: Spindle speed (RPM)
  3658. :param ppname_g Name of the postprocessor
  3659. :return: None
  3660. """
  3661. tooldia = tooldia if tooldia else float(self.options["cnctooldia"])
  3662. outname = outname if outname is not None else self.options["name"]
  3663. z_cut = z_cut if z_cut is not None else float(self.options["cutz"])
  3664. z_move = z_move if z_move is not None else float(self.options["travelz"])
  3665. feedrate = feedrate if feedrate is not None else float(self.options["feedrate"])
  3666. feedrate_z = feedrate_z if feedrate_z is not None else float(self.options["feedrate_z"])
  3667. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else float(self.options["feedrate_rapid"])
  3668. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  3669. depthperpass = depthperpass if depthperpass is not None else float(self.options["depthperpass"])
  3670. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  3671. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  3672. extracut = extracut if extracut is not None else float(self.options["extracut"])
  3673. startz = startz if startz is not None else self.options["startz"]
  3674. endz = endz if endz is not None else float(self.options["endz"])
  3675. toolchangez = toolchangez if toolchangez else float(self.options["toolchangez"])
  3676. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  3677. toolchange = toolchange if toolchange else self.options["toolchange"]
  3678. offset = offset if offset else 0.0
  3679. # int or None.
  3680. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  3681. dwell = dwell if dwell else self.options["dwell"]
  3682. dwelltime = dwelltime if dwelltime else float(self.options["dwelltime"])
  3683. ppname_g = ppname_g if ppname_g else self.options["ppname_g"]
  3684. # Object initialization function for app.new_object()
  3685. # RUNNING ON SEPARATE THREAD!
  3686. def job_init(job_obj, app_obj):
  3687. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3688. # Propagate options
  3689. job_obj.options["tooldia"] = tooldia
  3690. app_obj.progress.emit(20)
  3691. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3692. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3693. app_obj.progress.emit(40)
  3694. job_obj.options['type'] = 'Geometry'
  3695. job_obj.options['tool_dia'] = tooldia
  3696. job_obj.segx = segx
  3697. job_obj.segy = segy
  3698. try:
  3699. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3700. except ValueError:
  3701. # try to convert comma to decimal point. if it's still not working error message and return
  3702. try:
  3703. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3704. except ValueError:
  3705. self.app.inform.emit(
  3706. '[ERROR_NOTCL]Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]')
  3707. try:
  3708. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3709. except ValueError:
  3710. # try to convert comma to decimal point. if it's still not working error message and return
  3711. try:
  3712. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3713. except ValueError:
  3714. self.app.inform.emit(
  3715. '[ERROR_NOTCL]Wrong value format for self.defaults["feedrate_probe"] '
  3716. 'or self.options["feedrate_probe"]')
  3717. # TODO: The tolerance should not be hard coded. Just for testing.
  3718. job_obj.generate_from_geometry_2(self, tooldia=tooldia, offset=offset, tolerance=0.0005,
  3719. z_cut=z_cut, z_move=z_move,
  3720. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3721. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  3722. multidepth=multidepth, depthpercut=depthperpass,
  3723. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3724. extracut=extracut, startz=startz, endz=endz,
  3725. pp_geometry_name=ppname_g
  3726. )
  3727. app_obj.progress.emit(50)
  3728. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  3729. # source of gcode
  3730. job_obj.toolchange_xy_type = "geometry"
  3731. job_obj.gcode_parse()
  3732. app_obj.progress.emit(80)
  3733. if use_thread:
  3734. # To be run in separate thread
  3735. def job_thread(app_obj):
  3736. with self.app.proc_container.new("Generating CNC Code"):
  3737. app_obj.new_object("cncjob", outname, job_init)
  3738. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  3739. app_obj.progress.emit(100)
  3740. # Create a promise with the name
  3741. self.app.collection.promise(outname)
  3742. # Send to worker
  3743. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3744. else:
  3745. self.app.new_object("cncjob", outname, job_init)
  3746. # def on_plot_cb_click(self, *args): # TODO: args not needed
  3747. # if self.muted_ui:
  3748. # return
  3749. # self.read_form_item('plot')
  3750. def scale(self, xfactor, yfactor=None, point=None):
  3751. """
  3752. Scales all geometry by a given factor.
  3753. :param xfactor: Factor by which to scale the object's geometry/
  3754. :type xfactor: float
  3755. :param yfactor: Factor by which to scale the object's geometry/
  3756. :type yfactor: float
  3757. :return: None
  3758. :rtype: None
  3759. """
  3760. try:
  3761. xfactor = float(xfactor)
  3762. except:
  3763. self.app.inform.emit("[ERROR_NOTCL] Scale factor has to be a number: integer or float.")
  3764. return
  3765. if yfactor is None:
  3766. yfactor = xfactor
  3767. else:
  3768. try:
  3769. yfactor = float(yfactor)
  3770. except:
  3771. self.app.inform.emit("[ERROR_NOTCL] Scale factor has to be a number: integer or float.")
  3772. return
  3773. if point is None:
  3774. px = 0
  3775. py = 0
  3776. else:
  3777. px, py = point
  3778. # if type(self.solid_geometry) == list:
  3779. # geo_list = self.flatten(self.solid_geometry)
  3780. # self.solid_geometry = []
  3781. # # for g in geo_list:
  3782. # # self.solid_geometry.append(affinity.scale(g, xfactor, yfactor, origin=(px, py)))
  3783. # self.solid_geometry = [affinity.scale(g, xfactor, yfactor, origin=(px, py))
  3784. # for g in geo_list]
  3785. # else:
  3786. # self.solid_geometry = affinity.scale(self.solid_geometry, xfactor, yfactor,
  3787. # origin=(px, py))
  3788. # self.app.inform.emit("[success]Geometry Scale done.")
  3789. def scale_recursion(geom):
  3790. if type(geom) == list:
  3791. geoms=list()
  3792. for local_geom in geom:
  3793. geoms.append(scale_recursion(local_geom))
  3794. return geoms
  3795. else:
  3796. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  3797. if self.multigeo is True:
  3798. for tool in self.tools:
  3799. self.tools[tool]['solid_geometry'] = scale_recursion(self.tools[tool]['solid_geometry'])
  3800. else:
  3801. self.solid_geometry=scale_recursion(self.solid_geometry)
  3802. self.app.inform.emit("[success]Geometry Scale done.")
  3803. def offset(self, vect):
  3804. """
  3805. Offsets all geometry by a given vector/
  3806. :param vect: (x, y) vector by which to offset the object's geometry.
  3807. :type vect: tuple
  3808. :return: None
  3809. :rtype: None
  3810. """
  3811. try:
  3812. dx, dy = vect
  3813. except TypeError:
  3814. self.app.inform.emit("[ERROR_NOTCL]An (x,y) pair of values are needed. "
  3815. "Probable you entered only one value in the Offset field.")
  3816. return
  3817. def translate_recursion(geom):
  3818. if type(geom) == list:
  3819. geoms=list()
  3820. for local_geom in geom:
  3821. geoms.append(translate_recursion(local_geom))
  3822. return geoms
  3823. else:
  3824. return affinity.translate(geom, xoff=dx, yoff=dy)
  3825. if self.multigeo is True:
  3826. for tool in self.tools:
  3827. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  3828. else:
  3829. self.solid_geometry=translate_recursion(self.solid_geometry)
  3830. self.app.inform.emit("[success]Geometry Offset done.")
  3831. def convert_units(self, units):
  3832. self.ui_disconnect()
  3833. factor = Geometry.convert_units(self, units)
  3834. self.options['cutz'] = float(self.options['cutz']) * factor
  3835. self.options['depthperpass'] = float(self.options['depthperpass']) * factor
  3836. self.options['travelz'] = float(self.options['travelz']) * factor
  3837. self.options['feedrate'] = float(self.options['feedrate']) * factor
  3838. self.options['feedrate_z'] = float(self.options['feedrate_z']) * factor
  3839. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  3840. self.options['endz'] = float(self.options['endz']) * factor
  3841. # self.options['cnctooldia'] *= factor
  3842. # self.options['painttooldia'] *= factor
  3843. # self.options['paintmargin'] *= factor
  3844. # self.options['paintoverlap'] *= factor
  3845. self.options["toolchangez"] = float(self.options["toolchangez"]) * factor
  3846. if self.app.defaults["geometry_toolchangexy"] == '':
  3847. self.options['toolchangexy'] = "0.0, 0.0"
  3848. else:
  3849. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  3850. if len(coords_xy) < 2:
  3851. self.app.inform.emit("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  3852. "in the format (x, y) \nbut now there is only one value, not two. ")
  3853. return 'fail'
  3854. coords_xy[0] *= factor
  3855. coords_xy[1] *= factor
  3856. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3857. if self.options['startz'] is not None:
  3858. self.options['startz'] = float(self.options['startz']) * factor
  3859. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  3860. 'endz', 'toolchangez']
  3861. if isinstance(self, FlatCAMGeometry):
  3862. temp_tools_dict = {}
  3863. tool_dia_copy = {}
  3864. data_copy = {}
  3865. for tooluid_key, tooluid_value in self.tools.items():
  3866. for dia_key, dia_value in tooluid_value.items():
  3867. if dia_key == 'tooldia':
  3868. dia_value *= factor
  3869. dia_value = float('%.4f' % dia_value)
  3870. tool_dia_copy[dia_key] = dia_value
  3871. if dia_key == 'offset':
  3872. tool_dia_copy[dia_key] = dia_value
  3873. if dia_key == 'offset_value':
  3874. dia_value *= factor
  3875. tool_dia_copy[dia_key] = dia_value
  3876. # convert the value in the Custom Tool Offset entry in UI
  3877. custom_offset = None
  3878. try:
  3879. custom_offset = float(self.ui.tool_offset_entry.get_value())
  3880. except ValueError:
  3881. # try to convert comma to decimal point. if it's still not working error message and return
  3882. try:
  3883. custom_offset = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3884. )
  3885. except ValueError:
  3886. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  3887. "use a number.")
  3888. return
  3889. except TypeError:
  3890. pass
  3891. if custom_offset:
  3892. custom_offset *= factor
  3893. self.ui.tool_offset_entry.set_value(custom_offset)
  3894. if dia_key == 'type':
  3895. tool_dia_copy[dia_key] = dia_value
  3896. if dia_key == 'tool_type':
  3897. tool_dia_copy[dia_key] = dia_value
  3898. if dia_key == 'data':
  3899. for data_key, data_value in dia_value.items():
  3900. # convert the form fields that are convertible
  3901. for param in param_list:
  3902. if data_key == param and data_value is not None:
  3903. data_copy[data_key] = data_value * factor
  3904. # copy the other dict entries that are not convertible
  3905. if data_key not in param_list:
  3906. data_copy[data_key] = data_value
  3907. tool_dia_copy[dia_key] = copy.deepcopy(data_copy)
  3908. data_copy.clear()
  3909. temp_tools_dict.update({
  3910. tooluid_key: copy.deepcopy(tool_dia_copy)
  3911. })
  3912. tool_dia_copy.clear()
  3913. self.tools.clear()
  3914. self.tools = copy.deepcopy(temp_tools_dict)
  3915. # if there is a value in the new tool field then convert that one too
  3916. tooldia = self.ui.addtool_entry.get_value()
  3917. if tooldia:
  3918. tooldia *= factor
  3919. # limit the decimals to 2 for METRIC and 3 for INCH
  3920. if units.lower() == 'in':
  3921. tooldia = float('%.4f' % tooldia)
  3922. else:
  3923. tooldia = float('%.2f' % tooldia)
  3924. self.ui.addtool_entry.set_value(tooldia)
  3925. return factor
  3926. def plot_element(self, element, color='red', visible=None):
  3927. visible = visible if visible else self.options['plot']
  3928. try:
  3929. for sub_el in element:
  3930. self.plot_element(sub_el)
  3931. except TypeError: # Element is not iterable...
  3932. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  3933. def plot(self, visible=None):
  3934. """
  3935. Adds the object into collection.
  3936. :return: None
  3937. """
  3938. # Does all the required setup and returns False
  3939. # if the 'ptint' option is set to False.
  3940. if not FlatCAMObj.plot(self):
  3941. return
  3942. try:
  3943. # plot solid geometries found as members of self.tools attribute dict
  3944. # for MultiGeo
  3945. if self.multigeo == True: # geo multi tool usage
  3946. for tooluid_key in self.tools:
  3947. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  3948. self.plot_element(solid_geometry, visible=visible)
  3949. # plot solid geometry that may be an direct attribute of the geometry object
  3950. # for SingleGeo
  3951. if self.solid_geometry:
  3952. self.plot_element(self.solid_geometry, visible=visible)
  3953. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  3954. self.shapes.redraw()
  3955. except (ObjectDeleted, AttributeError):
  3956. self.shapes.clear(update=True)
  3957. def on_plot_cb_click(self, *args):
  3958. if self.muted_ui:
  3959. return
  3960. self.plot()
  3961. self.read_form_item('plot')
  3962. self.ui_disconnect()
  3963. cb_flag = self.ui.plot_cb.isChecked()
  3964. for row in range(self.ui.geo_tools_table.rowCount()):
  3965. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  3966. if cb_flag:
  3967. table_cb.setChecked(True)
  3968. else:
  3969. table_cb.setChecked(False)
  3970. self.ui_connect()
  3971. def on_plot_cb_click_table(self):
  3972. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  3973. self.ui_disconnect()
  3974. cw = self.sender()
  3975. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  3976. cw_row = cw_index.row()
  3977. check_row = 0
  3978. self.shapes.clear(update=True)
  3979. for tooluid_key in self.tools:
  3980. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  3981. # find the geo_tool_table row associated with the tooluid_key
  3982. for row in range(self.ui.geo_tools_table.rowCount()):
  3983. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  3984. if tooluid_item == int(tooluid_key):
  3985. check_row = row
  3986. break
  3987. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  3988. self.plot_element(element=solid_geometry, visible=True)
  3989. self.shapes.redraw()
  3990. # make sure that the general plot is disabled if one of the row plot's are disabled and
  3991. # if all the row plot's are enabled also enable the general plot checkbox
  3992. cb_cnt = 0
  3993. total_row = self.ui.geo_tools_table.rowCount()
  3994. for row in range(total_row):
  3995. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  3996. cb_cnt += 1
  3997. else:
  3998. cb_cnt -= 1
  3999. if cb_cnt < total_row:
  4000. self.ui.plot_cb.setChecked(False)
  4001. else:
  4002. self.ui.plot_cb.setChecked(True)
  4003. self.ui_connect()
  4004. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  4005. """
  4006. Represents G-Code.
  4007. """
  4008. optionChanged = QtCore.pyqtSignal(str)
  4009. ui_type = CNCObjectUI
  4010. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  4011. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  4012. spindlespeed=None):
  4013. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  4014. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  4015. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  4016. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  4017. FlatCAMObj.__init__(self, name)
  4018. self.kind = "cncjob"
  4019. self.options.update({
  4020. "plot": True,
  4021. "tooldia": 0.03937, # 0.4mm in inches
  4022. "append": "",
  4023. "prepend": "",
  4024. "dwell": False,
  4025. "dwelltime": 1,
  4026. "type": 'Geometry',
  4027. "toolchange_macro": '',
  4028. "toolchange_macro_enable": False
  4029. })
  4030. '''
  4031. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  4032. diameter of the tools and the value is another dict that will hold the data under the following form:
  4033. {tooldia: {
  4034. 'tooluid': 1,
  4035. 'offset': 'Path',
  4036. 'type_item': 'Rough',
  4037. 'tool_type': 'C1',
  4038. 'data': {} # a dict to hold the parameters
  4039. 'gcode': "" # a string with the actual GCODE
  4040. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  4041. 'solid_geometry': []
  4042. },
  4043. ...
  4044. }
  4045. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  4046. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  4047. '''
  4048. self.cnc_tools = {}
  4049. '''
  4050. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  4051. diameter of the tools and the value is another dict that will hold the data under the following form:
  4052. {tooldia: {
  4053. 'tool': int,
  4054. 'nr_drills': int,
  4055. 'nr_slots': int,
  4056. 'offset': float,
  4057. 'data': {} # a dict to hold the parameters
  4058. 'gcode': "" # a string with the actual GCODE
  4059. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  4060. 'solid_geometry': []
  4061. },
  4062. ...
  4063. }
  4064. It is populated in the FlatCAMExcellon.on_create_cncjob_click() but actually
  4065. it's done in camlib.Excellon.generate_from_excellon_by_tool()
  4066. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  4067. '''
  4068. self.exc_cnc_tools = {}
  4069. # flag to store if the CNCJob is part of a special group of CNCJob objects that can't be processed by the
  4070. # default engine of FlatCAM. They generated by some of tools and are special cases of CNCJob objects.
  4071. self. special_group = None
  4072. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  4073. # (like the one in the TCL Command), False
  4074. self.multitool = False
  4075. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  4076. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  4077. self.g_x_re = re.compile(gcodex_re_string)
  4078. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  4079. self.g_y_re = re.compile(gcodey_re_string)
  4080. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  4081. self.g_z_re = re.compile(gcodez_re_string)
  4082. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  4083. self.g_f_re = re.compile(gcodef_re_string)
  4084. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  4085. self.g_t_re = re.compile(gcodet_re_string)
  4086. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  4087. self.g_nr_re = re.compile(gcodenr_re_string)
  4088. # Attributes to be included in serialization
  4089. # Always append to it because it carries contents
  4090. # from predecessors.
  4091. self.ser_attrs += ['options', 'kind', 'cnc_tools', 'multitool']
  4092. self.annotation = self.app.plotcanvas.new_text_group()
  4093. def build_ui(self):
  4094. self.ui_disconnect()
  4095. FlatCAMObj.build_ui(self)
  4096. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  4097. if self.cnc_tools:
  4098. self.ui.cnc_tools_table.show()
  4099. else:
  4100. self.ui.cnc_tools_table.hide()
  4101. offset = 0
  4102. tool_idx = 0
  4103. n = len(self.cnc_tools)
  4104. self.ui.cnc_tools_table.setRowCount(n)
  4105. for dia_key, dia_value in self.cnc_tools.items():
  4106. tool_idx += 1
  4107. row_no = tool_idx - 1
  4108. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  4109. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  4110. self.ui.cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  4111. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  4112. # There are no tool bits in MM with more than 2 decimals diameter.
  4113. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  4114. if self.units == 'MM':
  4115. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(dia_value['tooldia']))
  4116. else:
  4117. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(dia_value['tooldia']))
  4118. offset_txt = list(str(dia_value['offset']))
  4119. offset_txt[0] = offset_txt[0].upper()
  4120. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  4121. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  4122. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  4123. id.setFlags(QtCore.Qt.ItemIsEnabled)
  4124. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4125. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4126. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4127. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4128. # hack so the checkbox stay centered in the table cell
  4129. # used this:
  4130. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  4131. # plot_item = QtWidgets.QWidget()
  4132. # checkbox = FCCheckBox()
  4133. # checkbox.setCheckState(QtCore.Qt.Checked)
  4134. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  4135. # qhboxlayout.addWidget(checkbox)
  4136. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  4137. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  4138. plot_item = FCCheckBox()
  4139. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  4140. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  4141. if self.ui.plot_cb.isChecked():
  4142. plot_item.setChecked(True)
  4143. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  4144. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  4145. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  4146. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  4147. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  4148. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  4149. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  4150. # make the diameter column editable
  4151. # for row in range(tool_idx):
  4152. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  4153. # QtCore.Qt.ItemIsEnabled)
  4154. for row in range(tool_idx):
  4155. self.ui.cnc_tools_table.item(row, 0).setFlags(
  4156. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  4157. self.ui.cnc_tools_table.resizeColumnsToContents()
  4158. self.ui.cnc_tools_table.resizeRowsToContents()
  4159. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  4160. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  4161. vertical_header.hide()
  4162. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4163. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  4164. horizontal_header.setMinimumSectionSize(10)
  4165. horizontal_header.setDefaultSectionSize(70)
  4166. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  4167. horizontal_header.resizeSection(0, 20)
  4168. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  4169. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  4170. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  4171. horizontal_header.resizeSection(4, 40)
  4172. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  4173. horizontal_header.resizeSection(4, 17)
  4174. # horizontal_header.setStretchLastSection(True)
  4175. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4176. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  4177. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  4178. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  4179. # self.ui.geo_tools_table.setSortingEnabled(True)
  4180. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  4181. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  4182. self.ui_connect()
  4183. def set_ui(self, ui):
  4184. FlatCAMObj.set_ui(self, ui)
  4185. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  4186. assert isinstance(self.ui, CNCObjectUI), \
  4187. "Expected a CNCObjectUI, got %s" % type(self.ui)
  4188. self.form_fields.update({
  4189. "plot": self.ui.plot_cb,
  4190. # "tooldia": self.ui.tooldia_entry,
  4191. "append": self.ui.append_text,
  4192. "prepend": self.ui.prepend_text,
  4193. "toolchange_macro": self.ui.toolchange_text,
  4194. "toolchange_macro_enable": self.ui.toolchange_cb
  4195. })
  4196. # Fill form fields only on object create
  4197. self.to_form()
  4198. # this means that the object that created this CNCJob was an Excellon
  4199. try:
  4200. if self.travel_distance:
  4201. self.ui.t_distance_label.show()
  4202. self.ui.t_distance_entry.setVisible(True)
  4203. self.ui.t_distance_entry.setDisabled(True)
  4204. self.ui.t_distance_entry.set_value('%.4f' % float(self.travel_distance))
  4205. self.ui.units_label.setText(str(self.units).lower())
  4206. self.ui.units_label.setDisabled(True)
  4207. except AttributeError:
  4208. pass
  4209. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  4210. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  4211. # Show/Hide Advanced Options
  4212. if self.app.defaults["global_app_level"] == 'b':
  4213. self.ui.level.setText('<span style="color:green;"><b>Basic</b></span>')
  4214. self.ui.cnc_frame.hide()
  4215. else:
  4216. self.ui.level.setText('<span style="color:red;"><b>Advanced</b></span>')
  4217. self.ui.cnc_frame.show()
  4218. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  4219. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  4220. self.ui.modify_gcode_button.clicked.connect(self.on_modifygcode_button_click)
  4221. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  4222. def ui_connect(self):
  4223. for row in range(self.ui.cnc_tools_table.rowCount()):
  4224. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  4225. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  4226. def ui_disconnect(self):
  4227. for row in range(self.ui.cnc_tools_table.rowCount()):
  4228. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  4229. try:
  4230. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  4231. except:
  4232. pass
  4233. def on_updateplot_button_click(self, *args):
  4234. """
  4235. Callback for the "Updata Plot" button. Reads the form for updates
  4236. and plots the object.
  4237. """
  4238. self.read_form()
  4239. self.plot()
  4240. def on_plot_kind_change(self):
  4241. kind = self.ui.cncplot_method_combo.get_value()
  4242. self.plot(kind=kind)
  4243. def on_exportgcode_button_click(self, *args):
  4244. self.app.report_usage("cncjob_on_exportgcode_button")
  4245. self.read_form()
  4246. name = self.app.collection.get_active().options['name']
  4247. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4248. _filter_ = "RML1 Files (*.rol);;" \
  4249. "All Files (*.*)"
  4250. elif 'hpgl' in self.pp_geometry_name:
  4251. _filter_ = "HPGL Files (*.plt);;" \
  4252. "All Files (*.*)"
  4253. else:
  4254. _filter_ = "G-Code Files (*.nc);;G-Code Files (*.txt);;G-Code Files (*.tap);;G-Code Files (*.cnc);;" \
  4255. "G-Code Files (*.g-code);;All Files (*.*)"
  4256. try:
  4257. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  4258. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4259. caption="Export Machine Code ...",
  4260. directory=dir_file_to_save,
  4261. filter=_filter_
  4262. )
  4263. except TypeError:
  4264. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Machine Code ...", filter=_filter_)
  4265. filename = str(filename)
  4266. if filename == '':
  4267. self.app.inform.emit("[WARNING_NOTCL]Export Machine Code cancelled ...")
  4268. return
  4269. preamble = str(self.ui.prepend_text.get_value())
  4270. postamble = str(self.ui.append_text.get_value())
  4271. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  4272. if gc == 'fail':
  4273. return
  4274. self.app.file_saved.emit("gcode", filename)
  4275. self.app.inform.emit("[success] Machine Code file saved to: %s" % filename)
  4276. def on_modifygcode_button_click(self, *args):
  4277. preamble = str(self.ui.prepend_text.get_value())
  4278. postamble = str(self.ui.append_text.get_value())
  4279. gc = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  4280. if gc == 'fail':
  4281. return
  4282. else:
  4283. self.app.gcode_edited = gc
  4284. # add the tab if it was closed
  4285. self.app.ui.plot_tab_area.addTab(self.app.ui.cncjob_tab, "Code Editor")
  4286. # delete the absolute and relative position and messages in the infobar
  4287. self.app.ui.position_label.setText("")
  4288. self.app.ui.rel_position_label.setText("")
  4289. # Switch plot_area to CNCJob tab
  4290. self.app.ui.plot_tab_area.setCurrentWidget(self.app.ui.cncjob_tab)
  4291. # first clear previous text in text editor (if any)
  4292. self.app.ui.code_editor.clear()
  4293. # then append the text from GCode to the text editor
  4294. try:
  4295. for line in self.app.gcode_edited:
  4296. proc_line = str(line).strip('\n')
  4297. self.app.ui.code_editor.append(proc_line)
  4298. except Exception as e:
  4299. log.debug('FlatCAMCNNJob.on_modifygcode_button_click() -->%s' % str(e))
  4300. self.app.inform.emit('[ERROR]FlatCAMCNNJob.on_modifygcode_button_click() -->%s' % str(e))
  4301. return
  4302. self.app.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4303. self.app.handleTextChanged()
  4304. self.app.ui.show()
  4305. def gcode_header(self):
  4306. log.debug("FlatCAMCNCJob.gcode_header()")
  4307. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4308. marlin = False
  4309. hpgl = False
  4310. probe_pp = False
  4311. try:
  4312. for key in self.cnc_tools:
  4313. ppg = self.cnc_tools[key]['data']['ppname_g']
  4314. if ppg == 'marlin' or ppg == 'Repetier':
  4315. marlin = True
  4316. break
  4317. if ppg == 'hpgl':
  4318. hpgl = True
  4319. break
  4320. if "toolchange_probe" in ppg.lower():
  4321. probe_pp = True
  4322. break
  4323. except Exception as e:
  4324. log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  4325. try:
  4326. if self.options['ppname_e'] == 'marlin' or self.options['ppname_e'] == 'Repetier':
  4327. marlin = True
  4328. except Exception as e:
  4329. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4330. try:
  4331. if "toolchange_probe" in self.options['ppname_e'].lower():
  4332. probe_pp = True
  4333. except Exception as e:
  4334. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4335. if marlin is True:
  4336. gcode = ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4337. (str(self.app.version), str(self.app.version_date)) + '\n'
  4338. gcode += ';Name: ' + str(self.options['name']) + '\n'
  4339. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  4340. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4341. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4342. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  4343. gcode += ';Created on ' + time_str + '\n' + '\n'
  4344. elif hpgl is True:
  4345. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  4346. (str(self.app.version), str(self.app.version_date)) + '";\n'
  4347. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  4348. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  4349. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4350. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4351. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  4352. gcode += 'CO "Created on ' + time_str + '";\n'
  4353. elif probe_pp is True:
  4354. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4355. (str(self.app.version), str(self.app.version_date)) + '\n'
  4356. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  4357. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  4358. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  4359. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  4360. 'Then zero the Z axis.)\n' + '\n'
  4361. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4362. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4363. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4364. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4365. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4366. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4367. else:
  4368. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4369. (str(self.app.version), str(self.app.version_date)) + '\n'
  4370. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4371. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4372. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4373. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4374. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4375. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4376. return gcode
  4377. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  4378. gcode = ''
  4379. roland = False
  4380. hpgl = False
  4381. try:
  4382. if self.special_group:
  4383. self.app.inform.emit("[WARNING_NOTCL]This CNCJob object can't be processed because "
  4384. "it is a %s CNCJob object." % str(self.special_group))
  4385. return 'fail'
  4386. except AttributeError:
  4387. pass
  4388. # detect if using Roland postprocessor
  4389. try:
  4390. for key in self.cnc_tools:
  4391. if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  4392. roland = True
  4393. break
  4394. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  4395. hpgl = True
  4396. break
  4397. except:
  4398. try:
  4399. for key in self.cnc_tools:
  4400. if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  4401. roland = True
  4402. break
  4403. except:
  4404. pass
  4405. # do not add gcode_header when using the Roland postprocessor, add it for every other postprocessor
  4406. if roland is False and hpgl is False:
  4407. gcode = self.gcode_header()
  4408. # detect if using multi-tool and make the Gcode summation correctly for each case
  4409. if self.multitool is True:
  4410. for tooluid_key in self.cnc_tools:
  4411. for key, value in self.cnc_tools[tooluid_key].items():
  4412. if key == 'gcode':
  4413. gcode += value
  4414. break
  4415. else:
  4416. gcode += self.gcode
  4417. if roland is True:
  4418. g = preamble + gcode + postamble
  4419. elif hpgl is True:
  4420. g = self.gcode_header() + preamble + gcode + postamble
  4421. else:
  4422. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  4423. g_idx = gcode.rfind('G20')
  4424. # if it did not find 'G20' then search for 'G21'
  4425. if g_idx == -1:
  4426. g_idx = gcode.rfind('G21')
  4427. # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  4428. if g_idx == -1:
  4429. self.app.inform.emit("[ERROR_NOTCL] G-code does not have a units code: either G20 or G21")
  4430. return
  4431. g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble
  4432. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  4433. if self.ui.toolchange_cb.get_value() is True:
  4434. # match = self.re_toolchange.search(g)
  4435. if 'M6' in g:
  4436. m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  4437. g = g.replace('M6', m6_code)
  4438. # lines = StringIO(self.gcode)
  4439. lines = StringIO(g)
  4440. ## Write
  4441. if filename is not None:
  4442. try:
  4443. with open(filename, 'w') as f:
  4444. for line in lines:
  4445. f.write(line)
  4446. except FileNotFoundError:
  4447. self.app.inform.emit("[WARNING_NOTCL] No such file or directory")
  4448. return
  4449. elif to_file is False:
  4450. # Just for adding it to the recent files list.
  4451. self.app.file_opened.emit("cncjob", filename)
  4452. self.app.file_saved.emit("cncjob", filename)
  4453. self.app.inform.emit("[success] Saved to: " + filename)
  4454. else:
  4455. return lines
  4456. def get_gcode(self, preamble='', postamble=''):
  4457. #we need this to be able get_gcode separatelly for shell command export_gcode
  4458. return preamble + '\n' + self.gcode + "\n" + postamble
  4459. def get_svg(self):
  4460. # we need this to be able get_svg separately for shell command export_svg
  4461. pass
  4462. def on_plot_cb_click(self, *args):
  4463. if self.muted_ui:
  4464. return
  4465. kind = self.ui.cncplot_method_combo.get_value()
  4466. self.plot(kind=kind)
  4467. self.read_form_item('plot')
  4468. self.ui_disconnect()
  4469. cb_flag = self.ui.plot_cb.isChecked()
  4470. for row in range(self.ui.cnc_tools_table.rowCount()):
  4471. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  4472. if cb_flag:
  4473. table_cb.setChecked(True)
  4474. else:
  4475. table_cb.setChecked(False)
  4476. self.ui_connect()
  4477. def on_plot_cb_click_table(self):
  4478. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  4479. self.ui_disconnect()
  4480. cw = self.sender()
  4481. cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  4482. cw_row = cw_index.row()
  4483. kind = self.ui.cncplot_method_combo.get_value()
  4484. self.shapes.clear(update=True)
  4485. for tooluid_key in self.cnc_tools:
  4486. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4487. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4488. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  4489. for r in range(self.ui.cnc_tools_table.rowCount()):
  4490. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  4491. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  4492. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  4493. self.shapes.redraw()
  4494. # make sure that the general plot is disabled if one of the row plot's are disabled and
  4495. # if all the row plot's are enabled also enable the general plot checkbox
  4496. cb_cnt = 0
  4497. total_row = self.ui.cnc_tools_table.rowCount()
  4498. for row in range(total_row):
  4499. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  4500. cb_cnt += 1
  4501. else:
  4502. cb_cnt -= 1
  4503. if cb_cnt < total_row:
  4504. self.ui.plot_cb.setChecked(False)
  4505. else:
  4506. self.ui.plot_cb.setChecked(True)
  4507. self.ui_connect()
  4508. def plot(self, visible=None, kind='all'):
  4509. # Does all the required setup and returns False
  4510. # if the 'ptint' option is set to False.
  4511. if not FlatCAMObj.plot(self):
  4512. return
  4513. visible = visible if visible else self.options['plot']
  4514. try:
  4515. if self.multitool is False: # single tool usage
  4516. self.plot2(tooldia=float(self.options["tooldia"]), obj=self, visible=visible, kind=kind)
  4517. else:
  4518. # multiple tools usage
  4519. for tooluid_key in self.cnc_tools:
  4520. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4521. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4522. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  4523. self.shapes.redraw()
  4524. except (ObjectDeleted, AttributeError):
  4525. self.shapes.clear(update=True)
  4526. self.annotation.clear(update=True)
  4527. def convert_units(self, units):
  4528. factor = CNCjob.convert_units(self, units)
  4529. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  4530. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  4531. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  4532. 'endz', 'toolchangez']
  4533. temp_tools_dict = {}
  4534. tool_dia_copy = {}
  4535. data_copy = {}
  4536. for tooluid_key, tooluid_value in self.cnc_tools.items():
  4537. for dia_key, dia_value in tooluid_value.items():
  4538. if dia_key == 'tooldia':
  4539. dia_value *= factor
  4540. dia_value = float('%.4f' % dia_value)
  4541. tool_dia_copy[dia_key] = dia_value
  4542. if dia_key == 'offset':
  4543. tool_dia_copy[dia_key] = dia_value
  4544. if dia_key == 'offset_value':
  4545. dia_value *= factor
  4546. tool_dia_copy[dia_key] = dia_value
  4547. if dia_key == 'type':
  4548. tool_dia_copy[dia_key] = dia_value
  4549. if dia_key == 'tool_type':
  4550. tool_dia_copy[dia_key] = dia_value
  4551. if dia_key == 'data':
  4552. for data_key, data_value in dia_value.items():
  4553. # convert the form fields that are convertible
  4554. for param in param_list:
  4555. if data_key == param and data_value is not None:
  4556. data_copy[data_key] = data_value * factor
  4557. # copy the other dict entries that are not convertible
  4558. if data_key not in param_list:
  4559. data_copy[data_key] = data_value
  4560. tool_dia_copy[dia_key] = copy.deepcopy(data_copy)
  4561. data_copy.clear()
  4562. if dia_key == 'gcode':
  4563. tool_dia_copy[dia_key] = dia_value
  4564. if dia_key == 'gcode_parsed':
  4565. tool_dia_copy[dia_key] = dia_value
  4566. if dia_key == 'solid_geometry':
  4567. tool_dia_copy[dia_key] = dia_value
  4568. # if dia_key == 'solid_geometry':
  4569. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  4570. # if dia_key == 'gcode_parsed':
  4571. # for g in dia_value:
  4572. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  4573. #
  4574. # tool_dia_copy['gcode_parsed'] = copy.deepcopy(dia_value)
  4575. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  4576. temp_tools_dict.update({
  4577. tooluid_key: copy.deepcopy(tool_dia_copy)
  4578. })
  4579. tool_dia_copy.clear()
  4580. self.cnc_tools.clear()
  4581. self.cnc_tools = copy.deepcopy(temp_tools_dict)
  4582. # end of file