FlatCAMObj.py 163 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085
  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. from copy import copy, deepcopy
  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(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. # Expand lists
  291. if type(grb) is list:
  292. FlatCAMGerber.merge(grb, grb_final)
  293. # If not list, just append
  294. else:
  295. grb_final.solid_geometry.append(grb.solid_geometry)
  296. def __init__(self, name):
  297. Gerber.__init__(self, steps_per_circle=self.app.defaults["gerber_circle_steps"])
  298. FlatCAMObj.__init__(self, name)
  299. self.kind = "gerber"
  300. # The 'name' is already in self.options from FlatCAMObj
  301. # Automatically updates the UI
  302. self.options.update({
  303. "plot": True,
  304. "multicolored": False,
  305. "solid": False,
  306. "isotooldia": 0.016,
  307. "isopasses": 1,
  308. "isooverlap": 0.15,
  309. "milling_type": "cl",
  310. "combine_passes": True,
  311. "ncctools": "1.0, 0.5",
  312. "nccoverlap": 0.4,
  313. "nccmargin": 1,
  314. "noncoppermargin": 0.0,
  315. "noncopperrounded": False,
  316. "bboxmargin": 0.0,
  317. "bboxrounded": False
  318. })
  319. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  320. self.iso_type = 2
  321. # Attributes to be included in serialization
  322. # Always append to it because it carries contents
  323. # from predecessors.
  324. self.ser_attrs += ['options', 'kind']
  325. self.multigeo = False
  326. # assert isinstance(self.ui, GerberObjectUI)
  327. # self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  328. # self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  329. # self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  330. # self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  331. # self.ui.generate_cutout_button.clicked.connect(self.on_generatecutout_button_click)
  332. # self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  333. # self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  334. def set_ui(self, ui):
  335. """
  336. Maps options with GUI inputs.
  337. Connects GUI events to methods.
  338. :param ui: GUI object.
  339. :type ui: GerberObjectUI
  340. :return: None
  341. """
  342. FlatCAMObj.set_ui(self, ui)
  343. FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
  344. self.form_fields.update({
  345. "plot": self.ui.plot_cb,
  346. "multicolored": self.ui.multicolored_cb,
  347. "solid": self.ui.solid_cb,
  348. "isotooldia": self.ui.iso_tool_dia_entry,
  349. "isopasses": self.ui.iso_width_entry,
  350. "isooverlap": self.ui.iso_overlap_entry,
  351. "milling_type": self.ui.milling_type_radio,
  352. "combine_passes": self.ui.combine_passes_cb,
  353. "noncoppermargin": self.ui.noncopper_margin_entry,
  354. "noncopperrounded": self.ui.noncopper_rounded_cb,
  355. "bboxmargin": self.ui.bbmargin_entry,
  356. "bboxrounded": self.ui.bbrounded_cb
  357. })
  358. # Fill form fields only on object create
  359. self.to_form()
  360. assert isinstance(self.ui, GerberObjectUI)
  361. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  362. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  363. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  364. self.ui.generate_ext_iso_button.clicked.connect(self.on_ext_iso_button_click)
  365. self.ui.generate_int_iso_button.clicked.connect(self.on_int_iso_button_click)
  366. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  367. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  368. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  369. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  370. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  371. def on_generatenoncopper_button_click(self, *args):
  372. self.app.report_usage("gerber_on_generatenoncopper_button")
  373. self.read_form()
  374. name = self.options["name"] + "_noncopper"
  375. def geo_init(geo_obj, app_obj):
  376. assert isinstance(geo_obj, FlatCAMGeometry)
  377. bounding_box = self.solid_geometry.envelope.buffer(self.options["noncoppermargin"])
  378. if not self.options["noncopperrounded"]:
  379. bounding_box = bounding_box.envelope
  380. non_copper = bounding_box.difference(self.solid_geometry)
  381. geo_obj.solid_geometry = non_copper
  382. # TODO: Check for None
  383. self.app.new_object("geometry", name, geo_init)
  384. def on_generatebb_button_click(self, *args):
  385. self.app.report_usage("gerber_on_generatebb_button")
  386. self.read_form()
  387. name = self.options["name"] + "_bbox"
  388. def geo_init(geo_obj, app_obj):
  389. assert isinstance(geo_obj, FlatCAMGeometry)
  390. # Bounding box with rounded corners
  391. bounding_box = self.solid_geometry.envelope.buffer(self.options["bboxmargin"])
  392. if not self.options["bboxrounded"]: # Remove rounded corners
  393. bounding_box = bounding_box.envelope
  394. geo_obj.solid_geometry = bounding_box
  395. self.app.new_object("geometry", name, geo_init)
  396. def on_ext_iso_button_click(self, *args):
  397. if self.ui.follow_cb.get_value() == True:
  398. obj = self.app.collection.get_active()
  399. obj.follow()
  400. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  401. obj.ui.plot_cb.toggle()
  402. else:
  403. self.app.report_usage("gerber_on_iso_button")
  404. self.read_form()
  405. self.isolate(iso_type=0)
  406. def on_int_iso_button_click(self, *args):
  407. if self.ui.follow_cb.get_value() == True:
  408. obj = self.app.collection.get_active()
  409. obj.follow()
  410. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  411. obj.ui.plot_cb.toggle()
  412. else:
  413. self.app.report_usage("gerber_on_iso_button")
  414. self.read_form()
  415. self.isolate(iso_type=1)
  416. def on_iso_button_click(self, *args):
  417. if self.ui.follow_cb.get_value() == True:
  418. obj = self.app.collection.get_active()
  419. obj.follow()
  420. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  421. obj.ui.plot_cb.toggle()
  422. else:
  423. self.app.report_usage("gerber_on_iso_button")
  424. self.read_form()
  425. self.isolate()
  426. def follow(self, outname=None):
  427. """
  428. Creates a geometry object "following" the gerber paths.
  429. :return: None
  430. """
  431. # default_name = self.options["name"] + "_follow"
  432. # follow_name = outname or default_name
  433. if outname is None:
  434. follow_name = self.options["name"] + "_follow"
  435. else:
  436. follow_name = outname
  437. def follow_init(follow_obj, app):
  438. # Propagate options
  439. follow_obj.options["cnctooldia"] = self.options["isotooldia"]
  440. follow_obj.solid_geometry = self.solid_geometry
  441. # TODO: Do something if this is None. Offer changing name?
  442. try:
  443. self.app.new_object("geometry", follow_name, follow_init)
  444. except Exception as e:
  445. return "Operation failed: %s" % str(e)
  446. def isolate(self, iso_type=None, dia=None, passes=None, overlap=None,
  447. outname=None, combine=None, milling_type=None):
  448. """
  449. Creates an isolation routing geometry object in the project.
  450. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  451. :param dia: Tool diameter
  452. :param passes: Number of tool widths to cut
  453. :param overlap: Overlap between passes in fraction of tool diameter
  454. :param outname: Base name of the output object
  455. :return: None
  456. """
  457. if dia is None:
  458. dia = self.options["isotooldia"]
  459. if passes is None:
  460. passes = int(self.options["isopasses"])
  461. if overlap is None:
  462. overlap = self.options["isooverlap"]
  463. if combine is None:
  464. combine = self.options["combine_passes"]
  465. else:
  466. combine = bool(combine)
  467. if milling_type is None:
  468. milling_type = self.options["milling_type"]
  469. if iso_type is None:
  470. self.iso_type = 2
  471. else:
  472. self.iso_type = iso_type
  473. base_name = self.options["name"] + "_iso"
  474. base_name = outname or base_name
  475. def generate_envelope(offset, invert, envelope_iso_type=2):
  476. # isolation_geometry produces an envelope that is going on the left of the geometry
  477. # (the copper features). To leave the least amount of burrs on the features
  478. # the tool needs to travel on the right side of the features (this is called conventional milling)
  479. # the first pass is the one cutting all of the features, so it needs to be reversed
  480. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  481. # to cut on the right side of the left over copper i.e on the left side of the features.
  482. try:
  483. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type)
  484. except Exception as e:
  485. log.debug(str(e))
  486. return 'fail'
  487. if invert:
  488. try:
  489. if type(geom) is MultiPolygon:
  490. pl = []
  491. for p in geom:
  492. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  493. geom = MultiPolygon(pl)
  494. elif type(geom) is Polygon:
  495. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  496. else:
  497. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> Unexpected Geometry")
  498. except Exception as e:
  499. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> %s" % str(e))
  500. return geom
  501. if combine:
  502. if self.iso_type == 0:
  503. iso_name = self.options["name"] + "_ext_iso"
  504. elif self.iso_type == 1:
  505. iso_name = self.options["name"] + "_int_iso"
  506. else:
  507. iso_name = base_name
  508. # TODO: This is ugly. Create way to pass data into init function.
  509. def iso_init(geo_obj, app_obj):
  510. # Propagate options
  511. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  512. geo_obj.solid_geometry = []
  513. for i in range(passes):
  514. iso_offset = (((2 * i + 1) / 2.0) * dia) - (i * overlap * dia)
  515. # if milling type is climb then the move is counter-clockwise around features
  516. if milling_type == 'cl':
  517. # geom = generate_envelope (offset, i == 0)
  518. geom = generate_envelope(iso_offset, 1, envelope_iso_type=self.iso_type)
  519. else:
  520. geom = generate_envelope(iso_offset, 0, envelope_iso_type=self.iso_type)
  521. geo_obj.solid_geometry.append(geom)
  522. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  523. # or just looking in the lists (they are one level depth) and if any is not empty
  524. # proceed with object creation, if there are empty and the number of them is the length
  525. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  526. empty_cnt = 0
  527. if not isinstance(geo_obj.solid_geometry, list):
  528. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  529. for g in geo_obj.solid_geometry:
  530. if g:
  531. app_obj.inform.emit("[success]Isolation geometry created: %s" % geo_obj.options["name"])
  532. break
  533. else:
  534. empty_cnt += 1
  535. if empty_cnt == len(geo_obj.solid_geometry):
  536. raise ValidationError("Empty Geometry", None)
  537. geo_obj.multigeo = False
  538. # TODO: Do something if this is None. Offer changing name?
  539. self.app.new_object("geometry", iso_name, iso_init)
  540. else:
  541. for i in range(passes):
  542. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  543. if passes > 1:
  544. if self.iso_type == 0:
  545. iso_name = self.options["name"] + "_ext_iso" + str(i + 1)
  546. elif self.iso_type == 1:
  547. iso_name = self.options["name"] + "_int_iso" + str(i + 1)
  548. else:
  549. iso_name = base_name + str(i + 1)
  550. else:
  551. if self.iso_type == 0:
  552. iso_name = self.options["name"] + "_ext_iso"
  553. elif self.iso_type == 1:
  554. iso_name = self.options["name"] + "_int_iso"
  555. else:
  556. iso_name = base_name
  557. # TODO: This is ugly. Create way to pass data into init function.
  558. def iso_init(geo_obj, app_obj):
  559. # Propagate options
  560. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  561. # if milling type is climb then the move is counter-clockwise around features
  562. if milling_type == 'cl':
  563. # geo_obj.solid_geometry = generate_envelope(offset, i == 0)
  564. geo_obj.solid_geometry = generate_envelope(offset, 1, envelope_iso_type=self.iso_type)
  565. else:
  566. geo_obj.solid_geometry = generate_envelope(offset, 0, envelope_iso_type=self.iso_type)
  567. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  568. # or just looking in the lists (they are one level depth) and if any is not empty
  569. # proceed with object creation, if there are empty and the number of them is the length
  570. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  571. empty_cnt = 0
  572. if not isinstance(geo_obj.solid_geometry, list):
  573. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  574. for g in geo_obj.solid_geometry:
  575. if g:
  576. app_obj.inform.emit("[success]Isolation geometry created: %s" % geo_obj.options["name"])
  577. break
  578. else:
  579. empty_cnt += 1
  580. if empty_cnt == len(geo_obj.solid_geometry):
  581. raise ValidationError("Empty Geometry", None)
  582. geo_obj.multigeo = False
  583. # TODO: Do something if this is None. Offer changing name?
  584. self.app.new_object("geometry", iso_name, iso_init)
  585. def on_plot_cb_click(self, *args):
  586. if self.muted_ui:
  587. return
  588. self.read_form_item('plot')
  589. def on_solid_cb_click(self, *args):
  590. if self.muted_ui:
  591. return
  592. self.read_form_item('solid')
  593. self.plot()
  594. def on_multicolored_cb_click(self, *args):
  595. if self.muted_ui:
  596. return
  597. self.read_form_item('multicolored')
  598. self.plot()
  599. def convert_units(self, units):
  600. """
  601. Converts the units of the object by scaling dimensions in all geometry
  602. and options.
  603. :param units: Units to which to convert the object: "IN" or "MM".
  604. :type units: str
  605. :return: None
  606. :rtype: None
  607. """
  608. factor = Gerber.convert_units(self, units)
  609. self.options['isotooldia'] *= factor
  610. self.options['cutoutmargin'] *= factor
  611. self.options['cutoutgapsize'] *= factor
  612. self.options['noncoppermargin'] *= factor
  613. self.options['bboxmargin'] *= factor
  614. def plot(self, **kwargs):
  615. """
  616. :param kwargs: color and face_color
  617. :return:
  618. """
  619. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  620. # Does all the required setup and returns False
  621. # if the 'ptint' option is set to False.
  622. if not FlatCAMObj.plot(self):
  623. return
  624. if 'color' in kwargs:
  625. color = kwargs['color']
  626. else:
  627. color = self.app.defaults['global_plot_line']
  628. if 'face_color' in kwargs:
  629. face_color = kwargs['face_color']
  630. else:
  631. face_color = self.app.defaults['global_plot_fill']
  632. geometry = self.solid_geometry
  633. # Make sure geometry is iterable.
  634. try:
  635. _ = iter(geometry)
  636. except TypeError:
  637. geometry = [geometry]
  638. def random_color():
  639. color = np.random.rand(4)
  640. color[3] = 1
  641. return color
  642. try:
  643. if self.options["solid"]:
  644. for g in geometry:
  645. if type(g) == Polygon or type(g) == LineString:
  646. self.add_shape(shape=g, color=color,
  647. face_color=random_color() if self.options['multicolored']
  648. else face_color, visible=self.options['plot'])
  649. else:
  650. for el in g:
  651. self.add_shape(shape=el, color=color,
  652. face_color=random_color() if self.options['multicolored']
  653. else face_color, visible=self.options['plot'])
  654. else:
  655. for g in geometry:
  656. if type(g) == Polygon or type(g) == LineString:
  657. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  658. visible=self.options['plot'])
  659. else:
  660. for el in g:
  661. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  662. visible=self.options['plot'])
  663. self.shapes.redraw()
  664. except (ObjectDeleted, AttributeError):
  665. self.shapes.clear(update=True)
  666. def serialize(self):
  667. return {
  668. "options": self.options,
  669. "kind": self.kind
  670. }
  671. class FlatCAMExcellon(FlatCAMObj, Excellon):
  672. """
  673. Represents Excellon/Drill code.
  674. """
  675. ui_type = ExcellonObjectUI
  676. optionChanged = QtCore.pyqtSignal(str)
  677. def __init__(self, name):
  678. Excellon.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  679. FlatCAMObj.__init__(self, name)
  680. self.kind = "excellon"
  681. self.options.update({
  682. "plot": True,
  683. "solid": False,
  684. "drillz": -0.1,
  685. "travelz": 0.1,
  686. "feedrate": 5.0,
  687. "feedrate_rapid": 5.0,
  688. "tooldia": 0.1,
  689. "slot_tooldia": 0.1,
  690. "toolchange": False,
  691. "toolchangez": 1.0,
  692. "toolchangexy": "0.0, 0.0",
  693. "endz": 2.0,
  694. "startz": None,
  695. "spindlespeed": None,
  696. "dwell": True,
  697. "dwelltime": 1000,
  698. "ppname_e": 'defaults',
  699. "optimization_type": "R",
  700. "gcode_type": "drills"
  701. })
  702. # TODO: Document this.
  703. self.tool_cbs = {}
  704. # Attributes to be included in serialization
  705. # Always append to it because it carries contents
  706. # from predecessors.
  707. self.ser_attrs += ['options', 'kind']
  708. # variable to store the total amount of drills per job
  709. self.tot_drill_cnt = 0
  710. self.tool_row = 0
  711. # variable to store the total amount of slots per job
  712. self.tot_slot_cnt = 0
  713. self.tool_row_slots = 0
  714. self.multigeo = False
  715. @staticmethod
  716. def merge(exc_list, exc_final):
  717. """
  718. Merge Excellon objects found in exc_list parameter into exc_final object.
  719. Options are always copied from source .
  720. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  721. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  722. tool_name to be used in the final Excellon object, exc_final.
  723. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  724. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  725. :param exc_final: Destination FlatCAMExcellon object.
  726. :return: None
  727. """
  728. try:
  729. flattened_list = list(itertools.chain(*exc_list))
  730. except TypeError:
  731. flattened_list = exc_list
  732. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  733. # values will be list of Shapely Points
  734. custom_dict = {}
  735. for exc in flattened_list:
  736. # copy options of the current excellon obj to the final excellon obj
  737. for option in exc.options:
  738. if option is not 'name':
  739. try:
  740. exc_final.options[option] = exc.options[option]
  741. except:
  742. exc.app.log.warning("Failed to copy option.", option)
  743. for drill in exc.drills:
  744. exc_tool_dia = float('%.3f' % exc.tools[drill['tool']]['C'])
  745. if exc_tool_dia not in custom_dict:
  746. custom_dict[exc_tool_dia] = [drill['point']]
  747. else:
  748. custom_dict[exc_tool_dia].append(drill['point'])
  749. # add the zeros and units to the exc_final object
  750. exc_final.zeros = exc.zeros
  751. exc_final.units = exc.units
  752. # variable to make tool_name for the tools
  753. current_tool = 0
  754. # Here we add data to the exc_final object
  755. # the tools diameter are now the keys in the drill_dia dict and the values are the Shapely Points
  756. for tool_dia in custom_dict:
  757. # we create a tool name for each key in the drill_dia dict (the key is a unique drill diameter)
  758. current_tool += 1
  759. tool_name = str(current_tool)
  760. spec = {"C": float(tool_dia)}
  761. exc_final.tools[tool_name] = spec
  762. # rebuild the drills list of dict's that belong to the exc_final object
  763. for point in custom_dict[tool_dia]:
  764. exc_final.drills.append(
  765. {
  766. "point": point,
  767. "tool": str(current_tool)
  768. }
  769. )
  770. # create the geometry for the exc_final object
  771. exc_final.create_geometry()
  772. def build_ui(self):
  773. FlatCAMObj.build_ui(self)
  774. n = len(self.tools)
  775. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  776. self.ui.tools_table.setRowCount(n + 2)
  777. self.tot_drill_cnt = 0
  778. self.tot_slot_cnt = 0
  779. self.tool_row = 0
  780. sort = []
  781. for k, v in list(self.tools.items()):
  782. sort.append((k, v.get('C')))
  783. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  784. tools = [i[0] for i in sorted_tools]
  785. for tool_no in tools:
  786. drill_cnt = 0 # variable to store the nr of drills per tool
  787. slot_cnt = 0 # variable to store the nr of slots per tool
  788. # Find no of drills for the current tool
  789. for drill in self.drills:
  790. if drill['tool'] == tool_no:
  791. drill_cnt += 1
  792. self.tot_drill_cnt += drill_cnt
  793. # Find no of slots for the current tool
  794. for slot in self.slots:
  795. if slot['tool'] == tool_no:
  796. slot_cnt += 1
  797. self.tot_slot_cnt += slot_cnt
  798. id = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  799. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  800. self.ui.tools_table.setItem(self.tool_row, 0, id) # Tool name/id
  801. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  802. # There are no drill bits in MM with more than 3 decimals diameter
  803. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  804. if self.units == 'MM':
  805. dia = QtWidgets.QTableWidgetItem('%.2f' % (self.tools[tool_no]['C']))
  806. else:
  807. dia = QtWidgets.QTableWidgetItem('%.3f' % (self.tools[tool_no]['C']))
  808. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  809. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  810. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  811. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  812. if slot_cnt > 0:
  813. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  814. else:
  815. slot_count = QtWidgets.QTableWidgetItem('')
  816. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  817. self.ui.tools_table.setItem(self.tool_row, 1, dia) # Diameter
  818. self.ui.tools_table.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  819. self.ui.tools_table.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  820. self.tool_row += 1
  821. # add a last row with the Total number of drills
  822. empty = QtWidgets.QTableWidgetItem('')
  823. empty.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  824. empty_1 = QtWidgets.QTableWidgetItem('')
  825. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  826. label_tot_drill_count = QtWidgets.QTableWidgetItem('Total Drills')
  827. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  828. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  829. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  830. self.ui.tools_table.setItem(self.tool_row, 0, empty)
  831. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  832. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  833. self.ui.tools_table.setItem(self.tool_row, 3, empty_1) # Total number of drills
  834. font = QtGui.QFont()
  835. font.setBold(True)
  836. font.setWeight(75)
  837. for k in [1, 2]:
  838. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  839. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  840. self.tool_row += 1
  841. # add a last row with the Total number of slots
  842. empty_2 = QtWidgets.QTableWidgetItem('')
  843. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  844. empty_3 = QtWidgets.QTableWidgetItem('')
  845. empty_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  846. label_tot_slot_count = QtWidgets.QTableWidgetItem('Total Slots')
  847. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  848. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  849. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  850. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  851. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  852. self.ui.tools_table.setItem(self.tool_row, 2, empty_3)
  853. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  854. for kl in [1, 2, 3]:
  855. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  856. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  857. # sort the tool diameter column
  858. # self.ui.tools_table.sortItems(1)
  859. # all the tools are selected by default
  860. self.ui.tools_table.selectColumn(0)
  861. #
  862. self.ui.tools_table.resizeColumnsToContents()
  863. self.ui.tools_table.resizeRowsToContents()
  864. vertical_header = self.ui.tools_table.verticalHeader()
  865. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  866. vertical_header.hide()
  867. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  868. horizontal_header = self.ui.tools_table.horizontalHeader()
  869. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  870. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  871. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  872. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  873. # horizontal_header.setStretchLastSection(True)
  874. self.ui.tools_table.setSortingEnabled(False)
  875. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  876. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  877. if not self.drills:
  878. self.ui.tdlabel.hide()
  879. self.ui.tooldia_entry.hide()
  880. self.ui.generate_milling_button.hide()
  881. else:
  882. self.ui.tdlabel.show()
  883. self.ui.tooldia_entry.show()
  884. self.ui.generate_milling_button.show()
  885. if not self.slots:
  886. self.ui.stdlabel.hide()
  887. self.ui.slot_tooldia_entry.hide()
  888. self.ui.generate_milling_slots_button.hide()
  889. else:
  890. self.ui.stdlabel.show()
  891. self.ui.slot_tooldia_entry.show()
  892. self.ui.generate_milling_slots_button.show()
  893. def set_ui(self, ui):
  894. """
  895. Configures the user interface for this object.
  896. Connects options to form fields.
  897. :param ui: User interface object.
  898. :type ui: ExcellonObjectUI
  899. :return: None
  900. """
  901. FlatCAMObj.set_ui(self, ui)
  902. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  903. self.form_fields.update({
  904. "plot": self.ui.plot_cb,
  905. "solid": self.ui.solid_cb,
  906. "drillz": self.ui.cutz_entry,
  907. "travelz": self.ui.travelz_entry,
  908. "feedrate": self.ui.feedrate_entry,
  909. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  910. "tooldia": self.ui.tooldia_entry,
  911. "slot_tooldia": self.ui.slot_tooldia_entry,
  912. "toolchange": self.ui.toolchange_cb,
  913. "toolchangez": self.ui.toolchangez_entry,
  914. "spindlespeed": self.ui.spindlespeed_entry,
  915. "dwell": self.ui.dwell_cb,
  916. "dwelltime": self.ui.dwelltime_entry,
  917. "startz": self.ui.estartz_entry,
  918. "endz": self.ui.eendz_entry,
  919. "ppname_e": self.ui.pp_excellon_name_cb,
  920. "gcode_type": self.ui.excellon_gcode_type_radio
  921. })
  922. for name in list(self.app.postprocessors.keys()):
  923. # the HPGL postprocessor is only for Geometry not for Excellon job therefore don't add it
  924. if name == 'hpgl':
  925. continue
  926. self.ui.pp_excellon_name_cb.addItem(name)
  927. # Fill form fields
  928. self.to_form()
  929. assert isinstance(self.ui, ExcellonObjectUI), \
  930. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  931. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  932. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  933. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  934. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  935. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  936. def get_selected_tools_list(self):
  937. """
  938. Returns the keys to the self.tools dictionary corresponding
  939. to the selections on the tool list in the GUI.
  940. :return: List of tools.
  941. :rtype: list
  942. """
  943. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  944. def get_selected_tools_table_items(self):
  945. """
  946. Returns a list of lists, each list in the list is made out of row elements
  947. :return: List of table_tools items.
  948. :rtype: list
  949. """
  950. table_tools_items = []
  951. for x in self.ui.tools_table.selectedItems():
  952. table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  953. for column in range(0, self.ui.tools_table.columnCount())])
  954. for item in table_tools_items:
  955. item[0] = str(item[0])
  956. return table_tools_items
  957. def export_excellon(self):
  958. """
  959. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  960. :return: has_slots and Excellon_code
  961. """
  962. excellon_code = ''
  963. units = self.app.general_options_form.general_group.units_radio.get_value().upper()
  964. # store here if the file has slots, return 1 if any slots, 0 if only drills
  965. has_slots = 0
  966. # drills processing
  967. try:
  968. for tool in self.tools:
  969. if int(tool) < 10:
  970. excellon_code += 'T0' + str(tool) + '\n'
  971. else:
  972. excellon_code += 'T' + str(tool) + '\n'
  973. for drill in self.drills:
  974. if tool == drill['tool']:
  975. if units == 'MM':
  976. excellon_code += 'X' + '%.3f' % drill['point'].x + 'Y' + '%.3f' % drill['point'].y + '\n'
  977. else:
  978. excellon_code += 'X' + '%.4f' % drill['point'].x + 'Y' + '%.4f' % drill['point'].y + '\n'
  979. except Exception as e:
  980. log.debug(str(e))
  981. # slots processing
  982. try:
  983. if self.slots:
  984. has_slots = 1
  985. for tool in self.tools:
  986. if int(tool) < 10:
  987. excellon_code += 'T0' + str(tool) + '\n'
  988. else:
  989. excellon_code += 'T' + str(tool) + '\n'
  990. for slot in self.slots:
  991. if tool == slot['tool']:
  992. if units == 'MM':
  993. excellon_code += 'G00' + 'X' + '%.3f' % slot['start'].x + 'Y' + \
  994. '%.3f' % slot['start'].y + '\n'
  995. excellon_code += 'M15\n'
  996. excellon_code += 'G01' + 'X' + '%.3f' % slot['stop'].x + 'Y' + \
  997. '%.3f' % slot['stop'].y + '\n'
  998. excellon_code += 'M16\n'
  999. else:
  1000. excellon_code += 'G00' + 'X' + '%.4f' % slot['start'].x + 'Y' + \
  1001. '%.4f' % slot['start'].y + '\n'
  1002. excellon_code += 'M15\n'
  1003. excellon_code += 'G01' + 'X' + '%.4f' % slot['stop'].x + 'Y' + \
  1004. '%.4f' % slot['stop'].y + '\n'
  1005. excellon_code += 'M16\n'
  1006. except Exception as e:
  1007. log.debug(str(e))
  1008. return has_slots, excellon_code
  1009. def export_excellon_altium(self):
  1010. """
  1011. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  1012. :return: has_slots and Excellon_code
  1013. """
  1014. excellon_code = ''
  1015. units = self.app.general_options_form.general_group.units_radio.get_value().upper()
  1016. # store here if the file has slots, return 1 if any slots, 0 if only drills
  1017. has_slots = 0
  1018. # drills processing
  1019. try:
  1020. for tool in self.tools:
  1021. if int(tool) < 10:
  1022. excellon_code += 'T0' + str(tool) + '\n'
  1023. else:
  1024. excellon_code += 'T' + str(tool) + '\n'
  1025. for drill in self.drills:
  1026. if tool == drill['tool']:
  1027. drill_x = drill['point'].x
  1028. drill_y = drill['point'].y
  1029. if units == 'MM':
  1030. drill_x /= 25.4
  1031. drill_y /= 25.4
  1032. exc_x_formatted = ('%.4f' % drill_x).replace('.', '')
  1033. if drill_x < 10:
  1034. exc_x_formatted = '0' + exc_x_formatted
  1035. exc_y_formatted = ('%.4f' % drill_y).replace('.', '')
  1036. if drill_y < 10:
  1037. exc_y_formatted = '0' + exc_y_formatted
  1038. excellon_code += 'X' + exc_x_formatted + 'Y' + exc_y_formatted + '\n'
  1039. except Exception as e:
  1040. log.debug(str(e))
  1041. # slots processing
  1042. try:
  1043. if self.slots:
  1044. has_slots = 1
  1045. for tool in self.tools:
  1046. if int(tool) < 10:
  1047. excellon_code += 'T0' + str(tool) + '\n'
  1048. else:
  1049. excellon_code += 'T' + str(tool) + '\n'
  1050. for slot in self.slots:
  1051. if tool == slot['tool']:
  1052. start_slot_x = slot['start'].x
  1053. start_slot_y = slot['start'].y
  1054. stop_slot_x = slot['stop'].x
  1055. stop_slot_y = slot['stop'].y
  1056. if units == 'MM':
  1057. start_slot_x /= 25.4
  1058. start_slot_y /= 25.4
  1059. stop_slot_x /= 25.4
  1060. stop_slot_y /= 25.4
  1061. start_slot_x_formatted = ('%.4f' % start_slot_x).replace('.', '')
  1062. if start_slot_x < 10:
  1063. start_slot_x_formatted = '0' + start_slot_x_formatted
  1064. start_slot_y_formatted = ('%.4f' % start_slot_y).replace('.', '')
  1065. if start_slot_y < 10:
  1066. start_slot_y_formatted = '0' + start_slot_y_formatted
  1067. stop_slot_x_formatted = ('%.4f' % stop_slot_x).replace('.', '')
  1068. if stop_slot_x < 10:
  1069. stop_slot_x_formatted = '0' + stop_slot_x_formatted
  1070. stop_slot_y_formatted = ('%.4f' % stop_slot_y).replace('.', '')
  1071. if stop_slot_y < 10:
  1072. stop_slot_y_formatted = '0' + stop_slot_y_formatted
  1073. excellon_code += 'G00' + 'X' + start_slot_x_formatted + 'Y' + \
  1074. start_slot_y_formatted + '\n'
  1075. excellon_code += 'M15\n'
  1076. excellon_code += 'G01' + 'X' + stop_slot_x_formatted + 'Y' + \
  1077. stop_slot_y_formatted + '\n'
  1078. excellon_code += 'M16\n'
  1079. except Exception as e:
  1080. log.debug(str(e))
  1081. return has_slots, excellon_code
  1082. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1083. """
  1084. Note: This method is a good template for generic operations as
  1085. it takes it's options from parameters or otherwise from the
  1086. object's options and returns a (success, msg) tuple as feedback
  1087. for shell operations.
  1088. :return: Success/failure condition tuple (bool, str).
  1089. :rtype: tuple
  1090. """
  1091. # Get the tools from the list. These are keys
  1092. # to self.tools
  1093. if tools is None:
  1094. tools = self.get_selected_tools_list()
  1095. if outname is None:
  1096. outname = self.options["name"] + "_mill"
  1097. if tooldia is None:
  1098. tooldia = self.options["tooldia"]
  1099. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1100. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1101. sort = []
  1102. for k, v in self.tools.items():
  1103. sort.append((k, v.get('C')))
  1104. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1105. if tools == "all":
  1106. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1107. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1108. if len(tools) == 0:
  1109. self.app.inform.emit("[error_notcl]Please select one or more tools from the list and try again.")
  1110. return False, "Error: No tools."
  1111. for tool in tools:
  1112. if tooldia > self.tools[tool]["C"]:
  1113. self.app.inform.emit("[error_notcl] Milling tool for DRILLS is larger than hole size. Cancelled.")
  1114. return False, "Error: Milling tool is larger than hole."
  1115. def geo_init(geo_obj, app_obj):
  1116. assert isinstance(geo_obj, FlatCAMGeometry), \
  1117. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1118. app_obj.progress.emit(20)
  1119. ### Add properties to the object
  1120. # get the tool_table items in a list of row items
  1121. tool_table_items = self.get_selected_tools_table_items()
  1122. # insert an information only element in the front
  1123. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1124. geo_obj.options['Tools_in_use'] = tool_table_items
  1125. geo_obj.options['type'] = 'Excellon Geometry'
  1126. geo_obj.solid_geometry = []
  1127. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1128. # for FlatCAM is 6 decimals,
  1129. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1130. for hole in self.drills:
  1131. if hole['tool'] in tools:
  1132. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  1133. if buffer_value == 0:
  1134. geo_obj.solid_geometry.append(
  1135. Point(hole['point']).buffer(0.0000001).exterior)
  1136. else:
  1137. geo_obj.solid_geometry.append(
  1138. Point(hole['point']).buffer(buffer_value).exterior)
  1139. if use_thread:
  1140. def geo_thread(app_obj):
  1141. app_obj.new_object("geometry", outname, geo_init)
  1142. app_obj.progress.emit(100)
  1143. # Create a promise with the new name
  1144. self.app.collection.promise(outname)
  1145. # Send to worker
  1146. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1147. else:
  1148. self.app.new_object("geometry", outname, geo_init)
  1149. return True, ""
  1150. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1151. """
  1152. Note: This method is a good template for generic operations as
  1153. it takes it's options from parameters or otherwise from the
  1154. object's options and returns a (success, msg) tuple as feedback
  1155. for shell operations.
  1156. :return: Success/failure condition tuple (bool, str).
  1157. :rtype: tuple
  1158. """
  1159. # Get the tools from the list. These are keys
  1160. # to self.tools
  1161. if tools is None:
  1162. tools = self.get_selected_tools_list()
  1163. if outname is None:
  1164. outname = self.options["name"] + "_mill"
  1165. if tooldia is None:
  1166. tooldia = self.options["slot_tooldia"]
  1167. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1168. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1169. sort = []
  1170. for k, v in self.tools.items():
  1171. sort.append((k, v.get('C')))
  1172. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1173. if tools == "all":
  1174. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1175. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1176. if len(tools) == 0:
  1177. self.app.inform.emit("[error_notcl]Please select one or more tools from the list and try again.")
  1178. return False, "Error: No tools."
  1179. for tool in tools:
  1180. if tooldia > self.tools[tool]["C"]:
  1181. self.app.inform.emit("[error_notcl] Milling tool for SLOTS is larger than hole size. Cancelled.")
  1182. return False, "Error: Milling tool is larger than hole."
  1183. def geo_init(geo_obj, app_obj):
  1184. assert isinstance(geo_obj, FlatCAMGeometry), \
  1185. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1186. app_obj.progress.emit(20)
  1187. ### Add properties to the object
  1188. # get the tool_table items in a list of row items
  1189. tool_table_items = self.get_selected_tools_table_items()
  1190. # insert an information only element in the front
  1191. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1192. geo_obj.options['Tools_in_use'] = tool_table_items
  1193. geo_obj.options['type'] = 'Excellon Geometry'
  1194. geo_obj.solid_geometry = []
  1195. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1196. # for FlatCAM is 6 decimals,
  1197. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1198. for slot in self.slots:
  1199. if slot['tool'] in tools:
  1200. buffer_value = self.tools[slot['tool']]["C"] / 2 - tooldia / 2
  1201. if buffer_value == 0:
  1202. start = slot['start']
  1203. stop = slot['stop']
  1204. lines_string = LineString([start, stop])
  1205. poly = lines_string.buffer(0.0000001, self.geo_steps_per_circle).exterior
  1206. geo_obj.solid_geometry.append(poly)
  1207. else:
  1208. start = slot['start']
  1209. stop = slot['stop']
  1210. lines_string = LineString([start, stop])
  1211. poly = lines_string.buffer(buffer_value, self.geo_steps_per_circle).exterior
  1212. geo_obj.solid_geometry.append(poly)
  1213. if use_thread:
  1214. def geo_thread(app_obj):
  1215. app_obj.new_object("geometry", outname + '_slot', geo_init)
  1216. app_obj.progress.emit(100)
  1217. # Create a promise with the new name
  1218. self.app.collection.promise(outname)
  1219. # Send to worker
  1220. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1221. else:
  1222. self.app.new_object("geometry", outname + '_slot', geo_init)
  1223. return True, ""
  1224. def on_generate_milling_button_click(self, *args):
  1225. self.app.report_usage("excellon_on_create_milling_drills button")
  1226. self.read_form()
  1227. self.generate_milling_drills(use_thread=False)
  1228. def on_generate_milling_slots_button_click(self, *args):
  1229. self.app.report_usage("excellon_on_create_milling_slots_button")
  1230. self.read_form()
  1231. self.generate_milling_slots(use_thread=False)
  1232. def on_create_cncjob_button_click(self, *args):
  1233. self.app.report_usage("excellon_on_create_cncjob_button")
  1234. self.read_form()
  1235. # Get the tools from the list
  1236. tools = self.get_selected_tools_list()
  1237. if len(tools) == 0:
  1238. self.app.inform.emit("[error_notcl]Please select one or more tools from the list and try again.")
  1239. return
  1240. job_name = self.options["name"] + "_cnc"
  1241. pp_excellon_name = self.options["ppname_e"]
  1242. # Object initialization function for app.new_object()
  1243. def job_init(job_obj, app_obj):
  1244. assert isinstance(job_obj, FlatCAMCNCjob), \
  1245. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  1246. # get the tool_table items in a list of row items
  1247. tool_table_items = self.get_selected_tools_table_items()
  1248. # insert an information only element in the front
  1249. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1250. ### Add properties to the object
  1251. job_obj.options['Tools_in_use'] = tool_table_items
  1252. job_obj.options['type'] = 'Excellon'
  1253. app_obj.progress.emit(20)
  1254. job_obj.z_cut = self.options["drillz"]
  1255. job_obj.z_move = self.options["travelz"]
  1256. job_obj.feedrate = self.options["feedrate"]
  1257. job_obj.feedrate_rapid = self.options["feedrate_rapid"]
  1258. job_obj.spindlespeed = self.options["spindlespeed"]
  1259. job_obj.dwell = self.options["dwell"]
  1260. job_obj.dwelltime = self.options["dwelltime"]
  1261. job_obj.pp_excellon_name = pp_excellon_name
  1262. job_obj.toolchange_xy = "excellon"
  1263. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  1264. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  1265. # There could be more than one drill size...
  1266. # job_obj.tooldia = # TODO: duplicate variable!
  1267. # job_obj.options["tooldia"] =
  1268. tools_csv = ','.join(tools)
  1269. job_obj.generate_from_excellon_by_tool(self, tools_csv,
  1270. drillz=self.options['drillz'],
  1271. toolchange=self.options["toolchange"],
  1272. toolchangez=self.options["toolchangez"],
  1273. toolchangexy=self.options["toolchangexy"],
  1274. startz=self.options["startz"],
  1275. endz=self.options["endz"],
  1276. excellon_optimization_type=self.options["optimization_type"])
  1277. app_obj.progress.emit(50)
  1278. job_obj.gcode_parse()
  1279. app_obj.progress.emit(60)
  1280. job_obj.create_geometry()
  1281. app_obj.progress.emit(80)
  1282. # To be run in separate thread
  1283. def job_thread(app_obj):
  1284. with self.app.proc_container.new("Generating CNC Code"):
  1285. app_obj.new_object("cncjob", job_name, job_init)
  1286. app_obj.progress.emit(100)
  1287. # Create promise for the new name.
  1288. self.app.collection.promise(job_name)
  1289. # Send to worker
  1290. # self.app.worker.add_task(job_thread, [self.app])
  1291. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1292. def on_plot_cb_click(self, *args):
  1293. if self.muted_ui:
  1294. return
  1295. self.read_form_item('plot')
  1296. def on_solid_cb_click(self, *args):
  1297. if self.muted_ui:
  1298. return
  1299. self.read_form_item('solid')
  1300. self.plot()
  1301. def convert_units(self, units):
  1302. factor = Excellon.convert_units(self, units)
  1303. self.options['drillz'] *= factor
  1304. self.options['travelz'] *= factor
  1305. self.options['feedrate'] *= factor
  1306. self.options['feedrate_rapid'] *= factor
  1307. self.options['toolchangez'] *= factor
  1308. coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  1309. coords_xy[0] *= factor
  1310. coords_xy[1] *= factor
  1311. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  1312. if self.options['startz'] is not None:
  1313. self.options['startz'] *= factor
  1314. self.options['endz'] *= factor
  1315. def plot(self):
  1316. # Does all the required setup and returns False
  1317. # if the 'ptint' option is set to False.
  1318. if not FlatCAMObj.plot(self):
  1319. return
  1320. try:
  1321. _ = iter(self.solid_geometry)
  1322. except TypeError:
  1323. self.solid_geometry = [self.solid_geometry]
  1324. try:
  1325. # Plot excellon (All polygons?)
  1326. if self.options["solid"]:
  1327. for geo in self.solid_geometry:
  1328. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF', visible=self.options['plot'],
  1329. layer=2)
  1330. else:
  1331. for geo in self.solid_geometry:
  1332. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1333. for ints in geo.interiors:
  1334. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1335. self.shapes.redraw()
  1336. except (ObjectDeleted, AttributeError):
  1337. self.shapes.clear(update=True)
  1338. # try:
  1339. # # Plot excellon (All polygons?)
  1340. # if self.options["solid"]:
  1341. # for geo_type in self.solid_geometry:
  1342. # if geo_type is not None:
  1343. # if type(geo_type) is dict:
  1344. # for tooldia in geo_type:
  1345. # geo_list = geo_type[tooldia]
  1346. # for geo in geo_list:
  1347. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  1348. # visible=self.options['plot'],
  1349. # layer=2)
  1350. # else:
  1351. # self.add_shape(shape=geo_type, color='#750000BF', face_color='#C40000BF',
  1352. # visible=self.options['plot'],
  1353. # layer=2)
  1354. # else:
  1355. # for geo_type in self.solid_geometry:
  1356. # if geo_type is not None:
  1357. # if type(geo_type) is dict:
  1358. # for tooldia in geo_type:
  1359. # geo_list = geo_type[tooldia]
  1360. # for geo in geo_list:
  1361. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1362. # for ints in geo.interiors:
  1363. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1364. # else:
  1365. # self.add_shape(shape=geo_type.exterior, color='red', visible=self.options['plot'])
  1366. # for ints in geo_type.interiors:
  1367. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1368. # self.shapes.redraw()
  1369. # except (ObjectDeleted, AttributeError):
  1370. # self.shapes.clear(update=True)
  1371. class FlatCAMGeometry(FlatCAMObj, Geometry):
  1372. """
  1373. Geometric object not associated with a specific
  1374. format.
  1375. """
  1376. optionChanged = QtCore.pyqtSignal(str)
  1377. ui_type = GeometryObjectUI
  1378. @staticmethod
  1379. def merge(geo_list, geo_final, multigeo=None):
  1380. """
  1381. Merges the geometry of objects in grb_list into
  1382. the geometry of geo_final.
  1383. :param geo_list: List of FlatCAMGerber Objects to join.
  1384. :param geo_final: Destination FlatCAMGerber object.
  1385. :return: None
  1386. """
  1387. if geo_final.solid_geometry is None:
  1388. geo_final.solid_geometry = []
  1389. if type(geo_final.solid_geometry) is not list:
  1390. geo_final.solid_geometry = [geo_final.solid_geometry]
  1391. for geo in geo_list:
  1392. # Expand lists
  1393. if type(geo) is list:
  1394. FlatCAMGeometry.merge(geo, geo_final)
  1395. # If not list, just append
  1396. else:
  1397. # merge solid_geometry, useful for singletool geometry, for multitool each is empty
  1398. if multigeo is None or multigeo == False:
  1399. geo_final.multigeo = False
  1400. try:
  1401. geo_final.solid_geometry.append(geo.solid_geometry)
  1402. except Exception as e:
  1403. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  1404. else:
  1405. geo_final.multigeo = True
  1406. # if multigeo the solid_geometry is empty in the object attributes because it now lives in the
  1407. # tools object attribute, as a key value
  1408. geo_final.solid_geometry = []
  1409. # find the tool_uid maximum value in the geo_final
  1410. geo_final_uid_list = []
  1411. for key in geo_final.tools:
  1412. geo_final_uid_list.append(int(key))
  1413. try:
  1414. max_uid = max(geo_final_uid_list, key=int)
  1415. except ValueError:
  1416. max_uid = 0
  1417. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  1418. # to merge the obj.tools as it is likely there is none to merge.
  1419. if not isinstance(geo, FlatCAMGerber) and not isinstance(geo, FlatCAMExcellon):
  1420. for tool_uid in geo.tools:
  1421. max_uid += 1
  1422. geo_final.tools[max_uid] = dict(geo.tools[tool_uid])
  1423. @staticmethod
  1424. def get_pts(o):
  1425. """
  1426. Returns a list of all points in the object, where
  1427. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  1428. of such. Search is done recursively.
  1429. :param: geometric object
  1430. :return: List of points
  1431. :rtype: list
  1432. """
  1433. pts = []
  1434. ## Iterable: descend into each item.
  1435. try:
  1436. for subo in o:
  1437. pts += FlatCAMGeometry.get_pts(subo)
  1438. ## Non-iterable
  1439. except TypeError:
  1440. if o is not None:
  1441. if type(o) == MultiPolygon:
  1442. for poly in o:
  1443. pts += FlatCAMGeometry.get_pts(poly)
  1444. ## Descend into .exerior and .interiors
  1445. elif type(o) == Polygon:
  1446. pts += FlatCAMGeometry.get_pts(o.exterior)
  1447. for i in o.interiors:
  1448. pts += FlatCAMGeometry.get_pts(i)
  1449. elif type(o) == MultiLineString:
  1450. for line in o:
  1451. pts += FlatCAMGeometry.get_pts(line)
  1452. ## Has .coords: list them.
  1453. else:
  1454. pts += list(o.coords)
  1455. else:
  1456. return
  1457. return pts
  1458. def __init__(self, name):
  1459. FlatCAMObj.__init__(self, name)
  1460. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  1461. self.kind = "geometry"
  1462. self.options.update({
  1463. "plot": True,
  1464. "cutz": -0.002,
  1465. "vtipdia": 0.1,
  1466. "vtipangle": 30,
  1467. "travelz": 0.1,
  1468. "feedrate": 5.0,
  1469. "feedrate_z": 5.0,
  1470. "feedrate_rapid": 5.0,
  1471. "spindlespeed": None,
  1472. "dwell": True,
  1473. "dwelltime": 1000,
  1474. "multidepth": False,
  1475. "depthperpass": 0.002,
  1476. "extracut": False,
  1477. "endz": 2.0,
  1478. "toolchange": False,
  1479. "toolchangez": 1.0,
  1480. "toolchangexy": "0.0, 0.0",
  1481. "startz": None,
  1482. "ppname_g": 'default',
  1483. })
  1484. if "cnctooldia" not in self.options:
  1485. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  1486. self.options["startz"] = self.app.defaults["geometry_startz"]
  1487. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  1488. self.tooluid = 0
  1489. '''
  1490. self.tools = {}
  1491. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  1492. tool_id of the tools and the value is another dict that will hold the data under the following form:
  1493. {tooluid: {
  1494. 'tooldia': 1,
  1495. 'offset': 'Path',
  1496. 'offset_value': 0.0
  1497. 'type': 'Rough',
  1498. 'tool_type': 'C1',
  1499. 'data': self.default_tool_data
  1500. 'solid_geometry': []
  1501. }
  1502. }
  1503. '''
  1504. self.tools = {}
  1505. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  1506. # those elements are the ones used for generating GCode
  1507. self.sel_tools = {}
  1508. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  1509. self.type_item_options = ["Iso", "Rough", "Finish"]
  1510. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  1511. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  1512. self.v_tool_type = None
  1513. self.multigeo = False
  1514. # Attributes to be included in serialization
  1515. # Always append to it because it carries contents
  1516. # from predecessors.
  1517. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  1518. def build_ui(self):
  1519. self.ui_disconnect()
  1520. FlatCAMObj.build_ui(self)
  1521. offset = 0
  1522. tool_idx = 0
  1523. n = len(self.tools)
  1524. self.ui.geo_tools_table.setRowCount(n)
  1525. for tooluid_key, tooluid_value in self.tools.items():
  1526. tool_idx += 1
  1527. row_no = tool_idx - 1
  1528. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  1529. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1530. self.ui.geo_tools_table.setItem(row_no, 0, id) # Tool name/id
  1531. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  1532. # There are no tool bits in MM with more than 3 decimals diameter.
  1533. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  1534. if self.units == 'MM':
  1535. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(tooluid_value['tooldia']))
  1536. else:
  1537. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(tooluid_value['tooldia']))
  1538. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1539. offset_item = QtWidgets.QComboBox()
  1540. for item in self.offset_item_options:
  1541. offset_item.addItem(item)
  1542. offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  1543. idx = offset_item.findText(tooluid_value['offset'])
  1544. offset_item.setCurrentIndex(idx)
  1545. type_item = QtWidgets.QComboBox()
  1546. for item in self.type_item_options:
  1547. type_item.addItem(item)
  1548. type_item.setStyleSheet('background-color: rgb(255,255,255)')
  1549. idx = type_item.findText(tooluid_value['type'])
  1550. type_item.setCurrentIndex(idx)
  1551. tool_type_item = QtWidgets.QComboBox()
  1552. for item in self.tool_type_item_options:
  1553. tool_type_item.addItem(item)
  1554. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  1555. idx = tool_type_item.findText(tooluid_value['tool_type'])
  1556. tool_type_item.setCurrentIndex(idx)
  1557. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  1558. plot_item = FCCheckBox()
  1559. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  1560. if self.ui.plot_cb.isChecked():
  1561. plot_item.setChecked(True)
  1562. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  1563. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  1564. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  1565. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  1566. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  1567. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  1568. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  1569. try:
  1570. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  1571. except:
  1572. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools")
  1573. # make the diameter column editable
  1574. for row in range(tool_idx):
  1575. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  1576. QtCore.Qt.ItemIsEditable |
  1577. QtCore.Qt.ItemIsEnabled)
  1578. # sort the tool diameter column
  1579. # self.ui.geo_tools_table.sortItems(1)
  1580. # all the tools are selected by default
  1581. # self.ui.geo_tools_table.selectColumn(0)
  1582. self.ui.geo_tools_table.resizeColumnsToContents()
  1583. self.ui.geo_tools_table.resizeRowsToContents()
  1584. vertical_header = self.ui.geo_tools_table.verticalHeader()
  1585. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1586. vertical_header.hide()
  1587. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1588. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  1589. horizontal_header.setMinimumSectionSize(10)
  1590. horizontal_header.setDefaultSectionSize(70)
  1591. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  1592. horizontal_header.resizeSection(0, 20)
  1593. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1594. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  1595. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1596. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  1597. horizontal_header.resizeSection(4, 40)
  1598. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  1599. horizontal_header.resizeSection(4, 17)
  1600. # horizontal_header.setStretchLastSection(True)
  1601. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1602. self.ui.geo_tools_table.setColumnWidth(0, 20)
  1603. self.ui.geo_tools_table.setColumnWidth(4, 40)
  1604. self.ui.geo_tools_table.setColumnWidth(6, 17)
  1605. # self.ui.geo_tools_table.setSortingEnabled(True)
  1606. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  1607. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  1608. # update UI for all rows - useful after units conversion but only if there is at least one row
  1609. row_cnt = self.ui.geo_tools_table.rowCount()
  1610. if row_cnt > 0:
  1611. for r in range(row_cnt):
  1612. self.update_ui(r)
  1613. # select only the first tool / row
  1614. selected_row = 0
  1615. try:
  1616. self.select_tools_table_row(selected_row, clearsel=True)
  1617. # update the Geometry UI
  1618. self.update_ui()
  1619. except Exception as e:
  1620. # when the tools table is empty there will be this error but once the table is populated it will go away
  1621. log.debug(str(e))
  1622. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  1623. # and can create some problems
  1624. if self.multigeo is False:
  1625. self.ui.geo_tools_table.setColumnHidden(6, True)
  1626. else:
  1627. self.ui.geo_tools_table.setColumnHidden(6, False)
  1628. self.set_tool_offset_visibility(selected_row)
  1629. self.ui_connect()
  1630. def set_ui(self, ui):
  1631. FlatCAMObj.set_ui(self, ui)
  1632. log.debug("FlatCAMGeometry.set_ui()")
  1633. assert isinstance(self.ui, GeometryObjectUI), \
  1634. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  1635. # populate postprocessor names in the combobox
  1636. for name in list(self.app.postprocessors.keys()):
  1637. self.ui.pp_geometry_name_cb.addItem(name)
  1638. self.form_fields.update({
  1639. "plot": self.ui.plot_cb,
  1640. "cutz": self.ui.cutz_entry,
  1641. "vtipdia": self.ui.tipdia_entry,
  1642. "vtipangle": self.ui.tipangle_entry,
  1643. "travelz": self.ui.travelz_entry,
  1644. "feedrate": self.ui.cncfeedrate_entry,
  1645. "feedrate_z": self.ui.cncplunge_entry,
  1646. "feedrate_rapid": self.ui.cncfeedrate_rapid_entry,
  1647. "spindlespeed": self.ui.cncspindlespeed_entry,
  1648. "dwell": self.ui.dwell_cb,
  1649. "dwelltime": self.ui.dwelltime_entry,
  1650. "multidepth": self.ui.mpass_cb,
  1651. "ppname_g": self.ui.pp_geometry_name_cb,
  1652. "depthperpass": self.ui.maxdepth_entry,
  1653. "extracut": self.ui.extracut_cb,
  1654. "toolchange": self.ui.toolchangeg_cb,
  1655. "toolchangez": self.ui.toolchangez_entry,
  1656. "endz": self.ui.gendz_entry,
  1657. })
  1658. # Fill form fields only on object create
  1659. self.to_form()
  1660. self.ui.tipdialabel.hide()
  1661. self.ui.tipdia_entry.hide()
  1662. self.ui.tipanglelabel.hide()
  1663. self.ui.tipangle_entry.hide()
  1664. self.ui.cutz_entry.setDisabled(False)
  1665. # store here the default data for Geometry Data
  1666. self.default_data = {}
  1667. self.default_data.update({
  1668. "name": None,
  1669. "plot": None,
  1670. "cutz": None,
  1671. "vtipdia": None,
  1672. "vtipangle": None,
  1673. "travelz": None,
  1674. "feedrate": None,
  1675. "feedrate_z": None,
  1676. "feedrate_rapid": None,
  1677. "dwell": None,
  1678. "dwelltime": None,
  1679. "multidepth": None,
  1680. "ppname_g": None,
  1681. "depthperpass": None,
  1682. "extracut": None,
  1683. "toolchange": None,
  1684. "toolchangez": None,
  1685. "endz": None,
  1686. "spindlespeed": None,
  1687. "toolchangexy": None,
  1688. "startz": None
  1689. })
  1690. # fill in self.default_data values from self.options
  1691. for def_key in self.default_data:
  1692. for opt_key, opt_val in self.options.items():
  1693. if def_key == opt_key:
  1694. self.default_data[def_key] = opt_val
  1695. self.tooluid += 1
  1696. if not self.tools:
  1697. self.tools.update({
  1698. self.tooluid: {
  1699. 'tooldia': self.options["cnctooldia"],
  1700. 'offset': 'Path',
  1701. 'offset_value': 0.0,
  1702. 'type': 'Rough',
  1703. 'tool_type': 'C1',
  1704. 'data': self.default_data,
  1705. 'solid_geometry': []
  1706. }
  1707. })
  1708. else:
  1709. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  1710. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  1711. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  1712. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  1713. # following convoluted way of changing the keys from string to float type
  1714. temp_tools = {}
  1715. new_key = 0.0
  1716. for tooluid_key in self.tools:
  1717. val = dict(self.tools[tooluid_key])
  1718. new_key = deepcopy(int(tooluid_key))
  1719. temp_tools[new_key] = val
  1720. self.tools.clear()
  1721. self.tools = dict(temp_tools)
  1722. self.ui.tool_offset_entry.hide()
  1723. self.ui.tool_offset_lbl.hide()
  1724. # used to store the state of the mpass_cb if the selected postproc for geometry is hpgl
  1725. self.old_pp_state = self.default_data['multidepth']
  1726. self.old_toolchangeg_state = self.default_data['toolchange']
  1727. if not isinstance(self.ui, GeometryObjectUI):
  1728. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  1729. return
  1730. self.ui.geo_tools_table.setupContextMenu()
  1731. self.ui.geo_tools_table.addContextMenu(
  1732. "Copy", self.on_tool_copy, icon=QtGui.QIcon("share/copy16.png"))
  1733. self.ui.geo_tools_table.addContextMenu(
  1734. "Delete", lambda: self.on_tool_delete(all=None), icon=QtGui.QIcon("share/delete32.png"))
  1735. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1736. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  1737. self.ui.paint_tool_button.clicked.connect(self.app.paint_tool.run)
  1738. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  1739. def set_tool_offset_visibility(self, current_row):
  1740. if current_row is None:
  1741. return
  1742. try:
  1743. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  1744. if tool_offset is not None:
  1745. tool_offset_txt = tool_offset.currentText()
  1746. if tool_offset_txt == 'Custom':
  1747. self.ui.tool_offset_entry.show()
  1748. self.ui.tool_offset_lbl.show()
  1749. else:
  1750. self.ui.tool_offset_entry.hide()
  1751. self.ui.tool_offset_lbl.hide()
  1752. except Exception as e:
  1753. log.debug("set_tool_offset_visibility() --> " + str(e))
  1754. return
  1755. def on_offset_value_edited(self):
  1756. '''
  1757. This will save the offset_value into self.tools storage whenever the oofset value is edited
  1758. :return:
  1759. '''
  1760. for current_row in self.ui.geo_tools_table.selectedItems():
  1761. # sometime the header get selected and it has row number -1
  1762. # we don't want to do anything with the header :)
  1763. if current_row.row() < 0:
  1764. continue
  1765. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  1766. self.set_tool_offset_visibility(current_row.row())
  1767. for tooluid_key, tooluid_value in self.tools.items():
  1768. if int(tooluid_key) == tool_uid:
  1769. tooluid_value['offset_value'] = self.ui.tool_offset_entry.get_value()
  1770. def ui_connect(self):
  1771. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  1772. # changes in geometry UI
  1773. for i in range(self.ui.grid3.count()):
  1774. try:
  1775. # works for CheckBoxes
  1776. self.ui.grid3.itemAt(i).widget().stateChanged.connect(self.gui_form_to_storage)
  1777. except:
  1778. # works for ComboBoxes
  1779. try:
  1780. self.ui.grid3.itemAt(i).widget().currentIndexChanged.connect(self.gui_form_to_storage)
  1781. except:
  1782. # works for Entry
  1783. try:
  1784. self.ui.grid3.itemAt(i).widget().editingFinished.connect(self.gui_form_to_storage)
  1785. except:
  1786. pass
  1787. for row in range(self.ui.geo_tools_table.rowCount()):
  1788. for col in [2, 3, 4]:
  1789. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  1790. self.on_tooltable_cellwidget_change)
  1791. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  1792. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  1793. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  1794. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  1795. self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  1796. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  1797. self.ui.tool_offset_entry.editingFinished.connect(self.on_offset_value_edited)
  1798. for row in range(self.ui.geo_tools_table.rowCount()):
  1799. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  1800. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1801. def ui_disconnect(self):
  1802. try:
  1803. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  1804. # changes in geometry UI
  1805. for i in range(self.ui.grid3.count()):
  1806. if isinstance(self.ui.grid3.itemAt(i).widget(), FCCheckBox):
  1807. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect()
  1808. if isinstance(self.ui.grid3.itemAt(i).widget(), FCComboBox):
  1809. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect()
  1810. if isinstance(self.ui.grid3.itemAt(i).widget(), LengthEntry) or \
  1811. isinstance(self.ui.grid3.itemAt(i), IntEntry) or \
  1812. isinstance(self.ui.grid3.itemAt(i), FCEntry):
  1813. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect()
  1814. except:
  1815. pass
  1816. try:
  1817. for row in range(self.ui.geo_tools_table.rowCount()):
  1818. for col in [2, 3, 4]:
  1819. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  1820. except:
  1821. pass
  1822. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  1823. try:
  1824. self.ui.addtool_btn.clicked.disconnect()
  1825. except:
  1826. pass
  1827. try:
  1828. self.ui.copytool_btn.clicked.disconnect()
  1829. except:
  1830. pass
  1831. try:
  1832. self.ui.deltool_btn.clicked.disconnect()
  1833. except:
  1834. pass
  1835. try:
  1836. self.ui.geo_tools_table.currentItemChanged.disconnect()
  1837. except:
  1838. pass
  1839. try:
  1840. self.ui.geo_tools_table.itemChanged.disconnect()
  1841. except:
  1842. pass
  1843. try:
  1844. self.ui.tool_offset_entry.editingFinished.disconnect()
  1845. except:
  1846. pass
  1847. for row in range(self.ui.geo_tools_table.rowCount()):
  1848. try:
  1849. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  1850. except:
  1851. pass
  1852. try:
  1853. self.ui.plot_cb.stateChanged.disconnect()
  1854. except:
  1855. pass
  1856. def on_tool_add(self, dia=None):
  1857. self.ui_disconnect()
  1858. last_offset = None
  1859. last_offset_value = None
  1860. last_type = None
  1861. last_tool_type = None
  1862. last_data = None
  1863. last_solid_geometry = []
  1864. if dia is not None:
  1865. tooldia = dia
  1866. else:
  1867. tooldia = self.ui.addtool_entry.get_value()
  1868. if tooldia is None:
  1869. self.build_ui()
  1870. self.app.inform.emit("[error_notcl] Please enter the desired tool diameter in Float format.")
  1871. return
  1872. # construct a list of all 'tooluid' in the self.tools
  1873. tool_uid_list = []
  1874. for tooluid_key in self.tools:
  1875. tool_uid_item = int(tooluid_key)
  1876. tool_uid_list.append(tool_uid_item)
  1877. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  1878. if not tool_uid_list:
  1879. max_uid = 0
  1880. else:
  1881. max_uid = max(tool_uid_list)
  1882. self.tooluid = max_uid + 1
  1883. if self.units == 'IN':
  1884. tooldia = float('%.4f' % tooldia)
  1885. else:
  1886. tooldia = float('%.2f' % tooldia)
  1887. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  1888. # otherwise we add a tool with data copied from last tool
  1889. if not self.tools:
  1890. self.tools.update({
  1891. self.tooluid: {
  1892. 'tooldia': tooldia,
  1893. 'offset': 'Path',
  1894. 'offset_value': 0.0,
  1895. 'type': 'Rough',
  1896. 'tool_type': 'C1',
  1897. 'data': dict(self.default_data),
  1898. 'solid_geometry': []
  1899. }
  1900. })
  1901. else:
  1902. # print("LAST", self.tools[maxuid])
  1903. last_data = self.tools[max_uid]['data']
  1904. last_offset = self.tools[max_uid]['offset']
  1905. last_offset_value = self.tools[max_uid]['offset_value']
  1906. last_type = self.tools[max_uid]['type']
  1907. last_tool_type = self.tools[max_uid]['tool_type']
  1908. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  1909. self.tools.update({
  1910. self.tooluid: {
  1911. 'tooldia': tooldia,
  1912. 'offset': last_offset,
  1913. 'offset_value': last_offset_value,
  1914. 'type': last_type,
  1915. 'tool_type': last_tool_type,
  1916. 'data': dict(last_data),
  1917. 'solid_geometry': deepcopy(last_solid_geometry)
  1918. }
  1919. })
  1920. # print("CURRENT", self.tools[-1])
  1921. self.ui.tool_offset_entry.hide()
  1922. self.ui.tool_offset_lbl.hide()
  1923. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  1924. try:
  1925. self.ser_attrs.remove('tools')
  1926. except:
  1927. pass
  1928. self.ser_attrs.append('tools')
  1929. self.app.inform.emit("[success] Tool added in Tool Table.")
  1930. self.build_ui()
  1931. def on_tool_copy(self, all=None):
  1932. self.ui_disconnect()
  1933. # find the tool_uid maximum value in the self.tools
  1934. uid_list = []
  1935. for key in self.tools:
  1936. uid_list.append(int(key))
  1937. try:
  1938. max_uid = max(uid_list, key=int)
  1939. except ValueError:
  1940. max_uid = 0
  1941. if all is None:
  1942. if self.ui.geo_tools_table.selectedItems():
  1943. for current_row in self.ui.geo_tools_table.selectedItems():
  1944. # sometime the header get selected and it has row number -1
  1945. # we don't want to do anything with the header :)
  1946. if current_row.row() < 0:
  1947. continue
  1948. try:
  1949. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  1950. self.set_tool_offset_visibility(current_row.row())
  1951. max_uid += 1
  1952. self.tools[int(max_uid)] = dict(self.tools[tooluid_copy])
  1953. except AttributeError:
  1954. self.app.inform.emit("[warning_notcl]Failed. Select a tool to copy.")
  1955. self.build_ui()
  1956. return
  1957. except Exception as e:
  1958. log.debug("on_tool_copy() --> " + str(e))
  1959. # deselect the table
  1960. # self.ui.geo_tools_table.clearSelection()
  1961. else:
  1962. self.app.inform.emit("[warning_notcl]Failed. Select a tool to copy.")
  1963. self.build_ui()
  1964. return
  1965. else:
  1966. # we copy all tools in geo_tools_table
  1967. try:
  1968. temp_tools = dict(self.tools)
  1969. max_uid += 1
  1970. for tooluid in temp_tools:
  1971. self.tools[int(max_uid)] = dict(temp_tools[tooluid])
  1972. temp_tools.clear()
  1973. except Exception as e:
  1974. log.debug("on_tool_copy() --> " + str(e))
  1975. # if there are no more tools in geo tools table then hide the tool offset
  1976. if not self.tools:
  1977. self.ui.tool_offset_entry.hide()
  1978. self.ui.tool_offset_lbl.hide()
  1979. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  1980. try:
  1981. self.ser_attrs.remove('tools')
  1982. except:
  1983. pass
  1984. self.ser_attrs.append('tools')
  1985. self.build_ui()
  1986. self.app.inform.emit("[success] Tool was copied in Tool Table.")
  1987. def on_tool_edit(self, current_item):
  1988. self.ui_disconnect()
  1989. current_row = current_item.row()
  1990. tool_dia = float('%.4f' % float(self.ui.geo_tools_table.item(current_row, 1).text()))
  1991. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  1992. self.tools[tooluid]['tooldia'] = tool_dia
  1993. try:
  1994. self.ser_attrs.remove('tools')
  1995. self.ser_attrs.append('tools')
  1996. except:
  1997. pass
  1998. self.app.inform.emit("[success] Tool was edited in Tool Table.")
  1999. self.build_ui()
  2000. def on_tool_delete(self, all=None):
  2001. self.ui_disconnect()
  2002. if all is None:
  2003. if self.ui.geo_tools_table.selectedItems():
  2004. for current_row in self.ui.geo_tools_table.selectedItems():
  2005. # sometime the header get selected and it has row number -1
  2006. # we don't want to do anything with the header :)
  2007. if current_row.row() < 0:
  2008. continue
  2009. try:
  2010. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2011. self.set_tool_offset_visibility(current_row.row())
  2012. temp_tools = dict(self.tools)
  2013. for tooluid_key in self.tools:
  2014. if int(tooluid_key) == tooluid_del:
  2015. temp_tools.pop(tooluid_del, None)
  2016. self.tools = dict(temp_tools)
  2017. temp_tools.clear()
  2018. except AttributeError:
  2019. self.app.inform.emit("[warning_notcl]Failed. Select a tool to delete.")
  2020. self.build_ui()
  2021. return
  2022. except Exception as e:
  2023. log.debug("on_tool_delete() --> " + str(e))
  2024. # deselect the table
  2025. # self.ui.geo_tools_table.clearSelection()
  2026. else:
  2027. self.app.inform.emit("[warning_notcl]Failed. Select a tool to delete.")
  2028. self.build_ui()
  2029. return
  2030. else:
  2031. # we delete all tools in geo_tools_table
  2032. self.tools.clear()
  2033. self.app.plot_all()
  2034. # if there are no more tools in geo tools table then hide the tool offset
  2035. if not self.tools:
  2036. self.ui.tool_offset_entry.hide()
  2037. self.ui.tool_offset_lbl.hide()
  2038. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2039. try:
  2040. self.ser_attrs.remove('tools')
  2041. except:
  2042. pass
  2043. self.ser_attrs.append('tools')
  2044. self.build_ui()
  2045. self.app.inform.emit("[success] Tool was deleted in Tool Table.")
  2046. obj_active = self.app.collection.get_active()
  2047. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  2048. # we make it back SingleGeo
  2049. if self.ui.geo_tools_table.rowCount() <= 0:
  2050. obj_active.multigeo = False
  2051. obj_active.options['xmin'] = 0
  2052. obj_active.options['ymin'] = 0
  2053. obj_active.options['xmax'] = 0
  2054. obj_active.options['ymax'] = 0
  2055. if obj_active.multigeo is True:
  2056. try:
  2057. xmin, ymin, xmax, ymax = obj_active.bounds()
  2058. obj_active.options['xmin'] = xmin
  2059. obj_active.options['ymin'] = ymin
  2060. obj_active.options['xmax'] = xmax
  2061. obj_active.options['ymax'] = ymax
  2062. except:
  2063. obj_active.options['xmin'] = 0
  2064. obj_active.options['ymin'] = 0
  2065. obj_active.options['xmax'] = 0
  2066. obj_active.options['ymax'] = 0
  2067. def on_row_selection_change(self):
  2068. self.update_ui()
  2069. def update_ui(self, row=None):
  2070. self.ui_disconnect()
  2071. if row is None:
  2072. try:
  2073. current_row = self.ui.geo_tools_table.currentRow()
  2074. except:
  2075. current_row = 0
  2076. else:
  2077. current_row = row
  2078. if current_row < 0:
  2079. current_row = 0
  2080. self.set_tool_offset_visibility(current_row)
  2081. # populate the form with the data from the tool associated with the row parameter
  2082. try:
  2083. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2084. except Exception as e:
  2085. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2086. return
  2087. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  2088. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  2089. try:
  2090. tool_type_txt = self.ui.geo_tools_table.cellWidget(current_row, 4).currentText()
  2091. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  2092. except Exception as e:
  2093. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2094. return
  2095. try:
  2096. # set the form with data from the newly selected tool
  2097. for tooluid_key, tooluid_value in self.tools.items():
  2098. if int(tooluid_key) == tooluid:
  2099. for key, value in tooluid_value.items():
  2100. if key == 'data':
  2101. form_value_storage = tooluid_value[key]
  2102. self.update_form(form_value_storage)
  2103. if key == 'offset_value':
  2104. # update the offset value in the entry even if the entry is hidden
  2105. self.ui.tool_offset_entry.set_value(tooluid_value[key])
  2106. if key == 'tool_type' and value == 'V':
  2107. self.update_cutz()
  2108. except Exception as e:
  2109. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  2110. self.ui_connect()
  2111. def ui_update_v_shape(self, tool_type_txt):
  2112. if tool_type_txt == 'V':
  2113. self.ui.tipdialabel.show()
  2114. self.ui.tipdia_entry.show()
  2115. self.ui.tipanglelabel.show()
  2116. self.ui.tipangle_entry.show()
  2117. self.ui.cutz_entry.setDisabled(True)
  2118. self.update_cutz()
  2119. else:
  2120. self.ui.tipdialabel.hide()
  2121. self.ui.tipdia_entry.hide()
  2122. self.ui.tipanglelabel.hide()
  2123. self.ui.tipangle_entry.hide()
  2124. self.ui.cutz_entry.setDisabled(False)
  2125. def update_cutz(self):
  2126. vdia = float(self.ui.tipdia_entry.get_value())
  2127. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  2128. row = self.ui.geo_tools_table.currentRow()
  2129. tool_uid = int(self.ui.geo_tools_table.item(row, 5).text())
  2130. tooldia = float(self.ui.geo_tools_table.item(row, 1).text())
  2131. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  2132. new_cutz = float('%.4f' % -new_cutz)
  2133. self.ui.cutz_entry.set_value(new_cutz)
  2134. # store the new CutZ value into storage (self.tools)
  2135. for tooluid_key, tooluid_value in self.tools.items():
  2136. if int(tooluid_key) == tool_uid:
  2137. tooluid_value['data']['cutz'] = new_cutz
  2138. def on_tooltable_cellwidget_change(self):
  2139. cw = self.sender()
  2140. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  2141. cw_row = cw_index.row()
  2142. cw_col = cw_index.column()
  2143. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  2144. # store the text of the cellWidget that changed it's index in the self.tools
  2145. for tooluid_key, tooluid_value in self.tools.items():
  2146. if int(tooluid_key) == current_uid:
  2147. cb_txt = cw.currentText()
  2148. if cw_col == 2:
  2149. tooluid_value['offset'] = cb_txt
  2150. if cb_txt == 'Custom':
  2151. self.ui.tool_offset_entry.show()
  2152. self.ui.tool_offset_lbl.show()
  2153. else:
  2154. self.ui.tool_offset_entry.hide()
  2155. self.ui.tool_offset_lbl.hide()
  2156. # reset the offset_value in storage self.tools
  2157. tooluid_value['offset_value'] = 0.0
  2158. elif cw_col == 3:
  2159. # force toolpath type as 'Iso' if the tool type is V-Shape
  2160. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  2161. tooluid_value['type'] = 'Iso'
  2162. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2163. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2164. else:
  2165. tooluid_value['type'] = cb_txt
  2166. elif cw_col == 4:
  2167. tooluid_value['tool_type'] = cb_txt
  2168. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  2169. if cb_txt == 'V':
  2170. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2171. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2172. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  2173. def update_form(self, dict_storage):
  2174. for form_key in self.form_fields:
  2175. for storage_key in dict_storage:
  2176. if form_key == storage_key:
  2177. try:
  2178. self.form_fields[form_key].set_value(dict_storage[form_key])
  2179. except Exception as e:
  2180. log.debug(str(e))
  2181. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  2182. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  2183. self.ui.ois_dwell_geo.on_cb_change()
  2184. self.ui.ois_mpass_geo.on_cb_change()
  2185. self.ui.ois_tcz_geo.on_cb_change()
  2186. def gui_form_to_storage(self):
  2187. self.ui_disconnect()
  2188. widget_changed = self.sender()
  2189. try:
  2190. widget_idx = self.ui.grid3.indexOf(widget_changed)
  2191. except:
  2192. return
  2193. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  2194. if widget_idx == 1 or widget_idx == 3:
  2195. self.update_cutz()
  2196. # the original connect() function of the OptionalInpuSelection is no longer working because of the
  2197. # ui_diconnect() so I use this 'hack'
  2198. if isinstance(widget_changed, FCCheckBox):
  2199. if widget_changed.text() == 'Multi-Depth:':
  2200. self.ui.ois_mpass_geo.on_cb_change()
  2201. if widget_changed.text() == 'Tool change':
  2202. self.ui.ois_tcz_geo.on_cb_change()
  2203. if widget_changed.text() == 'Dwell:':
  2204. self.ui.ois_dwell_geo.on_cb_change()
  2205. row = self.ui.geo_tools_table.currentRow()
  2206. if row < 0:
  2207. row = 0
  2208. # store all the data associated with the row parameter to the self.tools storage
  2209. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  2210. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  2211. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  2212. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  2213. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  2214. offset_value_item = self.ui.tool_offset_entry.get_value()
  2215. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  2216. temp_tools = {}
  2217. temp_dia = {}
  2218. temp_data = {}
  2219. for tooluid_key, tooluid_value in self.tools.items():
  2220. if int(tooluid_key) == tooluid_item:
  2221. for key, value in tooluid_value.items():
  2222. if key == 'tooldia':
  2223. temp_dia[key] = tooldia_item
  2224. # update the 'offset', 'type' and 'tool_type' sections
  2225. if key == 'offset':
  2226. temp_dia[key] = offset_item
  2227. if key == 'type':
  2228. temp_dia[key] = type_item
  2229. if key == 'tool_type':
  2230. temp_dia[key] = tool_type_item
  2231. if key == 'offset_value':
  2232. temp_dia[key] = offset_value_item
  2233. if key == 'data':
  2234. # update the 'data' section
  2235. for data_key in tooluid_value[key].keys():
  2236. for form_key, form_value in self.form_fields.items():
  2237. if form_key == data_key:
  2238. temp_data[data_key] = form_value.get_value()
  2239. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  2240. # updated from self.app.defaults
  2241. if data_key not in self.form_fields:
  2242. temp_data[data_key] = value[data_key]
  2243. temp_dia[key] = dict(temp_data)
  2244. temp_data.clear()
  2245. if key == 'solid_geometry':
  2246. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  2247. temp_tools[tooluid_key] = dict(temp_dia)
  2248. else:
  2249. temp_tools[tooluid_key] = dict(tooluid_value)
  2250. self.tools.clear()
  2251. self.tools = dict(temp_tools)
  2252. temp_tools.clear()
  2253. self.ui_connect()
  2254. def select_tools_table_row(self, row, clearsel=None):
  2255. if clearsel:
  2256. self.ui.geo_tools_table.clearSelection()
  2257. if self.ui.geo_tools_table.rowCount() > 0:
  2258. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  2259. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  2260. def export_dxf(self):
  2261. units = self.app.general_options_form.general_group.units_radio.get_value().upper()
  2262. dwg = None
  2263. try:
  2264. dwg = ezdxf.new('R2010')
  2265. msp = dwg.modelspace()
  2266. def g2dxf(dxf_space, geo):
  2267. if isinstance(geo, MultiPolygon):
  2268. for poly in geo:
  2269. ext_points = list(poly.exterior.coords)
  2270. dxf_space.add_lwpolyline(ext_points)
  2271. for interior in poly.interiors:
  2272. dxf_space.add_lwpolyline(list(interior.coords))
  2273. if isinstance(geo, Polygon):
  2274. ext_points = list(geo.exterior.coords)
  2275. dxf_space.add_lwpolyline(ext_points)
  2276. for interior in geo.interiors:
  2277. dxf_space.add_lwpolyline(list(interior.coords))
  2278. if isinstance(geo, MultiLineString):
  2279. for line in geo:
  2280. dxf_space.add_lwpolyline(list(line.coords))
  2281. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  2282. dxf_space.add_lwpolyline(list(geo.coords))
  2283. multigeo_solid_geometry = []
  2284. if self.multigeo:
  2285. for tool in self.tools:
  2286. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  2287. else:
  2288. multigeo_solid_geometry = self.solid_geometry
  2289. for geo in multigeo_solid_geometry:
  2290. if type(geo) == list:
  2291. for g in geo:
  2292. g2dxf(msp, g)
  2293. else:
  2294. g2dxf(msp, geo)
  2295. # points = FlatCAMGeometry.get_pts(geo)
  2296. # msp.add_lwpolyline(points)
  2297. except Exception as e:
  2298. log.debug(str(e))
  2299. return dwg
  2300. def get_selected_tools_table_items(self):
  2301. """
  2302. Returns a list of lists, each list in the list is made out of row elements
  2303. :return: List of table_tools items.
  2304. :rtype: list
  2305. """
  2306. table_tools_items = []
  2307. for x in self.ui.geo_tools_table.selectedItems():
  2308. table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  2309. for column in range(0, self.ui.geo_tools_table.columnCount())])
  2310. for item in table_tools_items:
  2311. item[0] = str(item[0])
  2312. return table_tools_items
  2313. def on_pp_changed(self):
  2314. current_pp = self.ui.pp_geometry_name_cb.get_value()
  2315. if current_pp == 'hpgl':
  2316. self.old_pp_state = self.ui.mpass_cb.get_value()
  2317. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  2318. self.ui.mpass_cb.set_value(False)
  2319. self.ui.mpass_cb.setDisabled(True)
  2320. self.ui.toolchangeg_cb.set_value(True)
  2321. self.ui.toolchangeg_cb.setDisabled(True)
  2322. else:
  2323. self.ui.mpass_cb.set_value(self.old_pp_state)
  2324. self.ui.mpass_cb.setDisabled(False)
  2325. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  2326. self.ui.toolchangeg_cb.setDisabled(False)
  2327. def on_generatecnc_button_click(self, *args):
  2328. self.app.report_usage("geometry_on_generatecnc_button")
  2329. self.read_form()
  2330. # test to see if we have tools available in the tool table
  2331. if self.ui.geo_tools_table.selectedItems():
  2332. for x in self.ui.geo_tools_table.selectedItems():
  2333. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  2334. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  2335. for tooluid_key, tooluid_value in self.tools.items():
  2336. if int(tooluid_key) == tooluid:
  2337. self.sel_tools.update({
  2338. tooluid: dict(tooluid_value)
  2339. })
  2340. self.mtool_gen_cncjob()
  2341. self.ui.geo_tools_table.clearSelection()
  2342. else:
  2343. self.app.inform.emit("[error_notcl] Failed. No tool selected in the tool table ...")
  2344. def mtool_gen_cncjob(self, use_thread=True):
  2345. """
  2346. Creates a multi-tool CNCJob out of this Geometry object.
  2347. The actual work is done by the target FlatCAMCNCjob object's
  2348. `generate_from_geometry_2()` method.
  2349. :param z_cut: Cut depth (negative)
  2350. :param z_move: Hight of the tool when travelling (not cutting)
  2351. :param feedrate: Feed rate while cutting on X - Y plane
  2352. :param feedrate_z: Feed rate while cutting on Z plane
  2353. :param feedrate_rapid: Feed rate while moving with rapids
  2354. :param tooldia: Tool diameter
  2355. :param outname: Name of the new object
  2356. :param spindlespeed: Spindle speed (RPM)
  2357. :param ppname_g Name of the postprocessor
  2358. :return: None
  2359. """
  2360. offset_str = ''
  2361. multitool_gcode = ''
  2362. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  2363. outname = "%s_%s" % (self.options["name"], 'cnc')
  2364. # Object initialization function for app.new_object()
  2365. # RUNNING ON SEPARATE THREAD!
  2366. def job_init_single_geometry(job_obj, app_obj):
  2367. assert isinstance(job_obj, FlatCAMCNCjob), \
  2368. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2369. # count the tools
  2370. tool_cnt = 0
  2371. dia_cnc_dict = {}
  2372. # this turn on the FlatCAMCNCJob plot for multiple tools
  2373. job_obj.multitool = True
  2374. job_obj.multigeo = False
  2375. job_obj.cnc_tools.clear()
  2376. # job_obj.create_geometry()
  2377. job_obj.options['Tools_in_use'] = self.get_selected_tools_table_items()
  2378. for tooluid_key in self.sel_tools:
  2379. tool_cnt += 1
  2380. app_obj.progress.emit(20)
  2381. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  2382. if diadict_key == 'tooldia':
  2383. tooldia_val = float('%.4f' % float(diadict_value))
  2384. dia_cnc_dict.update({
  2385. diadict_key: tooldia_val
  2386. })
  2387. if diadict_key == 'offset':
  2388. o_val = diadict_value.lower()
  2389. dia_cnc_dict.update({
  2390. diadict_key: o_val
  2391. })
  2392. if diadict_key == 'type':
  2393. t_val = diadict_value
  2394. dia_cnc_dict.update({
  2395. diadict_key: t_val
  2396. })
  2397. if diadict_key == 'tool_type':
  2398. tt_val = diadict_value
  2399. dia_cnc_dict.update({
  2400. diadict_key: tt_val
  2401. })
  2402. if diadict_key == 'data':
  2403. for data_key, data_value in diadict_value.items():
  2404. if data_key == "multidepth":
  2405. multidepth = data_value
  2406. if data_key == "depthperpass":
  2407. depthpercut = data_value
  2408. if data_key == "extracut":
  2409. extracut = data_value
  2410. if data_key == "startz":
  2411. startz = data_value
  2412. if data_key == "endz":
  2413. endz = data_value
  2414. if data_key == "toolchangez":
  2415. toolchangez =data_value
  2416. if data_key == "toolchangexy":
  2417. toolchangexy = data_value
  2418. if data_key == "toolchange":
  2419. toolchange = data_value
  2420. if data_key == "cutz":
  2421. z_cut = data_value
  2422. if data_key == "travelz":
  2423. z_move = data_value
  2424. if data_key == "feedrate":
  2425. feedrate = data_value
  2426. if data_key == "feedrate_z":
  2427. feedrate_z = data_value
  2428. if data_key == "feedrate_rapid":
  2429. feedrate_rapid = data_value
  2430. if data_key == "ppname_g":
  2431. pp_geometry_name = data_value
  2432. if data_key == "spindlespeed":
  2433. spindlespeed = data_value
  2434. if data_key == "dwell":
  2435. dwell = data_value
  2436. if data_key == "dwelltime":
  2437. dwelltime = data_value
  2438. datadict = dict(diadict_value)
  2439. dia_cnc_dict.update({
  2440. diadict_key: datadict
  2441. })
  2442. if dia_cnc_dict['offset'] == 'in':
  2443. tool_offset = -dia_cnc_dict['tooldia'] / 2
  2444. offset_str = 'inside'
  2445. elif dia_cnc_dict['offset'].lower() == 'out':
  2446. tool_offset = dia_cnc_dict['tooldia'] / 2
  2447. offset_str = 'outside'
  2448. elif dia_cnc_dict['offset'].lower() == 'path':
  2449. offset_str = 'onpath'
  2450. tool_offset = 0.0
  2451. else:
  2452. offset_str = 'custom'
  2453. offset_value = self.ui.tool_offset_entry.get_value()
  2454. if offset_value:
  2455. tool_offset = float(offset_value)
  2456. else:
  2457. self.app.inform.emit(
  2458. "[warning] Tool Offset is selected in Tool Table but no value is provided.\n"
  2459. "Add a Tool Offset or change the Offset Type."
  2460. )
  2461. return
  2462. dia_cnc_dict.update({
  2463. 'offset_value': tool_offset
  2464. })
  2465. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  2466. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  2467. # Propagate options
  2468. job_obj.options["tooldia"] = tooldia_val
  2469. job_obj.options['type'] = 'Geometry'
  2470. job_obj.options['tool_dia'] = tooldia_val
  2471. app_obj.progress.emit(40)
  2472. dia_cnc_dict['gcode'] = job_obj.generate_from_geometry_2(
  2473. self, tooldia=tooldia_val, offset=tool_offset, tolerance=0.0005,
  2474. z_cut=z_cut, z_move=z_move,
  2475. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  2476. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  2477. multidepth=multidepth, depthpercut=depthpercut,
  2478. extracut=extracut, startz=startz, endz=endz,
  2479. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  2480. pp_geometry_name=pp_geometry_name,
  2481. tool_no=tool_cnt)
  2482. app_obj.progress.emit(50)
  2483. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  2484. # object is the source of gcode
  2485. job_obj.toolchange_xy = "geometry"
  2486. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  2487. # TODO this serve for bounding box creation only; should be optimized
  2488. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  2489. app_obj.progress.emit(80)
  2490. job_obj.cnc_tools.update({
  2491. tooluid_key: dict(dia_cnc_dict)
  2492. })
  2493. dia_cnc_dict.clear()
  2494. # Object initialization function for app.new_object()
  2495. # RUNNING ON SEPARATE THREAD!
  2496. def job_init_multi_geometry(job_obj, app_obj):
  2497. assert isinstance(job_obj, FlatCAMCNCjob), \
  2498. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2499. # count the tools
  2500. tool_cnt = 0
  2501. dia_cnc_dict = {}
  2502. current_uid = int(1)
  2503. # this turn on the FlatCAMCNCJob plot for multiple tools
  2504. job_obj.multitool = True
  2505. job_obj.multigeo = True
  2506. job_obj.cnc_tools.clear()
  2507. for tooluid_key in self.sel_tools:
  2508. tool_cnt += 1
  2509. app_obj.progress.emit(20)
  2510. # find the tool_dia associated with the tooluid_key
  2511. sel_tool_dia = self.sel_tools[tooluid_key]['tooldia']
  2512. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  2513. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  2514. for k, v in self.tools.items():
  2515. if float('%.4f' % float(v['tooldia'])) == float('%.4f' % float(sel_tool_dia)):
  2516. current_uid = int(k)
  2517. break
  2518. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  2519. if diadict_key == 'tooldia':
  2520. tooldia_val = float('%.4f' % float(diadict_value))
  2521. dia_cnc_dict.update({
  2522. diadict_key: tooldia_val
  2523. })
  2524. if diadict_key == 'offset':
  2525. o_val = diadict_value.lower()
  2526. dia_cnc_dict.update({
  2527. diadict_key: o_val
  2528. })
  2529. if diadict_key == 'type':
  2530. t_val = diadict_value
  2531. dia_cnc_dict.update({
  2532. diadict_key: t_val
  2533. })
  2534. if diadict_key == 'tool_type':
  2535. tt_val = diadict_value
  2536. dia_cnc_dict.update({
  2537. diadict_key: tt_val
  2538. })
  2539. if diadict_key == 'data':
  2540. for data_key, data_value in diadict_value.items():
  2541. if data_key == "multidepth":
  2542. multidepth = data_value
  2543. if data_key == "depthperpass":
  2544. depthpercut = data_value
  2545. if data_key == "extracut":
  2546. extracut = data_value
  2547. if data_key == "startz":
  2548. startz = data_value
  2549. if data_key == "endz":
  2550. endz = data_value
  2551. if data_key == "toolchangez":
  2552. toolchangez =data_value
  2553. if data_key == "toolchangexy":
  2554. toolchangexy = data_value
  2555. if data_key == "toolchange":
  2556. toolchange = data_value
  2557. if data_key == "cutz":
  2558. z_cut = data_value
  2559. if data_key == "travelz":
  2560. z_move = data_value
  2561. if data_key == "feedrate":
  2562. feedrate = data_value
  2563. if data_key == "feedrate_z":
  2564. feedrate_z = data_value
  2565. if data_key == "feedrate_rapid":
  2566. feedrate_rapid = data_value
  2567. if data_key == "ppname_g":
  2568. pp_geometry_name = data_value
  2569. if data_key == "spindlespeed":
  2570. spindlespeed = data_value
  2571. if data_key == "dwell":
  2572. dwell = data_value
  2573. if data_key == "dwelltime":
  2574. dwelltime = data_value
  2575. datadict = dict(diadict_value)
  2576. dia_cnc_dict.update({
  2577. diadict_key: datadict
  2578. })
  2579. if dia_cnc_dict['offset'] == 'in':
  2580. tool_offset = -dia_cnc_dict['tooldia'] / 2
  2581. offset_str = 'inside'
  2582. elif dia_cnc_dict['offset'].lower() == 'out':
  2583. tool_offset = dia_cnc_dict['tooldia'] / 2
  2584. offset_str = 'outside'
  2585. elif dia_cnc_dict['offset'].lower() == 'path':
  2586. offset_str = 'onpath'
  2587. tool_offset = 0.0
  2588. else:
  2589. offset_str = 'custom'
  2590. offset_value = self.ui.tool_offset_entry.get_value()
  2591. if offset_value:
  2592. tool_offset = float(offset_value)
  2593. else:
  2594. self.app.inform.emit(
  2595. "[warning] Tool Offset is selected in Tool Table but no value is provided.\n"
  2596. "Add a Tool Offset or change the Offset Type."
  2597. )
  2598. return
  2599. dia_cnc_dict.update({
  2600. 'offset_value': tool_offset
  2601. })
  2602. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  2603. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  2604. # Propagate options
  2605. job_obj.options["tooldia"] = tooldia_val
  2606. job_obj.options['type'] = 'Geometry'
  2607. job_obj.options['tool_dia'] = tooldia_val
  2608. app_obj.progress.emit(40)
  2609. tool_solid_geometry = self.tools[current_uid]['solid_geometry']
  2610. dia_cnc_dict['gcode'] = job_obj.generate_from_multitool_geometry(
  2611. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  2612. tolerance=0.0005, z_cut=z_cut, z_move=z_move,
  2613. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  2614. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  2615. multidepth=multidepth, depthpercut=depthpercut,
  2616. extracut=extracut, startz=startz, endz=endz,
  2617. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  2618. pp_geometry_name=pp_geometry_name,
  2619. tool_no=tool_cnt)
  2620. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  2621. # TODO this serve for bounding box creation only; should be optimized
  2622. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  2623. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  2624. # object is the source of gcode
  2625. job_obj.toolchange_xy = "geometry"
  2626. app_obj.progress.emit(80)
  2627. job_obj.cnc_tools.update({
  2628. tooluid_key: dict(dia_cnc_dict)
  2629. })
  2630. dia_cnc_dict.clear()
  2631. if use_thread:
  2632. # To be run in separate thread
  2633. # The idea is that if there is a solid_geometry in the file "root" then most likely thare are no
  2634. # separate solid_geometry in the self.tools dictionary
  2635. def job_thread(app_obj):
  2636. if self.solid_geometry:
  2637. with self.app.proc_container.new("Generating CNC Code"):
  2638. app_obj.new_object("cncjob", outname, job_init_single_geometry)
  2639. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  2640. app_obj.progress.emit(100)
  2641. else:
  2642. with self.app.proc_container.new("Generating CNC Code"):
  2643. app_obj.new_object("cncjob", outname, job_init_multi_geometry)
  2644. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  2645. app_obj.progress.emit(100)
  2646. # Create a promise with the name
  2647. self.app.collection.promise(outname)
  2648. # Send to worker
  2649. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2650. else:
  2651. if self.solid_geometry:
  2652. self.app.new_object("cncjob", outname, job_init_single_geometry)
  2653. else:
  2654. self.app.new_object("cncjob", outname, job_init_multi_geometry)
  2655. def generatecncjob(self, outname=None,
  2656. tooldia=None, offset=None,
  2657. z_cut=None, z_move=None,
  2658. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  2659. spindlespeed=None, dwell=None, dwelltime=None,
  2660. multidepth=None, depthperpass=None,
  2661. toolchange=None, toolchangez=None, toolchangexy=None,
  2662. extracut=None, startz=None, endz=None,
  2663. ppname_g=None,
  2664. use_thread=True):
  2665. """
  2666. Only used for TCL Command.
  2667. Creates a CNCJob out of this Geometry object. The actual
  2668. work is done by the target FlatCAMCNCjob object's
  2669. `generate_from_geometry_2()` method.
  2670. :param z_cut: Cut depth (negative)
  2671. :param z_move: Hight of the tool when travelling (not cutting)
  2672. :param feedrate: Feed rate while cutting on X - Y plane
  2673. :param feedrate_z: Feed rate while cutting on Z plane
  2674. :param feedrate_rapid: Feed rate while moving with rapids
  2675. :param tooldia: Tool diameter
  2676. :param outname: Name of the new object
  2677. :param spindlespeed: Spindle speed (RPM)
  2678. :param ppname_g Name of the postprocessor
  2679. :return: None
  2680. """
  2681. tooldia = tooldia if tooldia else self.options["cnctooldia"]
  2682. outname = outname if outname is not None else self.options["name"]
  2683. z_cut = z_cut if z_cut is not None else self.options["cutz"]
  2684. z_move = z_move if z_move is not None else self.options["travelz"]
  2685. feedrate = feedrate if feedrate is not None else self.options["feedrate"]
  2686. feedrate_z = feedrate_z if feedrate_z is not None else self.options["feedrate_z"]
  2687. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else self.options["feedrate_rapid"]
  2688. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  2689. depthperpass = depthperpass if depthperpass is not None else self.options["depthperpass"]
  2690. extracut = extracut if extracut is not None else self.options["extracut"]
  2691. startz = startz if startz is not None else self.options["startz"]
  2692. endz = endz if endz is not None else self.options["endz"]
  2693. toolchangez = toolchangez if toolchangez else self.options["toolchangez"]
  2694. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  2695. toolchange = toolchange if toolchange else self.options["toolchange"]
  2696. offset = offset if offset else 0.0
  2697. # int or None.
  2698. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  2699. dwell = dwell if dwell else self.options["dwell"]
  2700. dwelltime = dwelltime if dwelltime else self.options["dwelltime"]
  2701. ppname_g = ppname_g if ppname_g else self.options["ppname_g"]
  2702. # Object initialization function for app.new_object()
  2703. # RUNNING ON SEPARATE THREAD!
  2704. def job_init(job_obj, app_obj):
  2705. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2706. # Propagate options
  2707. job_obj.options["tooldia"] = tooldia
  2708. app_obj.progress.emit(20)
  2709. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  2710. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  2711. app_obj.progress.emit(40)
  2712. job_obj.options['type'] = 'Geometry'
  2713. job_obj.options['tool_dia'] = tooldia
  2714. # TODO: The tolerance should not be hard coded. Just for testing.
  2715. job_obj.generate_from_geometry_2(self, tooldia=tooldia, offset=offset, tolerance=0.0005,
  2716. z_cut=z_cut, z_move=z_move,
  2717. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  2718. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  2719. multidepth=multidepth, depthpercut=depthperpass,
  2720. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  2721. extracut=extracut, startz=startz, endz=endz,
  2722. pp_geometry_name=ppname_g
  2723. )
  2724. app_obj.progress.emit(50)
  2725. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  2726. # source of gcode
  2727. job_obj.toolchange_xy = "geometry"
  2728. job_obj.gcode_parse()
  2729. app_obj.progress.emit(80)
  2730. if use_thread:
  2731. # To be run in separate thread
  2732. def job_thread(app_obj):
  2733. with self.app.proc_container.new("Generating CNC Code"):
  2734. app_obj.new_object("cncjob", outname, job_init)
  2735. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  2736. app_obj.progress.emit(100)
  2737. # Create a promise with the name
  2738. self.app.collection.promise(outname)
  2739. # Send to worker
  2740. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2741. else:
  2742. self.app.new_object("cncjob", outname, job_init)
  2743. # def on_plot_cb_click(self, *args): # TODO: args not needed
  2744. # if self.muted_ui:
  2745. # return
  2746. # self.read_form_item('plot')
  2747. def scale(self, xfactor, yfactor=None, point=None):
  2748. """
  2749. Scales all geometry by a given factor.
  2750. :param xfactor: Factor by which to scale the object's geometry/
  2751. :type xfactor: float
  2752. :param yfactor: Factor by which to scale the object's geometry/
  2753. :type yfactor: float
  2754. :return: None
  2755. :rtype: None
  2756. """
  2757. if yfactor is None:
  2758. yfactor = xfactor
  2759. if point is None:
  2760. px = 0
  2761. py = 0
  2762. else:
  2763. px, py = point
  2764. if type(self.solid_geometry) == list:
  2765. geo_list = self.flatten(self.solid_geometry)
  2766. self.solid_geometry = []
  2767. # for g in geo_list:
  2768. # self.solid_geometry.append(affinity.scale(g, xfactor, yfactor, origin=(px, py)))
  2769. self.solid_geometry = [affinity.scale(g, xfactor, yfactor, origin=(px, py))
  2770. for g in geo_list]
  2771. else:
  2772. self.solid_geometry = affinity.scale(self.solid_geometry, xfactor, yfactor,
  2773. origin=(px, py))
  2774. def offset(self, vect):
  2775. """
  2776. Offsets all geometry by a given vector/
  2777. :param vect: (x, y) vector by which to offset the object's geometry.
  2778. :type vect: tuple
  2779. :return: None
  2780. :rtype: None
  2781. """
  2782. dx, dy = vect
  2783. def translate_recursion(geom):
  2784. if type(geom) == list:
  2785. geoms=list()
  2786. for local_geom in geom:
  2787. geoms.append(translate_recursion(local_geom))
  2788. return geoms
  2789. else:
  2790. return affinity.translate(geom, xoff=dx, yoff=dy)
  2791. if self.multigeo is True:
  2792. for tool in self.tools:
  2793. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  2794. else:
  2795. self.solid_geometry=translate_recursion(self.solid_geometry)
  2796. def convert_units(self, units):
  2797. self.ui_disconnect()
  2798. factor = Geometry.convert_units(self, units)
  2799. self.options['cutz'] *= factor
  2800. self.options['depthperpass'] *= factor
  2801. self.options['travelz'] *= factor
  2802. self.options['feedrate'] *= factor
  2803. self.options['feedrate_z'] *= factor
  2804. self.options['feedrate_rapid'] *= factor
  2805. self.options['endz'] *= factor
  2806. # self.options['cnctooldia'] *= factor
  2807. self.options['painttooldia'] *= factor
  2808. self.options['paintmargin'] *= factor
  2809. self.options['paintoverlap'] *= factor
  2810. self.options["toolchangez"] *= factor
  2811. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  2812. coords_xy[0] *= factor
  2813. coords_xy[1] *= factor
  2814. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2815. if self.options['startz'] is not None:
  2816. self.options['startz'] *= factor
  2817. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  2818. 'endz', 'toolchangez']
  2819. temp_tools_dict = {}
  2820. tool_dia_copy = {}
  2821. data_copy = {}
  2822. for tooluid_key, tooluid_value in self.tools.items():
  2823. for dia_key, dia_value in tooluid_value.items():
  2824. if dia_key == 'tooldia':
  2825. dia_value *= factor
  2826. dia_value = float('%.4f' % dia_value)
  2827. tool_dia_copy[dia_key] = dia_value
  2828. if dia_key == 'offset':
  2829. tool_dia_copy[dia_key] = dia_value
  2830. if dia_key == 'offset_value':
  2831. dia_value *= factor
  2832. tool_dia_copy[dia_key] = dia_value
  2833. # convert the value in the Custom Tool Offset entry in UI
  2834. custom_offset = self.ui.tool_offset_entry.get_value()
  2835. if custom_offset:
  2836. custom_offset *= factor
  2837. self.ui.tool_offset_entry.set_value(custom_offset)
  2838. if dia_key == 'type':
  2839. tool_dia_copy[dia_key] = dia_value
  2840. if dia_key == 'tool_type':
  2841. tool_dia_copy[dia_key] = dia_value
  2842. if dia_key == 'data':
  2843. for data_key, data_value in dia_value.items():
  2844. # convert the form fields that are convertible
  2845. for param in param_list:
  2846. if data_key == param and data_value is not None:
  2847. data_copy[data_key] = data_value * factor
  2848. # copy the other dict entries that are not convertible
  2849. if data_key not in param_list:
  2850. data_copy[data_key] = data_value
  2851. tool_dia_copy[dia_key] = dict(data_copy)
  2852. data_copy.clear()
  2853. temp_tools_dict.update({
  2854. tooluid_key: dict(tool_dia_copy)
  2855. })
  2856. tool_dia_copy.clear()
  2857. self.tools.clear()
  2858. self.tools = dict(temp_tools_dict)
  2859. # if there is a value in the new tool field then convert that one too
  2860. tooldia = self.ui.addtool_entry.get_value()
  2861. if tooldia:
  2862. tooldia *= factor
  2863. # limit the decimals to 2 for METRIC and 3 for INCH
  2864. if units.lower() == 'in':
  2865. tooldia = float('%.4f' % tooldia)
  2866. else:
  2867. tooldia = float('%.2f' % tooldia)
  2868. self.ui.addtool_entry.set_value(tooldia)
  2869. return factor
  2870. def plot_element(self, element, color='red', visible=None):
  2871. visible = visible if visible else self.options['plot']
  2872. try:
  2873. for sub_el in element:
  2874. self.plot_element(sub_el)
  2875. except TypeError: # Element is not iterable...
  2876. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  2877. def plot(self, visible=None):
  2878. """
  2879. Adds the object into collection.
  2880. :return: None
  2881. """
  2882. # Does all the required setup and returns False
  2883. # if the 'ptint' option is set to False.
  2884. if not FlatCAMObj.plot(self):
  2885. return
  2886. try:
  2887. # plot solid geometries found as members of self.tools attribute dict
  2888. # for MultiGeo
  2889. if self.multigeo == True: # geo multi tool usage
  2890. for tooluid_key in self.tools:
  2891. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  2892. self.plot_element(solid_geometry, visible=visible)
  2893. # plot solid geometry that may be an direct attribute of the geometry object
  2894. # for SingleGeo
  2895. if self.solid_geometry:
  2896. self.plot_element(self.solid_geometry, visible=visible)
  2897. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  2898. self.shapes.redraw()
  2899. except (ObjectDeleted, AttributeError):
  2900. self.shapes.clear(update=True)
  2901. def on_plot_cb_click(self, *args):
  2902. if self.muted_ui:
  2903. return
  2904. self.plot()
  2905. self.read_form_item('plot')
  2906. self.ui_disconnect()
  2907. cb_flag = self.ui.plot_cb.isChecked()
  2908. for row in range(self.ui.geo_tools_table.rowCount()):
  2909. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  2910. if cb_flag:
  2911. table_cb.setChecked(True)
  2912. else:
  2913. table_cb.setChecked(False)
  2914. self.ui_connect()
  2915. def on_plot_cb_click_table(self):
  2916. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  2917. self.ui_disconnect()
  2918. cw = self.sender()
  2919. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  2920. cw_row = cw_index.row()
  2921. check_row = 0
  2922. self.shapes.clear(update=True)
  2923. for tooluid_key in self.tools:
  2924. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  2925. # find the geo_tool_table row associated with the tooluid_key
  2926. for row in range(self.ui.geo_tools_table.rowCount()):
  2927. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  2928. if tooluid_item == int(tooluid_key):
  2929. check_row = row
  2930. break
  2931. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  2932. self.plot_element(element=solid_geometry, visible=True)
  2933. self.shapes.redraw()
  2934. # make sure that the general plot is disabled if one of the row plot's are disabled and
  2935. # if all the row plot's are enabled also enable the general plot checkbox
  2936. cb_cnt = 0
  2937. total_row = self.ui.geo_tools_table.rowCount()
  2938. for row in range(total_row):
  2939. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  2940. cb_cnt += 1
  2941. else:
  2942. cb_cnt -= 1
  2943. if cb_cnt < total_row:
  2944. self.ui.plot_cb.setChecked(False)
  2945. else:
  2946. self.ui.plot_cb.setChecked(True)
  2947. self.ui_connect()
  2948. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  2949. """
  2950. Represents G-Code.
  2951. """
  2952. optionChanged = QtCore.pyqtSignal(str)
  2953. ui_type = CNCObjectUI
  2954. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  2955. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  2956. spindlespeed=None):
  2957. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  2958. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  2959. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  2960. spindlespeed=spindlespeed, steps_per_circle=self.app.defaults["cncjob_steps_per_circle"])
  2961. FlatCAMObj.__init__(self, name)
  2962. self.kind = "cncjob"
  2963. self.options.update({
  2964. "plot": True,
  2965. "tooldia": 0.03937, # 0.4mm in inches
  2966. "append": "",
  2967. "prepend": "",
  2968. "dwell": False,
  2969. "dwelltime": 1,
  2970. "type": 'Geometry'
  2971. })
  2972. '''
  2973. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  2974. diameter of the tools and the value is another dict that will hold the data under the following form:
  2975. {tooldia: {
  2976. 'tooluid': 1,
  2977. 'offset': 'Path',
  2978. 'type_item': 'Rough',
  2979. 'tool_type': 'C1',
  2980. 'data': {} # a dict to hold the parameters
  2981. 'gcode': "" # a string with the actual GCODE
  2982. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  2983. 'solid_geometry': []
  2984. },
  2985. ...
  2986. }
  2987. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  2988. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  2989. '''
  2990. self.cnc_tools = {}
  2991. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  2992. # (like the one in the TCL Command), False
  2993. self.multitool = False
  2994. # used for parsing the GCode lines to adjust the offset when the GCode was offseted
  2995. offsetx_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  2996. self.g_offsetx_re = re.compile(offsetx_re_string)
  2997. offsety_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  2998. self.g_offsety_re = re.compile(offsety_re_string)
  2999. # Attributes to be included in serialization
  3000. # Always append to it because it carries contents
  3001. # from predecessors.
  3002. self.ser_attrs += ['options', 'kind', 'cnc_tools', 'multitool']
  3003. self.annotation = self.app.plotcanvas.new_text_group()
  3004. def build_ui(self):
  3005. self.ui_disconnect()
  3006. FlatCAMObj.build_ui(self)
  3007. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  3008. if self.cnc_tools:
  3009. self.ui.cnc_tools_table.show()
  3010. self.ui.plot_options_label.show()
  3011. else:
  3012. self.ui.cnc_tools_table.hide()
  3013. self.ui.plot_options_label.hide()
  3014. offset = 0
  3015. tool_idx = 0
  3016. n = len(self.cnc_tools)
  3017. self.ui.cnc_tools_table.setRowCount(n)
  3018. for dia_key, dia_value in self.cnc_tools.items():
  3019. tool_idx += 1
  3020. row_no = tool_idx - 1
  3021. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  3022. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  3023. self.ui.cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  3024. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  3025. # There are no tool bits in MM with more than 2 decimals diameter.
  3026. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  3027. if self.units == 'MM':
  3028. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(dia_value['tooldia']))
  3029. else:
  3030. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(dia_value['tooldia']))
  3031. offset_txt = list(str(dia_value['offset']))
  3032. offset_txt[0] = offset_txt[0].upper()
  3033. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  3034. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  3035. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  3036. id.setFlags(QtCore.Qt.ItemIsEnabled)
  3037. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3038. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3039. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3040. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3041. # hack so the checkbox stay centered in the table cell
  3042. # used this:
  3043. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  3044. # plot_item = QtWidgets.QWidget()
  3045. # checkbox = FCCheckBox()
  3046. # checkbox.setCheckState(QtCore.Qt.Checked)
  3047. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  3048. # qhboxlayout.addWidget(checkbox)
  3049. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  3050. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  3051. plot_item = FCCheckBox()
  3052. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  3053. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  3054. if self.ui.plot_cb.isChecked():
  3055. plot_item.setChecked(True)
  3056. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  3057. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  3058. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  3059. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  3060. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  3061. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  3062. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  3063. # make the diameter column editable
  3064. # for row in range(tool_idx):
  3065. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  3066. # QtCore.Qt.ItemIsEnabled)
  3067. for row in range(tool_idx):
  3068. self.ui.cnc_tools_table.item(row, 0).setFlags(
  3069. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  3070. self.ui.cnc_tools_table.resizeColumnsToContents()
  3071. self.ui.cnc_tools_table.resizeRowsToContents()
  3072. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  3073. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  3074. vertical_header.hide()
  3075. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3076. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  3077. horizontal_header.setMinimumSectionSize(10)
  3078. horizontal_header.setDefaultSectionSize(70)
  3079. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  3080. horizontal_header.resizeSection(0, 20)
  3081. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  3082. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  3083. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  3084. horizontal_header.resizeSection(4, 40)
  3085. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  3086. horizontal_header.resizeSection(4, 17)
  3087. # horizontal_header.setStretchLastSection(True)
  3088. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3089. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  3090. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  3091. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  3092. # self.ui.geo_tools_table.setSortingEnabled(True)
  3093. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  3094. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  3095. self.ui_connect()
  3096. def set_ui(self, ui):
  3097. FlatCAMObj.set_ui(self, ui)
  3098. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  3099. assert isinstance(self.ui, CNCObjectUI), \
  3100. "Expected a CNCObjectUI, got %s" % type(self.ui)
  3101. self.form_fields.update({
  3102. "plot": self.ui.plot_cb,
  3103. # "tooldia": self.ui.tooldia_entry,
  3104. "append": self.ui.append_text,
  3105. "prepend": self.ui.prepend_text,
  3106. })
  3107. # Fill form fields only on object create
  3108. self.to_form()
  3109. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  3110. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  3111. self.ui.modify_gcode_button.clicked.connect(self.on_modifygcode_button_click)
  3112. def ui_connect(self):
  3113. for row in range(self.ui.cnc_tools_table.rowCount()):
  3114. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  3115. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  3116. def ui_disconnect(self):
  3117. for row in range(self.ui.cnc_tools_table.rowCount()):
  3118. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  3119. try:
  3120. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  3121. except:
  3122. pass
  3123. def on_updateplot_button_click(self, *args):
  3124. """
  3125. Callback for the "Updata Plot" button. Reads the form for updates
  3126. and plots the object.
  3127. """
  3128. self.read_form()
  3129. self.plot()
  3130. def on_exportgcode_button_click(self, *args):
  3131. self.app.report_usage("cncjob_on_exportgcode_button")
  3132. self.read_form()
  3133. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  3134. _filter_ = "RML1 Files (*.rol);;" \
  3135. "All Files (*.*)"
  3136. elif 'hpgl' in self.pp_geometry_name:
  3137. _filter_ = "HPGL Files (*.plt);;" \
  3138. "All Files (*.*)"
  3139. else:
  3140. _filter_ = "G-Code Files (*.nc);;G-Code Files (*.txt);;G-Code Files (*.tap);;G-Code Files (*.cnc);;" \
  3141. "G-Code Files (*.g-code);;All Files (*.*)"
  3142. try:
  3143. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3144. caption="Export Machine Code ...", directory=self.app.get_last_save_folder(), filter=_filter_)[0])
  3145. except TypeError:
  3146. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export Machine Code ...", filter=_filter_)[0])
  3147. preamble = str(self.ui.prepend_text.get_value())
  3148. postamble = str(self.ui.append_text.get_value())
  3149. self.export_gcode(filename, preamble=preamble, postamble=postamble)
  3150. self.app.file_saved.emit("gcode", filename)
  3151. self.app.inform.emit("[success] Machine Code file saved to: %s" % filename)
  3152. def on_modifygcode_button_click(self, *args):
  3153. # add the tab if it was closed
  3154. self.app.ui.plot_tab_area.addTab(self.app.ui.cncjob_tab, "CNC Code Editor")
  3155. # delete the absolute and relative position and messages in the infobar
  3156. self.app.ui.position_label.setText("")
  3157. self.app.ui.rel_position_label.setText("")
  3158. # Switch plot_area to CNCJob tab
  3159. self.app.ui.plot_tab_area.setCurrentWidget(self.app.ui.cncjob_tab)
  3160. preamble = str(self.ui.prepend_text.get_value())
  3161. postamble = str(self.ui.append_text.get_value())
  3162. self.app.gcode_edited = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  3163. # first clear previous text in text editor (if any)
  3164. self.app.ui.code_editor.clear()
  3165. # then append the text from GCode to the text editor
  3166. for line in self.app.gcode_edited:
  3167. proc_line = str(line).strip('\n')
  3168. self.app.ui.code_editor.append(proc_line)
  3169. self.app.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3170. self.app.handleTextChanged()
  3171. self.app.ui.show()
  3172. def gcode_header(self):
  3173. log.debug("FlatCAMCNCJob.gcode_header()")
  3174. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  3175. marlin = False
  3176. hpgl = False
  3177. try:
  3178. for key in self.cnc_tools:
  3179. if self.cnc_tools[key]['data']['ppname_g'] == 'marlin':
  3180. marlin = True
  3181. break
  3182. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  3183. hpgl = True
  3184. break
  3185. except Exception as e:
  3186. log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  3187. try:
  3188. for key in self.cnc_tools:
  3189. if self.cnc_tools[key]['data']['ppname_e'] == 'marlin':
  3190. marlin = True
  3191. break
  3192. except:
  3193. pass
  3194. if marlin is True:
  3195. gcode = ';Marlin G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  3196. (str(self.app.version), str(self.app.version_date)) + '\n'
  3197. gcode += ';Name: ' + str(self.options['name']) + '\n'
  3198. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  3199. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  3200. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  3201. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  3202. gcode += ';Created on ' + time_str + '\n' + '\n'
  3203. elif hpgl is True:
  3204. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  3205. (str(self.app.version), str(self.app.version_date)) + '";\n'
  3206. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  3207. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  3208. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  3209. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  3210. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  3211. gcode += 'CO "Created on ' + time_str + '";\n'
  3212. else:
  3213. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  3214. (str(self.app.version), str(self.app.version_date)) + '\n'
  3215. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  3216. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  3217. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  3218. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  3219. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  3220. gcode += '(Created on ' + time_str + ')\n' + '\n'
  3221. return gcode
  3222. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  3223. gcode = ''
  3224. roland = False
  3225. hpgl = False
  3226. # detect if using Roland postprocessor
  3227. try:
  3228. for key in self.cnc_tools:
  3229. if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  3230. roland = True
  3231. break
  3232. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  3233. hpgl = True
  3234. break
  3235. except:
  3236. try:
  3237. for key in self.cnc_tools:
  3238. if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  3239. roland = True
  3240. break
  3241. except:
  3242. pass
  3243. # do not add gcode_header when using the Roland postprocessor, add it for every other postprocessor
  3244. if roland is False and hpgl is False:
  3245. gcode = self.gcode_header()
  3246. # detect if using multi-tool and make the Gcode summation correctly for each case
  3247. if self.multitool is True:
  3248. for tooluid_key in self.cnc_tools:
  3249. for key, value in self.cnc_tools[tooluid_key].items():
  3250. if key == 'gcode':
  3251. gcode += value
  3252. break
  3253. else:
  3254. gcode += self.gcode
  3255. if roland is True:
  3256. g = preamble + gcode + postamble
  3257. elif hpgl is True:
  3258. g = self.gcode_header() + preamble + gcode + postamble
  3259. else:
  3260. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  3261. g_idx = gcode.rfind('G20')
  3262. # if it did not find 'G20' then search for 'G21'
  3263. if g_idx == -1:
  3264. g_idx = gcode.rfind('G21')
  3265. # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  3266. if g_idx == -1:
  3267. self.app.inform.emit("[error_notcl] G-code does not have a units code: either G20 or G21")
  3268. return
  3269. g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble
  3270. # lines = StringIO(self.gcode)
  3271. lines = StringIO(g)
  3272. ## Write
  3273. if filename is not None:
  3274. try:
  3275. with open(filename, 'w') as f:
  3276. for line in lines:
  3277. f.write(line)
  3278. except FileNotFoundError:
  3279. self.app.inform.emit("[warning_notcl] No such file or directory")
  3280. return
  3281. elif to_file is False:
  3282. # Just for adding it to the recent files list.
  3283. self.app.file_opened.emit("cncjob", filename)
  3284. self.app.inform.emit("[success] Saved to: " + filename)
  3285. else:
  3286. return lines
  3287. def get_gcode(self, preamble='', postamble=''):
  3288. #we need this to be able get_gcode separatelly for shell command export_gcode
  3289. return preamble + '\n' + self.gcode + "\n" + postamble
  3290. def get_svg(self):
  3291. # we need this to be able get_svg separately for shell command export_svg
  3292. pass
  3293. def on_plot_cb_click(self, *args):
  3294. if self.muted_ui:
  3295. return
  3296. self.plot()
  3297. self.read_form_item('plot')
  3298. self.ui_disconnect()
  3299. cb_flag = self.ui.plot_cb.isChecked()
  3300. for row in range(self.ui.cnc_tools_table.rowCount()):
  3301. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  3302. if cb_flag:
  3303. table_cb.setChecked(True)
  3304. else:
  3305. table_cb.setChecked(False)
  3306. self.ui_connect()
  3307. def on_plot_cb_click_table(self):
  3308. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  3309. self.ui_disconnect()
  3310. cw = self.sender()
  3311. cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  3312. cw_row = cw_index.row()
  3313. self.shapes.clear(update=True)
  3314. for tooluid_key in self.cnc_tools:
  3315. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  3316. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  3317. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  3318. if self.ui.cnc_tools_table.cellWidget((tooluid_key - 1), 6).isChecked():
  3319. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed)
  3320. self.shapes.redraw()
  3321. # make sure that the general plot is disabled if one of the row plot's are disabled and
  3322. # if all the row plot's are enabled also enable the general plot checkbox
  3323. cb_cnt = 0
  3324. total_row = self.ui.cnc_tools_table.rowCount()
  3325. for row in range(total_row):
  3326. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  3327. cb_cnt += 1
  3328. else:
  3329. cb_cnt -= 1
  3330. if cb_cnt < total_row:
  3331. self.ui.plot_cb.setChecked(False)
  3332. else:
  3333. self.ui.plot_cb.setChecked(True)
  3334. self.ui_connect()
  3335. def plot(self, visible=None):
  3336. # Does all the required setup and returns False
  3337. # if the 'ptint' option is set to False.
  3338. if not FlatCAMObj.plot(self):
  3339. return
  3340. visible = visible if visible else self.options['plot']
  3341. try:
  3342. if self.multitool is False: # single tool usage
  3343. self.plot2(tooldia=self.options["tooldia"], obj=self, visible=visible)
  3344. else:
  3345. # multiple tools usage
  3346. for tooluid_key in self.cnc_tools:
  3347. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  3348. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  3349. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed)
  3350. self.shapes.redraw()
  3351. except (ObjectDeleted, AttributeError):
  3352. self.shapes.clear(update=True)
  3353. self.annotation.clear(update=True)
  3354. def convert_units(self, units):
  3355. factor = CNCjob.convert_units(self, units)
  3356. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  3357. self.options["tooldia"] *= factor
  3358. # end of file