FlatCAMObj.py 203 KB

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