FlatCAMApp.py 242 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966
  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. import sys
  9. import traceback
  10. import urllib.request, urllib.parse, urllib.error
  11. import getopt
  12. import os
  13. import random
  14. import logging
  15. import simplejson as json
  16. import re
  17. import os
  18. import tkinter as tk
  19. from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
  20. import time # Just used for debugging. Double check before removing.
  21. import urllib.request, urllib.parse, urllib.error
  22. import webbrowser
  23. from contextlib import contextmanager
  24. from xml.dom.minidom import parseString as parse_xml_string
  25. from copy import copy,deepcopy
  26. import numpy as np
  27. from datetime import datetime
  28. import gc
  29. ########################################
  30. ## Imports part of FlatCAM ##
  31. ########################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from PlotCanvas import *
  35. from FlatCAMGUI import *
  36. from FlatCAMCommon import LoudDict
  37. from FlatCAMPostProc import load_postprocessors
  38. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  39. from FlatCAMProcess import *
  40. from FlatCAMWorkerStack import WorkerStack
  41. from VisPyVisuals import Color
  42. from vispy.gloo.util import _screenshot
  43. from vispy.io import write_png
  44. from flatcamTools import *
  45. from multiprocessing import Pool
  46. import tclCommands
  47. from ParseFont import *
  48. ########################################
  49. ## App ##
  50. ########################################
  51. class App(QtCore.QObject):
  52. """
  53. The main application class. The constructor starts the GUI.
  54. """
  55. # Get Cmd Line Options
  56. cmd_line_shellfile = ''
  57. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  58. try:
  59. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  60. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  61. except getopt.GetoptError:
  62. print(cmd_line_help)
  63. sys.exit(2)
  64. for opt, arg in cmd_line_options:
  65. if opt == '-h':
  66. print(cmd_line_help)
  67. sys.exit()
  68. elif opt == '--shellfile':
  69. cmd_line_shellfile = arg
  70. # Logging ##
  71. log = logging.getLogger('base')
  72. log.setLevel(logging.DEBUG)
  73. # log.setLevel(logging.WARNING)
  74. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  75. handler = logging.StreamHandler()
  76. handler.setFormatter(formatter)
  77. log.addHandler(handler)
  78. # Version
  79. version = 9.0
  80. version_date = "2019/01/06"
  81. beta = True
  82. # URL for update checks and statistics
  83. version_url = "http://flatcam.org/version"
  84. # App URL
  85. app_url = "http://flatcam.org"
  86. # Manual URL
  87. manual_url = "http://flatcam.org/manual/index.html"
  88. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  89. ##################
  90. ## Signals ##
  91. ##################
  92. # Inform the user
  93. # Handled by:
  94. # * App.info() --> Print on the status bar
  95. inform = QtCore.pyqtSignal(str)
  96. # General purpose background task
  97. worker_task = QtCore.pyqtSignal(dict)
  98. # File opened
  99. # Handled by:
  100. # * register_folder()
  101. # * register_recent()
  102. # Note: Setting the parameters to unicode does not seem
  103. # to have an effect. Then are received as Qstring
  104. # anyway.
  105. # File type and filename
  106. file_opened = QtCore.pyqtSignal(str, str)
  107. # File type and filename
  108. file_saved = QtCore.pyqtSignal(str, str)
  109. # Percentage of progress
  110. progress = QtCore.pyqtSignal(int)
  111. plots_updated = QtCore.pyqtSignal()
  112. # Emitted by new_object() and passes the new object as argument, plot flag.
  113. # on_object_created() adds the object to the collection, plots on appropriate flag
  114. # and emits new_object_available.
  115. object_created = QtCore.pyqtSignal(object, bool, bool)
  116. # Emitted when a object has been changed (like scaled, mirrored)
  117. object_changed = QtCore.pyqtSignal(object)
  118. # Emitted after object has been plotted.
  119. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  120. object_plotted = QtCore.pyqtSignal(object)
  121. # Emitted when a new object has been added to the collection
  122. # and is ready to be used.
  123. new_object_available = QtCore.pyqtSignal(object)
  124. message = QtCore.pyqtSignal(str, str, str)
  125. # Emmited when shell command is finished(one command only)
  126. shell_command_finished = QtCore.pyqtSignal(object)
  127. # Emitted when multiprocess pool has been recreated
  128. pool_recreated = QtCore.pyqtSignal(object)
  129. # Emitted when an unhandled exception happens
  130. # in the worker task.
  131. thread_exception = QtCore.pyqtSignal(object)
  132. def __init__(self, user_defaults=True, post_gui=None):
  133. """
  134. Starts the application.
  135. :return: app
  136. :rtype: App
  137. """
  138. App.log.info("FlatCAM Starting...")
  139. ###################
  140. ### OS-specific ###
  141. ###################
  142. # Folder for user settings.
  143. if sys.platform == 'win32':
  144. from win32com.shell import shell, shellcon
  145. if platform.architecture()[0] == '32bit':
  146. App.log.debug("Win32!")
  147. else:
  148. App.log.debug("Win64!")
  149. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  150. '/FlatCAM'
  151. self.os = 'windows'
  152. else: # Linux/Unix/MacOS
  153. self.data_path = os.path.expanduser('~') + \
  154. '/.FlatCAM'
  155. self.os = 'unix'
  156. ###############################
  157. ### Setup folders and files ###
  158. ###############################
  159. if not os.path.exists(self.data_path):
  160. os.makedirs(self.data_path)
  161. App.log.debug('Created data folder: ' + self.data_path)
  162. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  163. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  164. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  165. if not os.path.exists(self.postprocessorpaths):
  166. os.makedirs(self.postprocessorpaths)
  167. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  168. # create defaults.json file if there is none
  169. try:
  170. f = open(self.data_path + '/defaults.json')
  171. f.close()
  172. except IOError:
  173. App.log.debug('Creating empty defaults.json')
  174. f = open(self.data_path + '/defaults.json', 'w')
  175. json.dump({}, f)
  176. f.close()
  177. # create factory_defaults.json file if there is none
  178. try:
  179. f = open(self.data_path + '/factory_defaults.json')
  180. f.close()
  181. except IOError:
  182. App.log.debug('Creating empty factory_defaults.json')
  183. f = open(self.data_path + '/factory_defaults.json', 'w')
  184. json.dump({}, f)
  185. f.close()
  186. try:
  187. f = open(self.data_path + '/recent.json')
  188. f.close()
  189. except IOError:
  190. App.log.debug('Creating empty recent.json')
  191. f = open(self.data_path + '/recent.json', 'w')
  192. json.dump([], f)
  193. f.close()
  194. # Application directory. CHDIR to it. Otherwise, trying to load
  195. # GUI icons will fail as their path is relative.
  196. # This will fail under cx_freeze ...
  197. self.app_home = os.path.dirname(os.path.realpath(__file__))
  198. App.log.debug("Application path is " + self.app_home)
  199. App.log.debug("Started in " + os.getcwd())
  200. # cx_freeze workaround
  201. if os.path.isfile(self.app_home):
  202. self.app_home = os.path.dirname(self.app_home)
  203. os.chdir(self.app_home)
  204. # Create multiprocessing pool
  205. self.pool = Pool()
  206. ####################
  207. ## Initialize GUI ##
  208. ####################
  209. # FlatCAM colors used in plotting
  210. self.FC_light_green = '#BBF268BF'
  211. self.FC_dark_green = '#006E20BF'
  212. self.FC_light_blue = '#a5a5ffbf'
  213. self.FC_dark_blue = '#0000ffbf'
  214. QtCore.QObject.__init__(self)
  215. self.ui = FlatCAMGUI(self.version, self.beta, self)
  216. # self.connect(self.ui,
  217. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  218. # self.save_geometry) PyQt4
  219. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  220. self.ui.final_save.connect(self.final_save)
  221. ##############
  222. #### Data ####
  223. ##############
  224. self.recent = []
  225. self.clipboard = QtWidgets.QApplication.clipboard()
  226. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  227. self.project_filename = None
  228. self.toggle_units_ignore = False
  229. # self.defaults_form = PreferencesUI()
  230. self.general_defaults_form = GeneralPreferencesUI()
  231. self.gerber_defaults_form = GerberPreferencesUI()
  232. self.excellon_defaults_form = ExcellonPreferencesUI()
  233. self.geometry_defaults_form = GeometryPreferencesUI()
  234. self.cncjob_defaults_form = CNCJobPreferencesUI()
  235. # when adding entries here read the comments in the method found bellow named:
  236. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  237. self.defaults_form_fields = {
  238. "units": self.general_defaults_form.general_group.units_radio,
  239. "global_shell_at_startup": self.general_defaults_form.general_group.shell_startup_cb,
  240. "global_gridx": self.general_defaults_form.general_group.gridx_entry,
  241. "global_gridy": self.general_defaults_form.general_group.gridy_entry,
  242. "global_plot_fill": self.general_defaults_form.general_group.pf_color_entry,
  243. "global_plot_line": self.general_defaults_form.general_group.pl_color_entry,
  244. "global_sel_fill": self.general_defaults_form.general_group.sf_color_entry,
  245. "global_sel_line": self.general_defaults_form.general_group.sl_color_entry,
  246. "global_alt_sel_fill": self.general_defaults_form.general_group.alt_sf_color_entry,
  247. "global_alt_sel_line": self.general_defaults_form.general_group.alt_sl_color_entry,
  248. "global_draw_color": self.general_defaults_form.general_group.draw_color_entry,
  249. "global_sel_draw_color": self.general_defaults_form.general_group.sel_draw_color_entry,
  250. "global_pan_button": self.general_defaults_form.general_group.pan_button_radio,
  251. "global_mselect_key": self.general_defaults_form.general_group.mselect_radio,
  252. # "global_pan_with_space_key": self.general_defaults_form.general_group.pan_with_space_cb,
  253. "global_workspace": self.general_defaults_form.general_group.workspace_cb,
  254. "global_workspaceT": self.general_defaults_form.general_group.wk_cb,
  255. "gerber_plot": self.gerber_defaults_form.gerber_group.plot_cb,
  256. "gerber_solid": self.gerber_defaults_form.gerber_group.solid_cb,
  257. "gerber_multicolored": self.gerber_defaults_form.gerber_group.multicolored_cb,
  258. "gerber_isotooldia": self.gerber_defaults_form.gerber_group.iso_tool_dia_entry,
  259. "gerber_isopasses": self.gerber_defaults_form.gerber_group.iso_width_entry,
  260. "gerber_isooverlap": self.gerber_defaults_form.gerber_group.iso_overlap_entry,
  261. "gerber_ncctools": self.gerber_defaults_form.gerber_group.ncc_tool_dia_entry,
  262. "gerber_nccoverlap": self.gerber_defaults_form.gerber_group.ncc_overlap_entry,
  263. "gerber_nccmargin": self.gerber_defaults_form.gerber_group.ncc_margin_entry,
  264. "gerber_nccmethod": self.gerber_defaults_form.gerber_group.ncc_method_radio,
  265. "gerber_nccconnect": self.gerber_defaults_form.gerber_group.ncc_connect_cb,
  266. "gerber_ncccontour": self.gerber_defaults_form.gerber_group.ncc_contour_cb,
  267. "gerber_nccrest": self.gerber_defaults_form.gerber_group.ncc_rest_cb,
  268. "gerber_combine_passes": self.gerber_defaults_form.gerber_group.combine_passes_cb,
  269. "gerber_milling_type": self.gerber_defaults_form.gerber_group.milling_type_radio,
  270. "gerber_cutouttooldia": self.gerber_defaults_form.gerber_group.cutout_tooldia_entry,
  271. "gerber_cutoutmargin": self.gerber_defaults_form.gerber_group.cutout_margin_entry,
  272. "gerber_cutoutgapsize": self.gerber_defaults_form.gerber_group.cutout_gap_entry,
  273. "gerber_gaps": self.gerber_defaults_form.gerber_group.gaps_radio,
  274. "gerber_noncoppermargin": self.gerber_defaults_form.gerber_group.noncopper_margin_entry,
  275. "gerber_noncopperrounded": self.gerber_defaults_form.gerber_group.noncopper_rounded_cb,
  276. "gerber_bboxmargin": self.gerber_defaults_form.gerber_group.bbmargin_entry,
  277. "gerber_bboxrounded": self.gerber_defaults_form.gerber_group.bbrounded_cb,
  278. "gerber_circle_steps": self.gerber_defaults_form.gerber_group.circle_steps_entry,
  279. "excellon_plot": self.excellon_defaults_form.excellon_group.plot_cb,
  280. "excellon_solid": self.excellon_defaults_form.excellon_group.solid_cb,
  281. "excellon_drillz": self.excellon_defaults_form.excellon_group.cutz_entry,
  282. "excellon_travelz": self.excellon_defaults_form.excellon_group.travelz_entry,
  283. "excellon_feedrate": self.excellon_defaults_form.excellon_group.feedrate_entry,
  284. "excellon_feedrate_rapid": self.excellon_defaults_form.excellon_group.feedrate_rapid_entry,
  285. "excellon_spindlespeed": self.excellon_defaults_form.excellon_group.spindlespeed_entry,
  286. "excellon_dwell": self.excellon_defaults_form.excellon_group.dwell_cb,
  287. "excellon_dwelltime": self.excellon_defaults_form.excellon_group.dwelltime_entry,
  288. "excellon_toolchange": self.excellon_defaults_form.excellon_group.toolchange_cb,
  289. "excellon_toolchangez": self.excellon_defaults_form.excellon_group.toolchangez_entry,
  290. "excellon_toolchangexy": self.excellon_defaults_form.excellon_group.toolchangexy_entry,
  291. "excellon_ppname_e": self.excellon_defaults_form.excellon_group.pp_excellon_name_cb,
  292. "excellon_startz": self.excellon_defaults_form.excellon_group.estartz_entry,
  293. "excellon_endz": self.excellon_defaults_form.excellon_group.eendz_entry,
  294. "excellon_tooldia": self.excellon_defaults_form.excellon_group.tooldia_entry,
  295. "excellon_slot_tooldia": self.excellon_defaults_form.excellon_group.slot_tooldia_entry,
  296. "excellon_format_upper_in": self.excellon_defaults_form.excellon_group.excellon_format_upper_in_entry,
  297. "excellon_format_lower_in": self.excellon_defaults_form.excellon_group.excellon_format_lower_in_entry,
  298. "excellon_format_upper_mm": self.excellon_defaults_form.excellon_group.excellon_format_upper_mm_entry,
  299. "excellon_format_lower_mm": self.excellon_defaults_form.excellon_group.excellon_format_lower_mm_entry,
  300. "excellon_zeros": self.excellon_defaults_form.excellon_group.excellon_zeros_radio,
  301. "excellon_units": self.excellon_defaults_form.excellon_group.excellon_units_radio,
  302. "excellon_optimization_type": self.excellon_defaults_form.excellon_group.excellon_optimization_radio,
  303. "excellon_gcode_type": self.excellon_defaults_form.excellon_group.excellon_gcode_type_radio,
  304. "geometry_plot": self.geometry_defaults_form.geometry_group.plot_cb,
  305. "geometry_cutz": self.geometry_defaults_form.geometry_group.cutz_entry,
  306. "geometry_travelz": self.geometry_defaults_form.geometry_group.travelz_entry,
  307. "geometry_feedrate": self.geometry_defaults_form.geometry_group.cncfeedrate_entry,
  308. "geometry_feedrate_z": self.geometry_defaults_form.geometry_group.cncplunge_entry,
  309. "geometry_feedrate_rapid": self.geometry_defaults_form.geometry_group.cncfeedrate_rapid_entry,
  310. "geometry_cnctooldia": self.geometry_defaults_form.geometry_group.cnctooldia_entry,
  311. "geometry_painttooldia": self.geometry_defaults_form.geometry_group.painttooldia_entry,
  312. "geometry_spindlespeed": self.geometry_defaults_form.geometry_group.cncspindlespeed_entry,
  313. "geometry_dwell": self.geometry_defaults_form.geometry_group.dwell_cb,
  314. "geometry_dwelltime": self.geometry_defaults_form.geometry_group.dwelltime_entry,
  315. "geometry_paintoverlap": self.geometry_defaults_form.geometry_group.paintoverlap_entry,
  316. "geometry_paintmargin": self.geometry_defaults_form.geometry_group.paintmargin_entry,
  317. "geometry_paintmethod": self.geometry_defaults_form.geometry_group.paintmethod_combo,
  318. "geometry_selectmethod": self.geometry_defaults_form.geometry_group.selectmethod_combo,
  319. "geometry_pathconnect": self.geometry_defaults_form.geometry_group.pathconnect_cb,
  320. "geometry_paintcontour": self.geometry_defaults_form.geometry_group.contour_cb,
  321. "geometry_ppname_g": self.geometry_defaults_form.geometry_group.pp_geometry_name_cb,
  322. "geometry_toolchange": self.geometry_defaults_form.geometry_group.toolchange_cb,
  323. "geometry_toolchangez": self.geometry_defaults_form.geometry_group.toolchangez_entry,
  324. "geometry_toolchangexy": self.geometry_defaults_form.geometry_group.toolchangexy_entry,
  325. "geometry_startz": self.geometry_defaults_form.geometry_group.gstartz_entry,
  326. "geometry_endz": self.geometry_defaults_form.geometry_group.gendz_entry,
  327. "geometry_multidepth": self.geometry_defaults_form.geometry_group.multidepth_cb,
  328. "geometry_depthperpass": self.geometry_defaults_form.geometry_group.depthperpass_entry,
  329. "geometry_extracut": self.geometry_defaults_form.geometry_group.extracut_cb,
  330. "geometry_circle_steps": self.geometry_defaults_form.geometry_group.circle_steps_entry,
  331. "cncjob_plot": self.cncjob_defaults_form.cncjob_group.plot_cb,
  332. "cncjob_tooldia": self.cncjob_defaults_form.cncjob_group.tooldia_entry,
  333. "cncjob_coords_decimals": self.cncjob_defaults_form.cncjob_group.coords_dec_entry,
  334. "cncjob_fr_decimals": self.cncjob_defaults_form.cncjob_group.fr_dec_entry,
  335. "cncjob_prepend": self.cncjob_defaults_form.cncjob_group.prepend_text,
  336. "cncjob_append": self.cncjob_defaults_form.cncjob_group.append_text,
  337. "cncjob_steps_per_circle": self.cncjob_defaults_form.cncjob_group.steps_per_circle_entry
  338. }
  339. # loads postprocessors
  340. self.postprocessors = load_postprocessors(self)
  341. for name in list(self.postprocessors.keys()):
  342. self.geometry_defaults_form.geometry_group.pp_geometry_name_cb.addItem(name)
  343. self.excellon_defaults_form.excellon_group.pp_excellon_name_cb.addItem(name)
  344. self.defaults = LoudDict()
  345. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  346. self.defaults.update({
  347. "global_serial": 0,
  348. "global_stats": {},
  349. "units": "IN",
  350. "global_gridx": 1.0,
  351. "global_gridy": 1.0,
  352. "global_plot_fill": '#BBF268BF',
  353. "global_plot_line": '#006E20BF',
  354. "global_sel_fill": '#a5a5ffbf',
  355. "global_sel_line": '#0000ffbf',
  356. "global_alt_sel_fill": '#BBF268BF',
  357. "global_alt_sel_line": '#006E20BF',
  358. "global_draw_color": '#FF0000',
  359. "global_sel_draw_color": '#0000FF',
  360. "global_pan_button": '2',
  361. "global_mselect_key": 'Control',
  362. # "global_pan_with_space_key": False,
  363. "global_workspace": False,
  364. "global_workspaceT": "A4P",
  365. "global_toolbar_view": 31,
  366. "gerber_plot": True,
  367. "gerber_solid": True,
  368. "gerber_multicolored": False,
  369. "gerber_isotooldia": 0.016,
  370. "gerber_isopasses": 1,
  371. "gerber_isooverlap": 0.15,
  372. "gerber_ncctools": "1.0, 0.5",
  373. "gerber_nccoverlap": 0.4,
  374. "gerber_nccmargin": 1,
  375. "gerber_nccmethod": "seed",
  376. "gerber_nccconnect": True,
  377. "gerber_ncccontour": True,
  378. "gerber_nccrest": False,
  379. "gerber_combine_passes": False,
  380. "gerber_milling_type": "cl",
  381. "gerber_cutouttooldia": 0.07,
  382. "gerber_cutoutmargin": 0.1,
  383. "gerber_cutoutgapsize": 0.15,
  384. "gerber_gaps": "4",
  385. "gerber_noncoppermargin": 0.0,
  386. "gerber_noncopperrounded": False,
  387. "gerber_bboxmargin": 0.0,
  388. "gerber_bboxrounded": False,
  389. "gerber_circle_steps": 64,
  390. "excellon_plot": True,
  391. "excellon_solid": False,
  392. "excellon_drillz": -0.1,
  393. "excellon_travelz": 0.1,
  394. "excellon_feedrate": 3.0,
  395. "excellon_feedrate_rapid": 3.0,
  396. "excellon_spindlespeed": None,
  397. "excellon_dwell": False,
  398. "excellon_dwelltime": 1,
  399. "excellon_toolchange": False,
  400. "excellon_toolchangez": 1.0,
  401. "excellon_toolchangexy": "0.0, 0.0",
  402. "excellon_tooldia": 0.016,
  403. "excellon_slot_tooldia": 0.016,
  404. "excellon_startz": None,
  405. "excellon_endz": 2.0,
  406. "excellon_ppname_e": 'default',
  407. "excellon_format_upper_in": 2,
  408. "excellon_format_lower_in": 4,
  409. "excellon_format_upper_mm": 3,
  410. "excellon_format_lower_mm": 3,
  411. "excellon_zeros": "L",
  412. "excellon_units": "INCH",
  413. "excellon_optimization_type": 'B',
  414. "excellon_search_time": 3,
  415. "excellon_gcode_type": "drills",
  416. "geometry_plot": True,
  417. "geometry_cutz": -0.002,
  418. "geometry_travelz": 0.1,
  419. "geometry_toolchange": False,
  420. "geometry_toolchangez": 1.0,
  421. "geometry_toolchangexy": "0.0, 0.0",
  422. "geometry_startz": None,
  423. "geometry_endz": 2.0,
  424. "geometry_feedrate": 3.0,
  425. "geometry_feedrate_z": 3.0,
  426. "geometry_feedrate_rapid": 3.0,
  427. "geometry_cnctooldia": 0.016,
  428. "geometry_spindlespeed": None,
  429. "geometry_dwell": False,
  430. "geometry_dwelltime": 1,
  431. "geometry_painttooldia": 0.07,
  432. "geometry_paintoverlap": 0.15,
  433. "geometry_paintmargin": 0.0,
  434. "geometry_paintmethod": "seed",
  435. "geometry_selectmethod": "single",
  436. "geometry_pathconnect": True,
  437. "geometry_paintcontour": True,
  438. "geometry_ppname_g": 'default',
  439. "geometry_depthperpass": 0.002,
  440. "geometry_multidepth": False,
  441. "geometry_extracut": False,
  442. "geometry_circle_steps": 64,
  443. "cncjob_plot": True,
  444. "cncjob_tooldia": 0.0393701,
  445. "cncjob_coords_decimals": 4,
  446. "cncjob_fr_decimals": 2,
  447. "cncjob_prepend": "",
  448. "cncjob_append": "",
  449. "cncjob_steps_per_circle": 64,
  450. "global_background_timeout": 300000, # Default value is 5 minutes
  451. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  452. # (python trace only for unknown errors),
  453. # 1 = show trace(show trace allways),
  454. # 2 = (For the future).
  455. # Persistence
  456. "global_last_folder": None,
  457. "global_last_save_folder": None,
  458. # Default window geometry
  459. "global_def_win_x": 100,
  460. "global_def_win_y": 100,
  461. "global_def_win_w": 1024,
  462. "global_def_win_h": 650,
  463. # Constants...
  464. "global_defaults_save_period_ms": 20000, # Time between default saves.
  465. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  466. "global_shell_at_startup": False, # Show the shell at startup.
  467. "global_recent_limit": 10, # Max. items in recent list.
  468. "fit_key": '1',
  469. "zoom_out_key": '2',
  470. "zoom_in_key": '3',
  471. "grid_toggle_key": 'G',
  472. "zoom_ratio": 1.5,
  473. "global_point_clipboard_format": "(%.4f, %.4f)",
  474. "global_zdownrate": None,
  475. "gerber_use_buffer_for_union": True
  476. })
  477. ###############################
  478. ### Load defaults from file ###
  479. if user_defaults:
  480. self.load_defaults()
  481. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  482. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  483. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  484. self.save_defaults(silent=True)
  485. self.propagate_defaults(silent=True)
  486. self.restore_main_win_geom()
  487. def auto_save_defaults():
  488. try:
  489. self.save_defaults(silent=True)
  490. self.propagate_defaults(silent=True)
  491. finally:
  492. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  493. # the following lines activates automatic defaults save
  494. # if user_defaults:
  495. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  496. # self.options_form = PreferencesUI()
  497. self.general_options_form = GeneralPreferencesUI()
  498. self.gerber_options_form = GerberPreferencesUI()
  499. self.excellon_options_form = ExcellonPreferencesUI()
  500. self.geometry_options_form = GeometryPreferencesUI()
  501. self.cncjob_options_form = CNCJobPreferencesUI()
  502. self.options_form_fields = {
  503. "units": self.general_options_form.general_group.units_radio,
  504. "global_gridx": self.general_options_form.general_group.gridx_entry,
  505. "global_gridy": self.general_options_form.general_group.gridy_entry,
  506. "gerber_plot": self.gerber_options_form.gerber_group.plot_cb,
  507. "gerber_solid": self.gerber_options_form.gerber_group.solid_cb,
  508. "gerber_multicolored": self.gerber_options_form.gerber_group.multicolored_cb,
  509. "gerber_isotooldia": self.gerber_options_form.gerber_group.iso_tool_dia_entry,
  510. "gerber_isopasses": self.gerber_options_form.gerber_group.iso_width_entry,
  511. "gerber_isooverlap": self.gerber_options_form.gerber_group.iso_overlap_entry,
  512. "gerber_ncctools": self.gerber_options_form.gerber_group.ncc_tool_dia_entry,
  513. "gerber_nccoverlap": self.gerber_options_form.gerber_group.ncc_overlap_entry,
  514. "gerber_nccmargin": self.gerber_options_form.gerber_group.ncc_margin_entry,
  515. "gerber_combine_passes": self.gerber_options_form.gerber_group.combine_passes_cb,
  516. "gerber_cutouttooldia": self.gerber_options_form.gerber_group.cutout_tooldia_entry,
  517. "gerber_cutoutmargin": self.gerber_options_form.gerber_group.cutout_margin_entry,
  518. "gerber_cutoutgapsize": self.gerber_options_form.gerber_group.cutout_gap_entry,
  519. "gerber_gaps": self.gerber_options_form.gerber_group.gaps_radio,
  520. "gerber_noncoppermargin": self.gerber_options_form.gerber_group.noncopper_margin_entry,
  521. "gerber_noncopperrounded": self.gerber_options_form.gerber_group.noncopper_rounded_cb,
  522. "gerber_bboxmargin": self.gerber_options_form.gerber_group.bbmargin_entry,
  523. "gerber_bboxrounded": self.gerber_options_form.gerber_group.bbrounded_cb,
  524. "excellon_plot": self.excellon_options_form.excellon_group.plot_cb,
  525. "excellon_solid": self.excellon_options_form.excellon_group.solid_cb,
  526. "excellon_drillz": self.excellon_options_form.excellon_group.cutz_entry,
  527. "excellon_travelz": self.excellon_options_form.excellon_group.travelz_entry,
  528. "excellon_feedrate": self.excellon_options_form.excellon_group.feedrate_entry,
  529. "excellon_feedrate_rapid": self.excellon_options_form.excellon_group.feedrate_rapid_entry,
  530. "excellon_spindlespeed": self.excellon_options_form.excellon_group.spindlespeed_entry,
  531. "excellon_dwell": self.excellon_options_form.excellon_group.dwell_cb,
  532. "excellon_dwelltime": self.excellon_options_form.excellon_group.dwelltime_entry,
  533. "excellon_toolchange": self.excellon_options_form.excellon_group.toolchange_cb,
  534. "excellon_toolchangez": self.excellon_options_form.excellon_group.toolchangez_entry,
  535. "excellon_toolchangexy": self.excellon_options_form.excellon_group.toolchangexy_entry,
  536. "excellon_tooldia": self.excellon_options_form.excellon_group.tooldia_entry,
  537. "excellon_ppname_e": self.excellon_options_form.excellon_group.pp_excellon_name_cb,
  538. "excellon_startz": self.excellon_options_form.excellon_group.estartz_entry,
  539. "excellon_endz": self.excellon_options_form.excellon_group.eendz_entry,
  540. "excellon_format_upper_in": self.excellon_options_form.excellon_group.excellon_format_upper_in_entry,
  541. "excellon_format_lower_in": self.excellon_options_form.excellon_group.excellon_format_lower_in_entry,
  542. "excellon_format_upper_mm": self.excellon_options_form.excellon_group.excellon_format_upper_mm_entry,
  543. "excellon_format_lower_mm": self.excellon_options_form.excellon_group.excellon_format_lower_mm_entry,
  544. "excellon_zeros": self.excellon_options_form.excellon_group.excellon_zeros_radio,
  545. "excellon_units": self.excellon_options_form.excellon_group.excellon_units_radio,
  546. "excellon_optimization_type": self.excellon_options_form.excellon_group.excellon_optimization_radio,
  547. "geometry_plot": self.geometry_options_form.geometry_group.plot_cb,
  548. "geometry_cutz": self.geometry_options_form.geometry_group.cutz_entry,
  549. "geometry_travelz": self.geometry_options_form.geometry_group.travelz_entry,
  550. "geometry_feedrate": self.geometry_options_form.geometry_group.cncfeedrate_entry,
  551. "geometry_feedrate_z": self.geometry_options_form.geometry_group.cncplunge_entry,
  552. "geometry_feedrate_rapid": self.geometry_options_form.geometry_group.cncfeedrate_rapid_entry,
  553. "geometry_spindlespeed": self.geometry_options_form.geometry_group.cncspindlespeed_entry,
  554. "geometry_dwell": self.geometry_options_form.geometry_group.dwell_cb,
  555. "geometry_dwelltime": self.geometry_options_form.geometry_group.dwelltime_entry,
  556. "geometry_cnctooldia": self.geometry_options_form.geometry_group.cnctooldia_entry,
  557. "geometry_painttooldia": self.geometry_options_form.geometry_group.painttooldia_entry,
  558. "geometry_paintoverlap": self.geometry_options_form.geometry_group.paintoverlap_entry,
  559. "geometry_paintmargin": self.geometry_options_form.geometry_group.paintmargin_entry,
  560. "geometry_selectmethod": self.geometry_options_form.geometry_group.selectmethod_combo,
  561. "geometry_ppname_g": self.geometry_options_form.geometry_group.pp_geometry_name_cb,
  562. "geometry_toolchange": self.geometry_options_form.geometry_group.toolchange_cb,
  563. "geometry_toolchangez": self.geometry_options_form.geometry_group.toolchangez_entry,
  564. "geometry_toolchangexy": self.geometry_options_form.geometry_group.toolchangexy_entry,
  565. "geometry_startz": self.geometry_options_form.geometry_group.gstartz_entry,
  566. "geometry_endz": self.geometry_options_form.geometry_group.gendz_entry,
  567. "geometry_depthperpass": self.geometry_options_form.geometry_group.depthperpass_entry,
  568. "geometry_multidepth": self.geometry_options_form.geometry_group.multidepth_cb,
  569. "geometry_extracut": self.geometry_options_form.geometry_group.extracut_cb,
  570. "cncjob_plot": self.cncjob_options_form.cncjob_group.plot_cb,
  571. "cncjob_tooldia": self.cncjob_options_form.cncjob_group.tooldia_entry,
  572. "cncjob_prepend": self.cncjob_options_form.cncjob_group.prepend_text,
  573. "cncjob_append": self.cncjob_options_form.cncjob_group.append_text
  574. }
  575. for name in list(self.postprocessors.keys()):
  576. self.geometry_options_form.geometry_group.pp_geometry_name_cb.addItem(name)
  577. self.excellon_options_form.excellon_group.pp_excellon_name_cb.addItem(name)
  578. self.options = LoudDict()
  579. self.options.set_change_callback(self.on_options_dict_change)
  580. self.options.update({
  581. "units": "IN",
  582. "global_gridx": 1.0,
  583. "global_gridy": 1.0,
  584. "gerber_plot": True,
  585. "gerber_solid": True,
  586. "gerber_multicolored": False,
  587. "gerber_isotooldia": 0.016,
  588. "gerber_isopasses": 1,
  589. "gerber_isooverlap": 0.15,
  590. "gerber_ncctools": "1.0, 0.5",
  591. "gerber_nccoverlap": 0.4,
  592. "gerber_nccmargin": 1,
  593. "gerber_combine_passes": True,
  594. "gerber_cutouttooldia": 0.07,
  595. "gerber_cutoutmargin": 0.1,
  596. "gerber_cutoutgapsize": 0.15,
  597. "gerber_gaps": "4",
  598. "gerber_noncoppermargin": 0.0,
  599. "gerber_noncopperrounded": False,
  600. "gerber_bboxmargin": 0.0,
  601. "gerber_bboxrounded": False,
  602. "excellon_plot": True,
  603. "excellon_solid": False,
  604. "excellon_drillz": -0.1,
  605. "excellon_travelz": 0.1,
  606. "excellon_feedrate": 3.0,
  607. "excellon_feedrate_rapid": 3.0,
  608. "excellon_spindlespeed": None,
  609. "excellon_dwell": True,
  610. "excellon_dwelltime": 1000,
  611. "excellon_toolchange": False,
  612. "excellon_toolchangez": 1.0,
  613. "excellon_toolchangexy": "0.0, 0.0",
  614. "excellon_tooldia": 0.016,
  615. "excellon_ppname_e": 'default',
  616. "excellon_format_upper_in": 2,
  617. "excellon_format_lower_in": 4,
  618. "excellon_format_upper_mm": 3,
  619. "excellon_format_lower_mm": 3,
  620. "excellon_units": 'INCH',
  621. "excellon_optimization_type": 'B',
  622. "excellon_search_time": 3,
  623. "excellon_startz": None,
  624. "excellon_endz": 2.0,
  625. "excellon_zeros": "L",
  626. "geometry_plot": True,
  627. "geometry_cutz": -0.002,
  628. "geometry_travelz": 0.1,
  629. "geometry_feedrate": 3.0,
  630. "geometry_feedrate_z": 3.0,
  631. "geometry_feedrate_rapid": 3.0,
  632. "geometry_spindlespeed": None,
  633. "geometry_dwell": True,
  634. "geometry_dwelltime": 1000,
  635. "geometry_cnctooldia": 0.016,
  636. "geometry_painttooldia": 0.07,
  637. "geometry_paintoverlap": 0.15,
  638. "geometry_paintmargin": 0.0,
  639. "geometry_selectmethod": "single",
  640. "geometry_toolchange": False,
  641. "geometry_toolchangez": 2.0,
  642. "geometry_toolchangexy": "0.0, 0.0",
  643. "geometry_startz": None,
  644. "geometry_endz": 2.0,
  645. "geometry_ppname_g": "default",
  646. "geometry_depthperpass": 0.002,
  647. "geometry_multidepth": False,
  648. "geometry_extracut": False,
  649. "cncjob_plot": True,
  650. "cncjob_tooldia": 0.016,
  651. "cncjob_prepend": "",
  652. "cncjob_append": "",
  653. "global_background_timeout": 300000, # Default value is 5 minutes
  654. "global_verbose_error_level": 0, # Shell verbosity:
  655. # 0 = default(python trace only for unknown errors),
  656. # 1 = show trace(show trace allways), 2 = (For the future).
  657. })
  658. self.options.update(self.defaults) # Copy app defaults to project options
  659. self.gen_form = None
  660. self.ger_form = None
  661. self.exc_form = None
  662. self.geo_form = None
  663. self.cnc_form = None
  664. self.on_options_combo_change(0) # Will show the initial form
  665. ### Define OBJECT COLLECTION ###
  666. self.collection = ObjectCollection(self)
  667. self.ui.project_tab_layout.addWidget(self.collection.view)
  668. ###
  669. self.log.debug("Finished creating Object Collection.")
  670. ### Initialize the color box's color in Preferences -> Global -> Color
  671. # Init Plot Colors
  672. self.general_defaults_form.general_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  673. self.general_defaults_form.general_group.pf_color_button.setStyleSheet(
  674. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  675. self.general_defaults_form.general_group.pf_color_alpha_spinner.set_value(
  676. int(self.defaults['global_plot_fill'][7:9], 16))
  677. self.general_defaults_form.general_group.pf_color_alpha_slider.setValue(
  678. int(self.defaults['global_plot_fill'][7:9], 16))
  679. self.general_defaults_form.general_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  680. self.general_defaults_form.general_group.pl_color_button.setStyleSheet(
  681. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  682. # Init Left-Right Selection colors
  683. self.general_defaults_form.general_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  684. self.general_defaults_form.general_group.sf_color_button.setStyleSheet(
  685. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  686. self.general_defaults_form.general_group.sf_color_alpha_spinner.set_value(
  687. int(self.defaults['global_sel_fill'][7:9], 16))
  688. self.general_defaults_form.general_group.sf_color_alpha_slider.setValue(
  689. int(self.defaults['global_sel_fill'][7:9], 16))
  690. self.general_defaults_form.general_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  691. self.general_defaults_form.general_group.sl_color_button.setStyleSheet(
  692. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  693. # Init Right-Left Selection colors
  694. self.general_defaults_form.general_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  695. self.general_defaults_form.general_group.alt_sf_color_button.setStyleSheet(
  696. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  697. self.general_defaults_form.general_group.alt_sf_color_alpha_spinner.set_value(
  698. int(self.defaults['global_sel_fill'][7:9], 16))
  699. self.general_defaults_form.general_group.alt_sf_color_alpha_slider.setValue(
  700. int(self.defaults['global_sel_fill'][7:9], 16))
  701. self.general_defaults_form.general_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  702. self.general_defaults_form.general_group.alt_sl_color_button.setStyleSheet(
  703. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  704. # Init Draw color and Selection Draw Color
  705. self.general_defaults_form.general_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  706. self.general_defaults_form.general_group.draw_color_button.setStyleSheet(
  707. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  708. self.general_defaults_form.general_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  709. self.general_defaults_form.general_group.sel_draw_color_button.setStyleSheet(
  710. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  711. #### End of Data ####
  712. #### Plot Area ####
  713. start_plot_time = time.time() # debug
  714. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  715. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  716. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  717. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  718. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  719. # Keys over plot enabled
  720. self.plotcanvas.vis_connect('key_press', self.on_key_over_plot)
  721. self.plotcanvas.vis_connect('key_release', self.on_key_release_over_plot)
  722. self.ui.splitter.setStretchFactor(1, 2)
  723. # So it can receive key presses
  724. self.plotcanvas.vispy_canvas.native.setFocus()
  725. self.app_cursor = self.plotcanvas.new_cursor()
  726. self.app_cursor.enabled = False
  727. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  728. # depending on from where those tools are called different actions can be done
  729. self.call_source = 'app'
  730. end_plot_time = time.time()
  731. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  732. ### EDITOR section
  733. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  734. self.exc_editor = FlatCAMExcEditor(self)
  735. # start with GRID activated
  736. self.ui.grid_snap_btn.trigger()
  737. self.ui.corner_snap_btn.setEnabled(False)
  738. self.ui.snap_max_dist_entry.setEnabled(False)
  739. self.ui.g_editor_cmenu.setEnabled(False)
  740. self.ui.e_editor_cmenu.setEnabled(False)
  741. #### Adjust tabs width ####
  742. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  743. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  744. self.collection.view.setMinimumWidth(290)
  745. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  746. #### Worker ####
  747. self.workers = WorkerStack()
  748. self.worker_task.connect(self.workers.add_task)
  749. ### Signal handling ###
  750. ## Custom signals
  751. self.inform.connect(self.info)
  752. self.message.connect(self.message_dialog)
  753. self.progress.connect(self.set_progress_bar)
  754. self.object_created.connect(self.on_object_created)
  755. self.object_changed.connect(self.on_object_changed)
  756. self.object_plotted.connect(self.on_object_plotted)
  757. self.plots_updated.connect(self.on_plots_updated)
  758. self.file_opened.connect(self.register_recent)
  759. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  760. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  761. ## Standard signals
  762. # Menu
  763. self.ui.menufilenew.triggered.connect(self.on_file_new)
  764. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  765. self.ui.menufileopengerber_follow.triggered.connect(self.on_fileopengerber_follow)
  766. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  767. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  768. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  769. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  770. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  771. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  772. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  773. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  774. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  775. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  776. self.ui.menufileexportexcellon.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=None))
  777. self.ui.menufileexportexcellon_altium.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=True))
  778. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  779. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  780. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  781. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  782. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  783. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  784. self.ui.menueditnew.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  785. self.ui.menueditnewexc.triggered.connect(self.new_excellon_object)
  786. self.ui.menueditedit.triggered.connect(self.object2editor)
  787. self.ui.menueditok.triggered.connect(self.editor2object)
  788. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  789. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  790. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  791. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  792. self.ui.menueditdelete.triggered.connect(self.on_delete)
  793. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  794. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  795. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  796. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  797. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  798. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  799. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  800. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  801. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  802. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  803. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  804. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  805. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  806. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  807. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  808. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  809. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  810. self.ui.menuviewdisableall.triggered.connect(lambda: self.disable_plots(self.collection.get_list()))
  811. self.ui.menuviewdisableother.triggered.connect(lambda: self.disable_plots(self.collection.get_non_selected()))
  812. self.ui.menuviewenable.triggered.connect(lambda: self.enable_plots(self.collection.get_list()))
  813. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  814. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  815. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  816. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  817. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  818. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  819. self.ui.menuhelp_about.triggered.connect(self.on_about)
  820. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  821. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  822. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  823. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  824. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  825. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  826. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  827. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  828. # Toolbar
  829. #self.ui.file_new_btn.triggered.connect(self.on_file_new)
  830. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  831. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  832. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  833. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  834. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  835. self.ui.replot_btn.triggered.connect(self.plot_all)
  836. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  837. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  838. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  839. self.ui.newgeo_btn.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  840. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  841. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  842. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  843. self.ui.delete_btn.triggered.connect(self.on_delete)
  844. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  845. # Context Menu
  846. self.ui.gridmenu_1.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.05"))
  847. self.ui.gridmenu_2.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.1"))
  848. self.ui.gridmenu_3.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.2"))
  849. self.ui.gridmenu_4.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.5"))
  850. self.ui.gridmenu_5.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("1.0"))
  851. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  852. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  853. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  854. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  855. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  856. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  857. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  858. self.ui.clearplot.triggered.connect(self.clear_plots)
  859. self.ui.replot.triggered.connect(self.plot_all)
  860. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  861. # Preferences Plot Area TAB
  862. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  863. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  864. self.ui.pref_factory_button.clicked.connect(self.load_factory_defaults)
  865. self.ui.pref_load_button.clicked.connect(self.load_user_defaults)
  866. self.general_options_form.general_group.units_radio.group_toggle_fn = self.on_toggle_units
  867. # Setting plot colors signals
  868. self.general_defaults_form.general_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  869. self.general_defaults_form.general_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  870. self.general_defaults_form.general_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  871. self.general_defaults_form.general_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  872. self.general_defaults_form.general_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  873. self.general_defaults_form.general_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  874. # Setting selection (left - right) colors signals
  875. self.general_defaults_form.general_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  876. self.general_defaults_form.general_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  877. self.general_defaults_form.general_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  878. self.general_defaults_form.general_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  879. self.general_defaults_form.general_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  880. self.general_defaults_form.general_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  881. # Setting selection (right - left) colors signals
  882. self.general_defaults_form.general_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  883. self.general_defaults_form.general_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  884. self.general_defaults_form.general_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  885. self.on_alt_sf_color_spinner)
  886. self.general_defaults_form.general_group.alt_sf_color_alpha_slider.valueChanged.connect(
  887. self.on_alt_sf_color_slider)
  888. self.general_defaults_form.general_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  889. self.general_defaults_form.general_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  890. # Setting Editor Draw colors signals
  891. self.general_defaults_form.general_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  892. self.general_defaults_form.general_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  893. self.general_defaults_form.general_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  894. self.general_defaults_form.general_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  895. self.general_defaults_form.general_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  896. self.general_defaults_form.general_group.workspace_cb.stateChanged.connect(self.on_workspace)
  897. # Modify G-CODE Plot Area TAB
  898. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  899. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  900. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  901. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  902. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  903. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  904. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  905. # Object list
  906. self.collection.view.activated.connect(self.on_row_activated)
  907. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  908. self.general_defaults_form.general_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  909. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  910. self.excellon_defaults_form.excellon_group.excellon_defaults_button.clicked.connect(
  911. self.on_excellon_defaults_button)
  912. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  913. self.excellon_options_form.excellon_group.excellon_defaults_button.clicked.connect(
  914. self.on_excellon_options_button)
  915. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  916. self.tool_tab_locked = False
  917. ####################
  918. ### Other setups ###
  919. ####################
  920. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  921. self.setup_obj_classes()
  922. self.setup_recent_items()
  923. self.setup_component_editor()
  924. #############
  925. ### Shell ###
  926. #############
  927. ###
  928. # Auto-complete KEYWORDS
  929. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  930. 'aligndrill', 'clear',
  931. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob', 'export_gcode',
  932. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  933. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  934. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  935. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  936. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  937. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  938. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  939. ]
  940. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  941. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  942. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  943. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  944. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  945. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  946. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  947. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  948. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  949. ]
  950. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  951. self.shell = FCShell(self, version=self.version)
  952. self.shell._edit.set_model_data(self.myKeywords)
  953. self.shell.setWindowIcon(self.ui.app_icon)
  954. self.shell.setWindowTitle("FlatCAM Shell")
  955. self.shell.resize(*self.defaults["global_shell_shape"])
  956. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  957. self.shell.append_output("(Type help to get started)\n\n")
  958. self.init_tcl()
  959. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  960. self.ui.shell_dock.setWidget(self.shell)
  961. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  962. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  963. QtWidgets.QDockWidget.DockWidgetFloatable |
  964. QtWidgets.QDockWidget.DockWidgetClosable)
  965. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  966. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  967. if self.defaults["global_shell_at_startup"]:
  968. self.ui.shell_dock.show()
  969. else:
  970. self.ui.shell_dock.hide()
  971. #########################
  972. ### Tools and Plugins ###
  973. #########################
  974. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  975. self.install_tools()
  976. ### System Font Parsing ###
  977. self.f_parse = ParseFont()
  978. self.parse_system_fonts()
  979. # test if the program was started with a script as parameter
  980. if self.cmd_line_shellfile:
  981. try:
  982. with open(self.cmd_line_shellfile, "r") as myfile:
  983. cmd_line_shellfile_text = myfile.read()
  984. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  985. except Exception as ext:
  986. print("ERROR: ", ext)
  987. sys.exit(2)
  988. ###########################
  989. #### Check for updates ####
  990. ###########################
  991. # Separate thread (Not worker)
  992. if self.beta is False or self.beta is None:
  993. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  994. self.thr2 = QtCore.QThread()
  995. self.worker_task.emit({'fcn': self.version_check,
  996. 'params': []})
  997. self.thr2.start()
  998. ####################################
  999. #### Variables for global usage ####
  1000. ####################################
  1001. # coordinates for relative position display
  1002. self.rel_point1 = (0, 0)
  1003. self.rel_point2 = (0, 0)
  1004. # variable to store coordinates
  1005. self.pos = (0, 0)
  1006. self.pos_jump = (0, 0)
  1007. # variable to store if there was motion before right mouse button click (panning)
  1008. self.panning_action = False
  1009. # variable to store if a command is active (then the var is not None) and which one it is
  1010. self.command_active = None
  1011. # variable to store the status of moving selection action
  1012. # None value means that it's not an selection action
  1013. # True value = a selection from left to right
  1014. # False value = a selection from right to left
  1015. self.selection_type = None
  1016. # List to store the objects that are currently loaded in FlatCAM
  1017. # This list is updated on each object creation or object delete
  1018. self.all_objects_list = []
  1019. # List to store the objects that are selected
  1020. self.sel_objects_list = []
  1021. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1022. self.key_modifiers = None
  1023. # Variable to hold the status of the axis
  1024. self.toggle_axis = True
  1025. self.cursor = None
  1026. # Variable to store the GCODE that was edited
  1027. self.gcode_edited = ""
  1028. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1029. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1030. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1031. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1032. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1033. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1034. 'mpf']
  1035. self.svg_list = ['svg']
  1036. self.dxf_list = ['dxf']
  1037. self.prj_list = ['flatprj']
  1038. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1039. # flag for polygons not cleared
  1040. self.poly_not_cleared = False
  1041. ### Save defaults to factory_defaults.json file ###
  1042. ### It's done only once after install #############
  1043. factory_file = open(self.data_path + '/factory_defaults.json')
  1044. fac_def_from_file = factory_file.read()
  1045. factory_defaults = json.loads(fac_def_from_file)
  1046. # if the file contain an empty dictionary then save the factory defaults into the file
  1047. if not factory_defaults:
  1048. self.save_factory_defaults(silent=False)
  1049. factory_file.close()
  1050. # Post-GUI initialization: Experimental attempt
  1051. # to perform unit tests on the GUI.
  1052. # if post_gui is not None:
  1053. # post_gui(self)
  1054. App.log.debug("END of constructor. Releasing control.")
  1055. # accept a project file as command line parameter
  1056. # the path/file_name must be enclosed in quotes if it contain spaces
  1057. for argument in App.args:
  1058. if '.FlatPrj' in argument:
  1059. try:
  1060. project_name = str(argument)
  1061. if project_name == "":
  1062. self.inform.emit("Open cancelled.")
  1063. else:
  1064. # self.open_project(project_name)
  1065. run_from_arg = True
  1066. self.worker_task.emit({'fcn': self.open_project,
  1067. 'params': [project_name, run_from_arg]})
  1068. except Exception as e:
  1069. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1070. def defaults_read_form(self):
  1071. for option in self.defaults_form_fields:
  1072. try:
  1073. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1074. except:
  1075. pass
  1076. def defaults_write_form(self):
  1077. for option in self.defaults:
  1078. self.defaults_write_form_field(option)
  1079. # try:
  1080. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1081. # except KeyError:
  1082. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1083. # # TODO: Rethink this?
  1084. # pass
  1085. def defaults_write_form_field(self, field):
  1086. try:
  1087. self.defaults_form_fields[field].set_value(self.defaults[field])
  1088. except KeyError:
  1089. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1090. # TODO: Rethink this?
  1091. pass
  1092. def clear_pool(self):
  1093. self.pool.close()
  1094. self.pool = Pool()
  1095. self.pool_recreated.emit(self.pool)
  1096. gc.collect()
  1097. # the order that the tools are installed is important as they can depend on each other install position
  1098. def install_tools(self):
  1099. self.dblsidedtool = DblSidedTool(self)
  1100. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1101. self.measurement_tool = Measurement(self)
  1102. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1103. self.panelize_tool = Panelize(self)
  1104. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1105. self.film_tool = Film(self)
  1106. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'), separator=True)
  1107. self.move_tool = ToolMove(self)
  1108. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1109. before=self.ui.menueditorigin)
  1110. self.cutout_tool = ToolCutout(self)
  1111. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16.png'), pos=self.ui.menutool,
  1112. before=self.measurement_tool.menuAction)
  1113. self.ncclear_tool = NonCopperClear(self)
  1114. self.ncclear_tool.install(icon=QtGui.QIcon('share/flatcam_icon16.png'), pos=self.ui.menutool,
  1115. before=self.measurement_tool.menuAction, separator=True)
  1116. self.paint_tool = ToolPaint(self)
  1117. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1118. before=self.measurement_tool.menuAction, separator=True)
  1119. self.calculator_tool = ToolCalculator(self)
  1120. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1121. self.transform_tool = ToolTransform(self)
  1122. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1123. self.properties_tool = Properties(self)
  1124. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1125. self.image_tool = ToolImage(self)
  1126. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1127. separator=True)
  1128. self.log.debug("Tools are installed.")
  1129. def init_tools(self):
  1130. # delete the data currently in the Tools Tab and the Tab itself
  1131. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1132. if widget is not None:
  1133. widget.deleteLater()
  1134. self.ui.notebook.removeTab(2)
  1135. # rebuild the Tools Tab
  1136. self.ui.tool_tab = QtWidgets.QWidget()
  1137. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1138. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1139. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1140. self.ui.tool_scroll_area = VerticalScrollArea()
  1141. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1142. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1143. self.install_tools()
  1144. self.log.debug("Tools are initialized.")
  1145. def parse_system_fonts(self):
  1146. self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1147. 'params': []})
  1148. def object2editor(self):
  1149. """
  1150. Send the current Geometry or Excellon object (if any) into the editor.
  1151. :return: None
  1152. """
  1153. if isinstance(self.collection.get_active(), FlatCAMGeometry):
  1154. edited_object = self.collection.get_active()
  1155. # for now, if the Geometry is MultiGeo do not allow the editing
  1156. if edited_object.multigeo is True:
  1157. self.inform.emit("[warning_notcl]Editing a MultiGeo Geometry is not possible for the moment.")
  1158. return
  1159. self.ui.update_obj_btn.setEnabled(True)
  1160. self.geo_editor.edit_fcgeometry(edited_object)
  1161. self.ui.g_editor_cmenu.setEnabled(True)
  1162. # set call source to the Editor we go into
  1163. self.call_source = 'geo_editor'
  1164. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  1165. sel_tab_widget_list = self.ui.selected_tab.findChildren(QtWidgets.QWidget)
  1166. for w in sel_tab_widget_list:
  1167. w.setEnabled(False)
  1168. elif isinstance(self.collection.get_active(), FlatCAMExcellon):
  1169. self.ui.update_obj_btn.setEnabled(True)
  1170. self.exc_editor.edit_exc_obj(self.collection.get_active())
  1171. self.ui.e_editor_cmenu.setEnabled(True)
  1172. # set call source to the Editor we go into
  1173. self.call_source = 'exc_editor'
  1174. else:
  1175. self.inform.emit("[warning_notcl]Select a Geometry or Excellon Object to edit.")
  1176. return
  1177. # make sure that we can't select another object while in Editor Mode:
  1178. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1179. # delete any selection shape that might be active as they are not relevant in Editor
  1180. self.delete_selection_shape()
  1181. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1182. self.inform.emit("[warning_notcl]Editor is activated ...")
  1183. def editor2object(self):
  1184. """
  1185. Transfers the Geometry or Excellon from the editor to the current object.
  1186. :return: None
  1187. """
  1188. edited_obj = self.collection.get_active()
  1189. obj_type = ""
  1190. if isinstance(edited_obj, FlatCAMGeometry):
  1191. obj_type = "Geometry"
  1192. self.geo_editor.update_fcgeometry(edited_obj)
  1193. self.geo_editor.update_options(edited_obj)
  1194. self.geo_editor.deactivate()
  1195. # edited_obj.on_tool_delete(all=True)
  1196. # edited_obj.on_tool_add(dia=edited_obj.options['cnctooldia'])
  1197. self.ui.corner_snap_btn.setEnabled(False)
  1198. self.ui.update_obj_btn.setEnabled(False)
  1199. self.ui.g_editor_cmenu.setEnabled(False)
  1200. self.ui.e_editor_cmenu.setEnabled(False)
  1201. # update the geo object options so it is including the bounding box values
  1202. try:
  1203. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1204. edited_obj.options['xmin'] = xmin
  1205. edited_obj.options['ymin'] = ymin
  1206. edited_obj.options['xmax'] = xmax
  1207. edited_obj.options['ymax'] = ymax
  1208. except AttributeError:
  1209. self.inform.emit("[warning] Object empty after edit.")
  1210. elif isinstance(edited_obj, FlatCAMExcellon):
  1211. obj_type = "Excellon"
  1212. self.exc_editor.update_exc_obj(edited_obj)
  1213. self.exc_editor.deactivate()
  1214. self.ui.corner_snap_btn.setEnabled(False)
  1215. self.ui.update_obj_btn.setEnabled(False)
  1216. self.ui.g_editor_cmenu.setEnabled(False)
  1217. self.ui.e_editor_cmenu.setEnabled(False)
  1218. else:
  1219. self.inform.emit("[warning_notcl]Select a Geometry or Excellon Object to update.")
  1220. return
  1221. # restore the call_source to app
  1222. self.call_source = 'app'
  1223. edited_obj.plot()
  1224. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1225. self.inform.emit("[success] %s is updated, returning to App..." % obj_type)
  1226. # reset the Object UI to original settings
  1227. # edited_obj.set_ui(edited_obj.ui_type())
  1228. # edited_obj.build_ui()
  1229. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1230. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1231. def get_last_folder(self):
  1232. return self.defaults["global_last_folder"]
  1233. def get_last_save_folder(self):
  1234. return self.defaults["global_last_save_folder"]
  1235. def report_usage(self, resource):
  1236. """
  1237. Increments usage counter for the given resource
  1238. in self.defaults['global_stats'].
  1239. :param resource: Name of the resource.
  1240. :return: None
  1241. """
  1242. if resource in self.defaults['global_stats']:
  1243. self.defaults['global_stats'][resource] += 1
  1244. else:
  1245. self.defaults['global_stats'][resource] = 1
  1246. def init_tcl(self):
  1247. if hasattr(self,'tcl'):
  1248. # self.tcl = None
  1249. # TODO we need to clean non default variables and procedures here
  1250. # new object cannot be used here as it will not remember values created for next passes,
  1251. # because tcl was execudted in old instance of TCL
  1252. pass
  1253. else:
  1254. self.tcl = tk.Tcl()
  1255. self.setup_shell()
  1256. self.log.debug("TCL Shell has been initialized.")
  1257. # TODO: This shouldn't be here.
  1258. class TclErrorException(Exception):
  1259. """
  1260. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1261. """
  1262. pass
  1263. def shell_message(self, msg, show=False, error=False):
  1264. """
  1265. Shows a message on the FlatCAM Shell
  1266. :param msg: Message to display.
  1267. :param show: Opens the shell.
  1268. :param error: Shows the message as an error.
  1269. :return: None
  1270. """
  1271. if show:
  1272. self.ui.shell_dock.show()
  1273. try:
  1274. if error:
  1275. self.shell.append_error(msg + "\n")
  1276. else:
  1277. self.shell.append_output(msg + "\n")
  1278. except AttributeError:
  1279. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1280. def raise_tcl_unknown_error(self, unknownException):
  1281. """
  1282. Raise exception if is different type than TclErrorException
  1283. this is here mainly to show unknown errors inside TCL shell console.
  1284. :param unknownException:
  1285. :return:
  1286. """
  1287. if not isinstance(unknownException, self.TclErrorException):
  1288. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1289. else:
  1290. raise unknownException
  1291. def display_tcl_error(self, error, error_info=None):
  1292. """
  1293. escape bracket [ with \ otherwise there is error
  1294. "ERROR: missing close-bracket" instead of real error
  1295. :param error: it may be text or exception
  1296. :return: None
  1297. """
  1298. if isinstance(error, Exception):
  1299. exc_type, exc_value, exc_traceback = error_info
  1300. if not isinstance(error, self.TclErrorException):
  1301. show_trace = 1
  1302. else:
  1303. show_trace = int(self.defaults['global_verbose_error_level'])
  1304. if show_trace > 0:
  1305. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1306. trc_formated = []
  1307. for a in reversed(trc):
  1308. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1309. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1310. exc_type,
  1311. "\n".join(trc_formated))
  1312. else:
  1313. text = "%s" % error
  1314. else:
  1315. text = error
  1316. text = text.replace('[', '\\[').replace('"', '\\"')
  1317. self.tcl.eval('return -code error "%s"' % text)
  1318. def raise_tcl_error(self, text):
  1319. """
  1320. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1321. :param text: text of error
  1322. :return: raise exception
  1323. """
  1324. self.display_tcl_error(text)
  1325. raise self.TclErrorException(text)
  1326. def exec_command(self, text):
  1327. """
  1328. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1329. Also handles execution in separated threads
  1330. :param text:
  1331. :return: output if there was any
  1332. """
  1333. self.report_usage('exec_command')
  1334. result = self.exec_command_test(text, False)
  1335. #MS: added this method call so the geometry is updated once the TCL
  1336. #command is executed
  1337. self.plot_all()
  1338. return result
  1339. def exec_command_test(self, text, reraise=True):
  1340. """
  1341. Same as exec_command(...) with additional control over exceptions.
  1342. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1343. :param text: Input command
  1344. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1345. :return: Output from the command
  1346. """
  1347. text = str(text)
  1348. try:
  1349. self.shell.open_proccessing() # Disables input box.
  1350. result = self.tcl.eval(str(text))
  1351. if result != 'None':
  1352. self.shell.append_output(result + '\n')
  1353. except tk.TclError as e:
  1354. # This will display more precise answer if something in TCL shell fails
  1355. result = self.tcl.eval("set errorInfo")
  1356. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1357. self.shell.append_error('ERROR: ' + result + '\n')
  1358. # Show error in console and just return or in test raise exception
  1359. if reraise:
  1360. raise e
  1361. finally:
  1362. self.shell.close_proccessing()
  1363. pass
  1364. return result
  1365. # """
  1366. # Code below is unsused. Saved for later.
  1367. # """
  1368. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1369. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1370. # self.log.debug(parts)
  1371. # try:
  1372. # if parts[0] not in commands:
  1373. # self.shell.append_error("Unknown command\n")
  1374. # return
  1375. #
  1376. # #import inspect
  1377. # #inspect.getargspec(someMethod)
  1378. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1379. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1380. # self.shell.append_error(
  1381. # "Command %s takes %d arguments. %d given.\n" %
  1382. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1383. # )
  1384. # return
  1385. #
  1386. # cmdfcn = commands[parts[0]]["fcn"]
  1387. # cmdconv = commands[parts[0]]["converters"]
  1388. # if len(parts) - 1 > 0:
  1389. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1390. # else:
  1391. # retval = cmdfcn()
  1392. # retfcn = commands[parts[0]]["retfcn"]
  1393. # if retval and retfcn(retval):
  1394. # self.shell.append_output(retfcn(retval) + "\n")
  1395. #
  1396. # except Exception as e:
  1397. # #self.shell.append_error(''.join(traceback.format_exc()))
  1398. # #self.shell.append_error("?\n")
  1399. # self.shell.append_error(str(e) + "\n")
  1400. def info(self, msg):
  1401. """
  1402. Informs the user. Normally on the status bar, optionally
  1403. also on the shell.
  1404. :param msg: Text to write.
  1405. :return: None
  1406. """
  1407. # Type of message in brackets at the begining of the message.
  1408. match = re.search("\[([^\]]+)\](.*)", msg)
  1409. if match:
  1410. level = match.group(1)
  1411. msg_ = match.group(2)
  1412. self.ui.fcinfo.set_status(str(msg_), level=level)
  1413. if level == "error" or level == "warning":
  1414. self.shell_message(msg, error=True, show=True)
  1415. elif level == "error_notcl" or level == "warning_notcl":
  1416. self.shell_message(msg, error=True, show=False)
  1417. else:
  1418. self.shell_message(msg, error=False, show=False)
  1419. else:
  1420. self.ui.fcinfo.set_status(str(msg), level="info")
  1421. # make sure that if the message is to clear the infobar with a space
  1422. # is not printed over and over on the shell
  1423. if msg != '':
  1424. self.shell_message(msg)
  1425. def load_defaults(self):
  1426. """
  1427. Loads the aplication's default settings from defaults.json into
  1428. ``self.defaults``.
  1429. :return: None
  1430. """
  1431. try:
  1432. f = open(self.data_path + "/defaults.json")
  1433. options = f.read()
  1434. f.close()
  1435. except IOError:
  1436. self.log.error("Could not load defaults file.")
  1437. self.inform.emit("[error] Could not load defaults file.")
  1438. # in case the defaults file can't be loaded, show all toolbars
  1439. self.defaults["global_toolbar_view"] = 31
  1440. return
  1441. try:
  1442. defaults = json.loads(options)
  1443. except:
  1444. # in case the defaults file can't be loaded, show all toolbars
  1445. self.defaults["global_toolbar_view"] = 31
  1446. e = sys.exc_info()[0]
  1447. App.log.error(str(e))
  1448. self.inform.emit("[error] Failed to parse defaults file.")
  1449. return
  1450. self.defaults.update(defaults)
  1451. # restore the toolbar view
  1452. tb = self.defaults["global_toolbar_view"]
  1453. if tb & 1:
  1454. self.ui.toolbarfile.setVisible(True)
  1455. else:
  1456. self.ui.toolbarfile.setVisible(False)
  1457. if tb & 2:
  1458. self.ui.toolbargeo.setVisible(True)
  1459. else:
  1460. self.ui.toolbargeo.setVisible(False)
  1461. if tb & 4:
  1462. self.ui.toolbarview.setVisible(True)
  1463. else:
  1464. self.ui.toolbarview.setVisible(False)
  1465. if tb & 8:
  1466. self.ui.toolbartools.setVisible(True)
  1467. else:
  1468. self.ui.toolbartools.setVisible(False)
  1469. if tb & 16:
  1470. self.ui.snap_toolbar.setVisible(True)
  1471. else:
  1472. self.ui.snap_toolbar.setVisible(False)
  1473. def load_factory_defaults(self):
  1474. """
  1475. Loads the aplication's factory default settings from factory_defaults.json into
  1476. ``self.defaults``.
  1477. :return: None
  1478. """
  1479. try:
  1480. f = open(self.data_path + "/factory_defaults.json")
  1481. options = f.read()
  1482. f.close()
  1483. except IOError:
  1484. self.log.error("Could not load factory defaults file.")
  1485. self.inform.emit("[error] Could not load factory defaults file.")
  1486. return
  1487. try:
  1488. factory_defaults = json.loads(options)
  1489. except:
  1490. e = sys.exc_info()[0]
  1491. App.log.error(str(e))
  1492. self.inform.emit("[error] Failed to parse factory defaults file.")
  1493. return
  1494. self.defaults.update(factory_defaults)
  1495. self.inform.emit("[success] Imported Factory Defaults ...")
  1496. def load_user_defaults(self):
  1497. self.load_defaults()
  1498. self.inform.emit("[success] Loaded User Defaults ...")
  1499. def save_geometry(self, x, y, width, height, notebook_width):
  1500. self.defaults["global_def_win_x"] = x
  1501. self.defaults["global_def_win_y"] = y
  1502. self.defaults["global_def_win_w"] = width
  1503. self.defaults["global_def_win_h"] = height
  1504. self.defaults["def_notebook_width"] = notebook_width
  1505. self.save_defaults()
  1506. def message_dialog(self, title, message, kind="info"):
  1507. icon = {"info": QtWidgets.QMessageBox.Information,
  1508. "warning": QtWidgets.QMessageBox.Warning,
  1509. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1510. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1511. dlg.setText(message)
  1512. dlg.exec_()
  1513. def register_recent(self, kind, filename):
  1514. self.log.debug("register_recent()")
  1515. self.log.debug(" %s" % kind)
  1516. self.log.debug(" %s" % filename)
  1517. record = {'kind': str(kind), 'filename': str(filename)}
  1518. if record in self.recent:
  1519. return
  1520. self.recent.insert(0, record)
  1521. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  1522. self.recent.pop()
  1523. try:
  1524. f = open(self.data_path + '/recent.json', 'w')
  1525. except IOError:
  1526. App.log.error("Failed to open recent items file for writing.")
  1527. self.inform.emit('[error_notcl]Failed to open recent files file for writing.')
  1528. return
  1529. #try:
  1530. json.dump(self.recent, f)
  1531. # except:
  1532. # App.log.error("Failed to write to recent items file.")
  1533. # self.inform.emit('ERROR: Failed to write to recent items file.')
  1534. # f.close()
  1535. f.close()
  1536. # Re-buid the recent items menu
  1537. self.setup_recent_items()
  1538. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  1539. """
  1540. Creates a new specalized FlatCAMObj and attaches it to the application,
  1541. this is, updates the GUI accordingly, any other records and plots it.
  1542. This method is thread-safe.
  1543. Notes:
  1544. * If the name is in use, the self.collection will modify it
  1545. when appending it to the collection. There is no need to handle
  1546. name conflicts here.
  1547. :param kind: The kind of object to create. One of 'gerber',
  1548. 'excellon', 'cncjob' and 'geometry'.
  1549. :type kind: str
  1550. :param name: Name for the object.
  1551. :type name: str
  1552. :param initialize: Function to run after creation of the object
  1553. but before it is attached to the application. The function is
  1554. called with 2 parameters: the new object and the App instance.
  1555. :type initialize: function
  1556. :return: None
  1557. :rtype: None
  1558. """
  1559. App.log.debug("new_object()")
  1560. self.plot = plot
  1561. self.autoselected = autoselected
  1562. t0 = time.time() # Debug
  1563. ## Create object
  1564. classdict = {
  1565. "gerber": FlatCAMGerber,
  1566. "excellon": FlatCAMExcellon,
  1567. "cncjob": FlatCAMCNCjob,
  1568. "geometry": FlatCAMGeometry
  1569. }
  1570. App.log.debug("Calling object constructor...")
  1571. obj = classdict[kind](name)
  1572. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  1573. # Set options from "Project options" form
  1574. self.options_read_form()
  1575. # IMPORTANT
  1576. # The key names in defaults and options dictionary's are not random:
  1577. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  1578. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  1579. # the options from project options form into the self.options. After that, below, depending on the type of
  1580. # object that is created, it will strip the name of the object and the underline (if the original key was
  1581. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  1582. # "toolchange"
  1583. for option in self.options:
  1584. if option.find(kind + "_") == 0:
  1585. oname = option[len(kind) + 1:]
  1586. obj.options[oname] = self.options[option]
  1587. # if kind == 'geometry':
  1588. # obj.tools = {}
  1589. # elif kind == 'cncjob':
  1590. # obj.cnc_tools = {}
  1591. # Initialize as per user request
  1592. # User must take care to implement initialize
  1593. # in a thread-safe way as is is likely that we
  1594. # have been invoked in a separate thread.
  1595. t1 = time.time()
  1596. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  1597. try:
  1598. return_value = initialize(obj, self)
  1599. except Exception as e:
  1600. if str(e) == "Empty Geometry":
  1601. self.inform.emit("[error_notcl] Object (%s) failed because: %s" % (kind, str(e)))
  1602. else:
  1603. self.inform.emit("[error] Object (%s) failed because: %s" % (kind, str(e)))
  1604. return "fail"
  1605. t2 = time.time()
  1606. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  1607. if return_value == 'fail':
  1608. return "fail"
  1609. # Check units and convert if necessary
  1610. # This condition CAN be true because initialize() can change obj.units
  1611. if self.options["units"].upper() != obj.units.upper():
  1612. self.inform.emit("Converting units to " + self.options["units"] + ".")
  1613. obj.convert_units(self.options["units"])
  1614. t3 = time.time()
  1615. self.log.debug("%f seconds converting units." % (t3 - t2))
  1616. # Create the bounding box for the object and then add the results to the obj.options
  1617. try:
  1618. xmin, ymin, xmax, ymax = obj.bounds()
  1619. obj.options['xmin'] = xmin
  1620. obj.options['ymin'] = ymin
  1621. obj.options['xmax'] = xmax
  1622. obj.options['ymax'] = ymax
  1623. except:
  1624. log.warning("The object has no bounds properties.")
  1625. pass
  1626. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  1627. # Move the object to the main thread and let the app know that it is available.
  1628. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  1629. self.object_created.emit(obj, self.plot, self.autoselected)
  1630. return obj
  1631. def new_excellon_object(self):
  1632. self.new_object('excellon', 'new_e', lambda x, y: None)
  1633. def on_object_created(self, obj, plot, autoselect):
  1634. """
  1635. Event callback for object creation.
  1636. :param obj: The newly created FlatCAM object.
  1637. :return: None
  1638. """
  1639. t0 = time.time() # DEBUG
  1640. self.log.debug("on_object_created()")
  1641. # The Collection might change the name if there is a collision
  1642. self.collection.append(obj)
  1643. # after adding the object to the collection always update the list of objects that are in the collection
  1644. self.all_objects_list = self.collection.get_list()
  1645. self.inform.emit("[success]Object (%s) created: %s" % (obj.kind, obj.options['name']))
  1646. self.new_object_available.emit(obj)
  1647. # update the SHELL auto-completer model with the name of the new object
  1648. self.myKeywords.append(obj.options['name'])
  1649. self.shell._edit.set_model_data(self.myKeywords)
  1650. if autoselect:
  1651. # select the just opened object but deselect the previous ones
  1652. self.collection.set_all_inactive()
  1653. self.collection.set_active(obj.options["name"])
  1654. def worker_task(obj):
  1655. with self.proc_container.new("Plotting"):
  1656. obj.plot()
  1657. t1 = time.time() # DEBUG
  1658. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  1659. self.object_plotted.emit(obj)
  1660. # Send to worker
  1661. # self.worker.add_task(worker_task, [self])
  1662. if plot:
  1663. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  1664. def on_object_changed(self, obj):
  1665. # update the bounding box data from obj.options
  1666. xmin, ymin, xmax, ymax = obj.bounds()
  1667. obj.options['xmin'] = xmin
  1668. obj.options['ymin'] = ymin
  1669. obj.options['xmax'] = xmax
  1670. obj.options['ymax'] = ymax
  1671. log.debug("Object changed, updating the bounding box data on self.options")
  1672. # delete the old selection shape
  1673. self.delete_selection_shape()
  1674. def on_object_plotted(self, obj):
  1675. self.on_zoom_fit(None)
  1676. def options_read_form(self):
  1677. for option in self.options_form_fields:
  1678. self.options[option] = self.options_form_fields[option].get_value()
  1679. def options_write_form(self):
  1680. for option in self.options:
  1681. self.options_write_form_field(option)
  1682. def options_write_form_field(self, field):
  1683. try:
  1684. self.options_form_fields[field].set_value(self.options[field])
  1685. except KeyError:
  1686. # Changed from error to debug. This allows to have data stored
  1687. # which is not user-editable.
  1688. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  1689. pass
  1690. def on_about(self):
  1691. """
  1692. Displays the "about" dialog.
  1693. :return: None
  1694. """
  1695. self.report_usage("on_about")
  1696. version = self.version
  1697. version_date = self.version_date
  1698. beta = self.beta
  1699. class AboutDialog(QtWidgets.QDialog):
  1700. def __init__(self, parent=None):
  1701. QtWidgets.QDialog.__init__(self, parent)
  1702. # Icon and title
  1703. self.setWindowIcon(parent.app_icon)
  1704. self.setWindowTitle("FlatCAM")
  1705. layout1 = QtWidgets.QVBoxLayout()
  1706. self.setLayout(layout1)
  1707. layout2 = QtWidgets.QHBoxLayout()
  1708. layout1.addLayout(layout2)
  1709. logo = QtWidgets.QLabel()
  1710. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  1711. layout2.addWidget(logo, stretch=0)
  1712. title = QtWidgets.QLabel(
  1713. "<font size=8><B>FlatCAM</B></font><BR>"
  1714. "Version %s %s (%s) - %s <BR>"
  1715. "<BR>"
  1716. "2D Computer-Aided Printed Circuit Board<BR>"
  1717. "Manufacturing.<BR>"
  1718. "<BR>"
  1719. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  1720. "<BR>"
  1721. "<B> Main Contributors:</B><BR>"
  1722. "Denis Hayrullin<BR>"
  1723. "Kamil Sopko<BR>"
  1724. "Marius Stanciu<BR>"
  1725. "Matthieu Berthomé<BR>"
  1726. "and many others found "
  1727. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  1728. "<BR>"
  1729. "Development is done "
  1730. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  1731. "DOWNLOAD area "
  1732. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  1733. "" % (version, ('BETA' if beta else ''), version_date, platform.architecture()[0])
  1734. )
  1735. title.setOpenExternalLinks(True)
  1736. layout2.addWidget(title, stretch=1)
  1737. layout3 = QtWidgets.QHBoxLayout()
  1738. layout1.addLayout(layout3)
  1739. layout3.addStretch()
  1740. okbtn = QtWidgets.QPushButton("Close")
  1741. layout3.addWidget(okbtn)
  1742. okbtn.clicked.connect(self.accept)
  1743. AboutDialog(self.ui).exec_()
  1744. def on_file_savedefaults(self):
  1745. """
  1746. Callback for menu item File->Save Defaults. Saves application default options
  1747. ``self.defaults`` to defaults.json.
  1748. :return: None
  1749. """
  1750. self.save_defaults()
  1751. def on_app_exit(self):
  1752. self.save_defaults()
  1753. log.debug("Application defaults saved ... Exit event.")
  1754. QtWidgets.qApp.quit()
  1755. def save_defaults(self, silent=False):
  1756. """
  1757. Saves application default options
  1758. ``self.defaults`` to defaults.json.
  1759. :return: None
  1760. """
  1761. self.report_usage("save_defaults")
  1762. # Read options from file
  1763. try:
  1764. f = open(self.data_path + "/defaults.json")
  1765. defaults_file_content = f.read()
  1766. f.close()
  1767. except:
  1768. e = sys.exc_info()[0]
  1769. App.log.error("Could not load defaults file.")
  1770. App.log.error(str(e))
  1771. self.inform.emit("[error_notcl] Could not load defaults file.")
  1772. return
  1773. try:
  1774. defaults = json.loads(defaults_file_content)
  1775. except:
  1776. e = sys.exc_info()[0]
  1777. App.log.error("Failed to parse defaults file.")
  1778. App.log.error(str(e))
  1779. self.inform.emit("[error_notcl] Failed to parse defaults file.")
  1780. return
  1781. # Update options
  1782. self.defaults_read_form()
  1783. defaults.update(self.defaults)
  1784. self.propagate_defaults(silent=True)
  1785. # Save update options
  1786. try:
  1787. f = open(self.data_path + "/defaults.json", "w")
  1788. json.dump(defaults, f)
  1789. f.close()
  1790. except:
  1791. self.inform.emit("[error_notcl] Failed to write defaults to file.")
  1792. return
  1793. # Save the toolbar view
  1794. tb_status = 0
  1795. if self.ui.toolbarfile.isVisible():
  1796. tb_status += 1
  1797. if self.ui.toolbargeo.isVisible():
  1798. tb_status += 2
  1799. if self.ui.toolbarview.isVisible():
  1800. tb_status += 4
  1801. if self.ui.toolbartools.isVisible():
  1802. tb_status += 8
  1803. if self.ui.snap_toolbar.isVisible():
  1804. tb_status += 16
  1805. self.defaults["global_toolbar_view"] = tb_status
  1806. if not silent:
  1807. self.inform.emit("[success]Defaults saved.")
  1808. def save_factory_defaults(self, silent=False):
  1809. """
  1810. Saves application factory default options
  1811. ``self.defaults`` to factory_defaults.json.
  1812. It's a one time job done just after the first install.
  1813. :return: None
  1814. """
  1815. self.report_usage("save_factory_defaults")
  1816. # Read options from file
  1817. try:
  1818. f_f_def = open(self.data_path + "/factory_defaults.json")
  1819. factory_defaults_file_content = f_f_def.read()
  1820. f_f_def.close()
  1821. except:
  1822. e = sys.exc_info()[0]
  1823. App.log.error("Could not load factory defaults file.")
  1824. App.log.error(str(e))
  1825. self.inform.emit("[error_notcl] Could not load factory defaults file.")
  1826. return
  1827. try:
  1828. factory_defaults = json.loads(factory_defaults_file_content)
  1829. except:
  1830. e = sys.exc_info()[0]
  1831. App.log.error("Failed to parse factory defaults file.")
  1832. App.log.error(str(e))
  1833. self.inform.emit("[error_notcl] Failed to parse factory defaults file.")
  1834. return
  1835. # Update options
  1836. self.defaults_read_form()
  1837. factory_defaults.update(self.defaults)
  1838. self.propagate_defaults(silent=True)
  1839. # Save update options
  1840. try:
  1841. f_f_def_s = open(self.data_path + "/factory_defaults.json", "w")
  1842. json.dump(factory_defaults, f_f_def_s)
  1843. f_f_def_s.close()
  1844. except:
  1845. self.inform.emit("[error_notcl] Failed to write factory defaults to file.")
  1846. return
  1847. if silent is False:
  1848. self.inform.emit("Factory defaults saved.")
  1849. def final_save(self):
  1850. self.save_defaults()
  1851. log.debug("Application defaults saved ... Exit event.")
  1852. def on_toggle_shell(self):
  1853. """
  1854. toggle shell if is visible close it if closed open it
  1855. :return:
  1856. """
  1857. if self.ui.shell_dock.isVisible():
  1858. self.ui.shell_dock.hide()
  1859. else:
  1860. self.ui.shell_dock.show()
  1861. def on_edit_join(self, name=None):
  1862. """
  1863. Callback for Edit->Join. Joins the selected geometry objects into
  1864. a new one.
  1865. :return: None
  1866. """
  1867. obj_name_single = str(name) if name else "Combo_SingleGeo"
  1868. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  1869. tooldias = []
  1870. geo_type_list = []
  1871. objs = self.collection.get_selected()
  1872. for obj in objs:
  1873. geo_type_list.append(obj.multigeo)
  1874. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  1875. if len(set(geo_type_list)) != 1:
  1876. self.inform.emit("[error] Failed join. The Geometry objects are of different types.\n"
  1877. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  1878. "convert from one to another and retry joining \n"
  1879. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  1880. "the result may not be what was expected. \n"
  1881. "Check the generated GCODE.")
  1882. return
  1883. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  1884. if True in geo_type_list:
  1885. def initialize(obj, app):
  1886. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  1887. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  1888. for v in obj.tools.values():
  1889. v['data']['name'] = obj_name_multi
  1890. self.new_object("geometry", obj_name_multi, initialize)
  1891. else:
  1892. def initialize(obj, app):
  1893. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  1894. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  1895. for v in obj.tools.values():
  1896. v['data']['name'] = obj_name_single
  1897. self.new_object("geometry", obj_name_single, initialize)
  1898. def on_edit_join_exc(self):
  1899. """
  1900. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  1901. a new one.
  1902. :return: None
  1903. """
  1904. objs = self.collection.get_selected()
  1905. for obj in objs:
  1906. if not isinstance(obj, FlatCAMExcellon):
  1907. self.inform.emit("[error_notcl]Failed. Excellon joining works only on Excellon objects.")
  1908. return
  1909. def initialize(obj, app):
  1910. FlatCAMExcellon.merge(objs, obj)
  1911. self.new_object("excellon", 'Combo_Excellon', initialize)
  1912. def on_convert_singlegeo_to_multigeo(self):
  1913. obj = self.collection.get_active()
  1914. if obj is None:
  1915. self.inform.emit("[error_notcl]Failed. Select a Geometry Object and try again.")
  1916. return
  1917. if not isinstance(obj, FlatCAMGeometry):
  1918. self.inform.emit("[error_notcl]Expected a FlatCAMGeometry, got %s" % type(obj))
  1919. return
  1920. obj.multigeo = True
  1921. for tooluid, dict_value in obj.tools.items():
  1922. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  1923. if not isinstance(obj.solid_geometry, list):
  1924. obj.solid_geometry = [obj.solid_geometry]
  1925. obj.solid_geometry[:] = []
  1926. obj.plot()
  1927. self.inform.emit("[success] A Geometry object was converted to MultiGeo type.")
  1928. def on_convert_multigeo_to_singlegeo(self):
  1929. obj = self.collection.get_active()
  1930. if obj is None:
  1931. self.inform.emit("[error_notcl]Failed. Select a Geometry Object and try again.")
  1932. return
  1933. if not isinstance(obj, FlatCAMGeometry):
  1934. self.inform.emit("[error_notcl]Expected a FlatCAMGeometry, got %s" % type(obj))
  1935. return
  1936. obj.multigeo = False
  1937. total_solid_geometry = []
  1938. for tooluid, dict_value in obj.tools.items():
  1939. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  1940. # clear the original geometry
  1941. dict_value['solid_geometry'][:] = []
  1942. obj.solid_geometry = deepcopy(total_solid_geometry)
  1943. obj.plot()
  1944. self.inform.emit("[success] A Geometry object was converted to SingleGeo type.")
  1945. def on_options_dict_change(self, field):
  1946. self.options_write_form_field(field)
  1947. if field == "units":
  1948. self.set_screen_units(self.options['units'])
  1949. def on_defaults_dict_change(self, field):
  1950. self.defaults_write_form_field(field)
  1951. def set_screen_units(self, units):
  1952. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  1953. def on_toggle_units(self):
  1954. """
  1955. Callback for the Units radio-button change in the Options tab.
  1956. Changes the application's default units or the current project's units.
  1957. If changing the project's units, the change propagates to all of
  1958. the objects in the project.
  1959. :return: None
  1960. """
  1961. self.report_usage("on_toggle_units")
  1962. if self.toggle_units_ignore:
  1963. return
  1964. # If option is the same, then ignore
  1965. if self.general_options_form.general_group.units_radio.get_value().upper() == self.options["units"].upper():
  1966. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  1967. return
  1968. # Options to scale
  1969. dimensions = ['gerber_isotooldia', 'gerber_cutoutmargin', 'gerber_cutoutgapsize',
  1970. 'gerber_noncoppermargin', 'gerber_bboxmargin','gerber_isooverlap','gerber_nccoverlap',
  1971. 'gerber_nccmargin','gerber_cutouttooldia','gerber_cutoutgapsize','gerber_cutoutmargin',
  1972. 'gerber_noncoppermargin','gerber_bboxmargin',
  1973. 'excellon_drillz', "excellon_toolchangexy",
  1974. 'excellon_travelz', 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  1975. 'excellon_tooldia', 'excellon_endz', 'cncjob_tooldia',
  1976. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate', 'geometry_feedrate_rapid',
  1977. 'geometry_cnctooldia', 'geometry_painttooldia', 'geometry_paintoverlap', 'geometry_toolchangexy',
  1978. 'geometry_toolchangez',
  1979. 'geometry_paintmargin', 'geometry_endz', 'geometry_depthperpass', 'global_gridx', 'global_gridy']
  1980. def scale_options(sfactor):
  1981. for dim in dimensions:
  1982. if dim == 'excellon_toolchangexy':
  1983. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  1984. coords_xy[0] *= sfactor
  1985. coords_xy[1] *= sfactor
  1986. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  1987. elif dim == 'geometry_toolchangexy':
  1988. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  1989. coords_xy[0] *= sfactor
  1990. coords_xy[1] *= sfactor
  1991. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  1992. else:
  1993. self.options[dim] *= sfactor
  1994. # The scaling factor depending on choice of units.
  1995. factor = 1/25.4
  1996. if self.general_options_form.general_group.units_radio.get_value().upper() == 'MM':
  1997. factor = 25.4
  1998. # Changing project units. Warn user.
  1999. msgbox = QtWidgets.QMessageBox()
  2000. msgbox.setText("<B>Change project units ...</B>")
  2001. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2002. "properties of all objects to be scaled accordingly. Continue?")
  2003. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2004. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2005. response = msgbox.exec_()
  2006. if response == QtWidgets.QMessageBox.Ok:
  2007. self.options_read_form()
  2008. scale_options(factor)
  2009. self.options_write_form()
  2010. # change this only if the workspace is active
  2011. if self.defaults['global_workspace'] is True:
  2012. self.plotcanvas.draw_workspace()
  2013. # adjust the grid values on the main toolbar
  2014. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2015. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2016. for obj in self.collection.get_list():
  2017. units = self.general_options_form.general_group.units_radio.get_value().upper()
  2018. obj.convert_units(units)
  2019. # make that the properties stored in the object are also updated
  2020. self.object_changed.emit(obj)
  2021. obj.build_ui()
  2022. current = self.collection.get_active()
  2023. if current is not None:
  2024. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2025. if not isinstance(current, FlatCAMGeometry):
  2026. current.to_form()
  2027. self.plot_all()
  2028. else:
  2029. # Undo toggling
  2030. self.toggle_units_ignore = True
  2031. if self.general_options_form.general_group.units_radio.get_value().upper() == 'MM':
  2032. self.general_options_form.general_group.units_radio.set_value('IN')
  2033. else:
  2034. self.general_options_form.general_group.units_radio.set_value('MM')
  2035. self.toggle_units_ignore = False
  2036. self.options_read_form()
  2037. self.inform.emit("Converted units to %s" % self.options["units"])
  2038. #self.ui.units_label.setText("[" + self.options["units"] + "]")
  2039. self.set_screen_units(self.options["units"])
  2040. def on_toggle_axis(self):
  2041. if self.toggle_axis is False:
  2042. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2043. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2044. self.plotcanvas.redraw()
  2045. self.toggle_axis = True
  2046. else:
  2047. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2048. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2049. self.plotcanvas.redraw()
  2050. self.toggle_axis = False
  2051. def on_options_combo_change(self, sel):
  2052. """
  2053. Called when the combo box to choose between application defaults and
  2054. project option changes value. The corresponding variables are
  2055. copied to the UI.
  2056. :param sel: The option index that was chosen.
  2057. :return: None
  2058. """
  2059. # combo_sel = self.ui.notebook.combo_options.get_active()
  2060. App.log.debug("Options --> %s" % sel)
  2061. # form = [self.defaults_form, self.options_form][sel]
  2062. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2063. if sel == 0:
  2064. self.gen_form = self.general_defaults_form
  2065. self.ger_form = self.gerber_defaults_form
  2066. self.exc_form = self.excellon_defaults_form
  2067. self.geo_form = self.geometry_defaults_form
  2068. self.cnc_form = self.cncjob_defaults_form
  2069. elif sel == 1:
  2070. self.gen_form = self.general_options_form
  2071. self.ger_form = self.gerber_options_form
  2072. self.exc_form = self.excellon_options_form
  2073. self.geo_form = self.geometry_options_form
  2074. self.cnc_form = self.cncjob_options_form
  2075. else:
  2076. return
  2077. try:
  2078. self.ui.general_scroll_area.takeWidget()
  2079. except:
  2080. self.log.debug("Nothing to remove")
  2081. self.ui.general_scroll_area.setWidget(self.gen_form)
  2082. self.gen_form.show()
  2083. try:
  2084. self.ui.gerber_scroll_area.takeWidget()
  2085. except:
  2086. self.log.debug("Nothing to remove")
  2087. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2088. self.ger_form.show()
  2089. try:
  2090. self.ui.excellon_scroll_area.takeWidget()
  2091. except:
  2092. self.log.debug("Nothing to remove")
  2093. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2094. self.exc_form.show()
  2095. try:
  2096. self.ui.geometry_scroll_area.takeWidget()
  2097. except:
  2098. self.log.debug("Nothing to remove")
  2099. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2100. self.geo_form.show()
  2101. try:
  2102. self.ui.cncjob_scroll_area.takeWidget()
  2103. except:
  2104. self.log.debug("Nothing to remove")
  2105. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2106. self.cnc_form.show()
  2107. self.log.debug("Finished GUI form initialization.")
  2108. # self.options2form()
  2109. def on_excellon_defaults_button(self):
  2110. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2111. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2112. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2113. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2114. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2115. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2116. log.debug("Excellon app defaults loaded ...")
  2117. def on_excellon_options_button(self):
  2118. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2119. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2120. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2121. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2122. self.options_form_fields["excellon_zeros"].set_value('L')
  2123. self.options_form_fields["excellon_units"].set_value('INCH')
  2124. log.debug("Excellon options defaults loaded ...")
  2125. # Setting plot colors handlers
  2126. def on_pf_color_entry(self):
  2127. self.defaults['global_plot_fill'] = self.general_defaults_form.general_group.pf_color_entry.get_value()[:7] + \
  2128. self.defaults['global_plot_fill'][7:9]
  2129. self.general_defaults_form.general_group.pf_color_button.setStyleSheet(
  2130. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2131. def on_pf_color_button(self):
  2132. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2133. c_dialog = QtWidgets.QColorDialog()
  2134. plot_fill_color = c_dialog.getColor(initial=current_color)
  2135. if plot_fill_color.isValid() is False:
  2136. return
  2137. self.general_defaults_form.general_group.pf_color_button.setStyleSheet(
  2138. "background-color:%s" % str(plot_fill_color.name()))
  2139. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2140. self.general_defaults_form.general_group.pf_color_entry.set_value(new_val)
  2141. self.defaults['global_plot_fill'] = new_val
  2142. def on_pf_color_spinner(self):
  2143. spinner_value = self.general_defaults_form.general_group.pf_color_alpha_spinner.value()
  2144. self.general_defaults_form.general_group.pf_color_alpha_slider.setValue(spinner_value)
  2145. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2146. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2147. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2148. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2149. def on_pf_color_slider(self):
  2150. slider_value = self.general_defaults_form.general_group.pf_color_alpha_slider.value()
  2151. self.general_defaults_form.general_group.pf_color_alpha_spinner.setValue(slider_value)
  2152. def on_pl_color_entry(self):
  2153. self.defaults['global_plot_line'] = self.general_defaults_form.general_group.pl_color_entry.get_value()[:7] + \
  2154. self.defaults['global_plot_line'][7:9]
  2155. self.general_defaults_form.general_group.pl_color_button.setStyleSheet(
  2156. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2157. def on_pl_color_button(self):
  2158. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2159. # print(current_color)
  2160. c_dialog = QtWidgets.QColorDialog()
  2161. plot_line_color = c_dialog.getColor(initial=current_color)
  2162. if plot_line_color.isValid() is False:
  2163. return
  2164. self.general_defaults_form.general_group.pl_color_button.setStyleSheet(
  2165. "background-color:%s" % str(plot_line_color.name()))
  2166. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2167. self.general_defaults_form.general_group.pl_color_entry.set_value(new_val_line)
  2168. self.defaults['global_plot_line'] = new_val_line
  2169. # Setting selection colors (left - right) handlers
  2170. def on_sf_color_entry(self):
  2171. self.defaults['global_sel_fill'] = self.general_defaults_form.general_group.sf_color_entry.get_value()[:7] + \
  2172. self.defaults['global_sel_fill'][7:9]
  2173. self.general_defaults_form.general_group.sf_color_button.setStyleSheet(
  2174. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2175. def on_sf_color_button(self):
  2176. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2177. c_dialog = QtWidgets.QColorDialog()
  2178. plot_fill_color = c_dialog.getColor(initial=current_color)
  2179. if plot_fill_color.isValid() is False:
  2180. return
  2181. self.general_defaults_form.general_group.sf_color_button.setStyleSheet(
  2182. "background-color:%s" % str(plot_fill_color.name()))
  2183. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2184. self.general_defaults_form.general_group.sf_color_entry.set_value(new_val)
  2185. self.defaults['global_sel_fill'] = new_val
  2186. def on_sf_color_spinner(self):
  2187. spinner_value = self.general_defaults_form.general_group.sf_color_alpha_spinner.value()
  2188. self.general_defaults_form.general_group.sf_color_alpha_slider.setValue(spinner_value)
  2189. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2190. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2191. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2192. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2193. def on_sf_color_slider(self):
  2194. slider_value = self.general_defaults_form.general_group.sf_color_alpha_slider.value()
  2195. self.general_defaults_form.general_group.sf_color_alpha_spinner.setValue(slider_value)
  2196. def on_sl_color_entry(self):
  2197. self.defaults['global_sel_line'] = self.general_defaults_form.general_group.sl_color_entry.get_value()[:7] + \
  2198. self.defaults['global_sel_line'][7:9]
  2199. self.general_defaults_form.general_group.sl_color_button.setStyleSheet(
  2200. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2201. def on_sl_color_button(self):
  2202. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2203. c_dialog = QtWidgets.QColorDialog()
  2204. plot_line_color = c_dialog.getColor(initial=current_color)
  2205. if plot_line_color.isValid() is False:
  2206. return
  2207. self.general_defaults_form.general_group.sl_color_button.setStyleSheet(
  2208. "background-color:%s" % str(plot_line_color.name()))
  2209. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2210. self.general_defaults_form.general_group.sl_color_entry.set_value(new_val_line)
  2211. self.defaults['global_sel_line'] = new_val_line
  2212. # Setting selection colors (right - left) handlers
  2213. def on_alt_sf_color_entry(self):
  2214. self.defaults['global_alt_sel_fill'] = self.general_defaults_form.general_group \
  2215. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2216. self.general_defaults_form.general_group.alt_sf_color_button.setStyleSheet(
  2217. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2218. def on_alt_sf_color_button(self):
  2219. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2220. c_dialog = QtWidgets.QColorDialog()
  2221. plot_fill_color = c_dialog.getColor(initial=current_color)
  2222. if plot_fill_color.isValid() is False:
  2223. return
  2224. self.general_defaults_form.general_group.alt_sf_color_button.setStyleSheet(
  2225. "background-color:%s" % str(plot_fill_color.name()))
  2226. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2227. self.general_defaults_form.general_group.alt_sf_color_entry.set_value(new_val)
  2228. self.defaults['global_alt_sel_fill'] = new_val
  2229. def on_alt_sf_color_spinner(self):
  2230. spinner_value = self.general_defaults_form.general_group.alt_sf_color_alpha_spinner.value()
  2231. self.general_defaults_form.general_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2232. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2233. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2234. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2235. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2236. def on_alt_sf_color_slider(self):
  2237. slider_value = self.general_defaults_form.general_group.alt_sf_color_alpha_slider.value()
  2238. self.general_defaults_form.general_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2239. def on_alt_sl_color_entry(self):
  2240. self.defaults['global_alt_sel_line'] = self.general_defaults_form.general_group \
  2241. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2242. self.general_defaults_form.general_group.alt_sl_color_button.setStyleSheet(
  2243. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2244. def on_alt_sl_color_button(self):
  2245. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2246. c_dialog = QtWidgets.QColorDialog()
  2247. plot_line_color = c_dialog.getColor(initial=current_color)
  2248. if plot_line_color.isValid() is False:
  2249. return
  2250. self.general_defaults_form.general_group.alt_sl_color_button.setStyleSheet(
  2251. "background-color:%s" % str(plot_line_color.name()))
  2252. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2253. self.general_defaults_form.general_group.alt_sl_color_entry.set_value(new_val_line)
  2254. self.defaults['global_alt_sel_line'] = new_val_line
  2255. # Setting Editor colors
  2256. def on_draw_color_entry(self):
  2257. self.defaults['global_draw_color'] = self.general_defaults_form.general_group \
  2258. .draw_color_entry.get_value()
  2259. self.general_defaults_form.general_group.draw_color_button.setStyleSheet(
  2260. "background-color:%s" % str(self.defaults['global_draw_color']))
  2261. def on_draw_color_button(self):
  2262. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2263. c_dialog = QtWidgets.QColorDialog()
  2264. draw_color = c_dialog.getColor(initial=current_color)
  2265. if draw_color.isValid() is False:
  2266. return
  2267. self.general_defaults_form.general_group.draw_color_button.setStyleSheet(
  2268. "background-color:%s" % str(draw_color.name()))
  2269. new_val = str(draw_color.name())
  2270. self.general_defaults_form.general_group.draw_color_entry.set_value(new_val)
  2271. self.defaults['global_draw_color'] = new_val
  2272. def on_sel_draw_color_entry(self):
  2273. self.defaults['global_sel_draw_color'] = self.general_defaults_form.general_group \
  2274. .sel_draw_color_entry.get_value()
  2275. self.general_defaults_form.general_group.sel_draw_color_button.setStyleSheet(
  2276. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  2277. def on_sel_draw_color_button(self):
  2278. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  2279. c_dialog = QtWidgets.QColorDialog()
  2280. sel_draw_color = c_dialog.getColor(initial=current_color)
  2281. if sel_draw_color.isValid() is False:
  2282. return
  2283. self.general_defaults_form.general_group.sel_draw_color_button.setStyleSheet(
  2284. "background-color:%s" % str(sel_draw_color.name()))
  2285. new_val_sel = str(sel_draw_color.name())
  2286. self.general_defaults_form.general_group.sel_draw_color_entry.set_value(new_val_sel)
  2287. self.defaults['global_sel_draw_color'] = new_val_sel
  2288. def on_workspace_modified(self):
  2289. self.save_defaults(silent=True)
  2290. self.plotcanvas.draw_workspace()
  2291. def on_workspace(self):
  2292. if self.general_defaults_form.general_group.workspace_cb.isChecked():
  2293. self.plotcanvas.restore_workspace()
  2294. else:
  2295. self.plotcanvas.delete_workspace()
  2296. self.save_defaults(silent=True)
  2297. def on_workspace_menu(self):
  2298. if self.general_defaults_form.general_group.workspace_cb.isChecked():
  2299. self.general_defaults_form.general_group.workspace_cb.setChecked(False)
  2300. else:
  2301. self.general_defaults_form.general_group.workspace_cb.setChecked(True)
  2302. self.on_workspace()
  2303. def on_save_button(self):
  2304. self.save_defaults(silent=False)
  2305. # load the defaults so they are updated into the app
  2306. self.load_defaults()
  2307. # Re-fresh project options
  2308. self.on_options_app2project()
  2309. def handleOpen(self):
  2310. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2311. "All Files (*.*)"
  2312. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  2313. caption='Open file', directory=self.get_last_folder(), filter=filter_group)
  2314. if path:
  2315. file = QtCore.QFile(path)
  2316. if file.open(QtCore.QIODevice.ReadOnly):
  2317. stream = QtCore.QTextStream(file)
  2318. self.gcode_edited = stream.readAll()
  2319. self.ui.code_editor.setPlainText(self.gcode_edited)
  2320. file.close()
  2321. def handlePrint(self):
  2322. dialog = QtPrintSupport.QPrintDialog()
  2323. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  2324. self.ui.code_editor.document().print_(dialog.printer())
  2325. def handlePreview(self):
  2326. dialog = QtPrintSupport.QPrintPreviewDialog()
  2327. dialog.paintRequested.connect(self.ui.code_editor.print_)
  2328. dialog.exec_()
  2329. def handleTextChanged(self):
  2330. # enable = not self.ui.code_editor.document().isEmpty()
  2331. # self.ui.buttonPrint.setEnabled(enable)
  2332. # self.ui.buttonPreview.setEnabled(enable)
  2333. pass
  2334. def handleSaveGCode(self):
  2335. _filter_ = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2336. "All Files (*.*)"
  2337. try:
  2338. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  2339. caption="Export G-Code ...", directory=self.defaults["global_last_folder"], filter=_filter_)[0])
  2340. except TypeError:
  2341. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export G-Code ...", filter=_filter_)[0])
  2342. try:
  2343. my_gcode = self.ui.code_editor.toPlainText()
  2344. with open(filename, 'w') as f:
  2345. for line in my_gcode:
  2346. f.write(line)
  2347. except FileNotFoundError:
  2348. self.inform.emit("[WARNING] No such file or directory")
  2349. return
  2350. # Just for adding it to the recent files list.
  2351. self.file_opened.emit("cncjob", filename)
  2352. self.file_saved.emit("cncjob", filename)
  2353. self.inform.emit("Saved to: " + filename)
  2354. def handleFindGCode(self):
  2355. flags = QtGui.QTextDocument.FindCaseSensitively
  2356. text_to_be_found = self.ui.entryFind.get_value()
  2357. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  2358. if r is False:
  2359. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2360. def handleReplaceGCode(self):
  2361. old = self.ui.entryFind.get_value()
  2362. new = self.ui.entryReplace.get_value()
  2363. if self.ui.sel_all_cb.isChecked():
  2364. while True:
  2365. cursor = self.ui.code_editor.textCursor()
  2366. cursor.beginEditBlock()
  2367. flags = QtGui.QTextDocument.FindCaseSensitively
  2368. # self.ui.editor is the QPlainTextEdit
  2369. r = self.ui.code_editor.find(str(old), flags)
  2370. if r:
  2371. qc = self.ui.code_editor.textCursor()
  2372. if qc.hasSelection():
  2373. qc.insertText(new)
  2374. else:
  2375. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2376. break
  2377. # Mark end of undo block
  2378. cursor.endEditBlock()
  2379. else:
  2380. cursor = self.ui.code_editor.textCursor()
  2381. cursor.beginEditBlock()
  2382. qc = self.ui.code_editor.textCursor()
  2383. if qc.hasSelection():
  2384. qc.insertText(new)
  2385. # Mark end of undo block
  2386. cursor.endEditBlock()
  2387. def on_new_geometry(self):
  2388. def initialize(obj, self):
  2389. obj.multitool = False
  2390. self.new_object('geometry', 'new_g', initialize)
  2391. self.plot_all()
  2392. def on_delete(self):
  2393. """
  2394. Delete the currently selected FlatCAMObjs.
  2395. :return: None
  2396. """
  2397. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  2398. # a geometry object before we update it.
  2399. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  2400. if self.collection.get_active():
  2401. self.log.debug("on_delete()")
  2402. self.report_usage("on_delete")
  2403. while (self.collection.get_active()):
  2404. self.delete_first_selected()
  2405. self.inform.emit("Object(s) deleted ...")
  2406. # make sure that the selection shape is deleted, too
  2407. self.delete_selection_shape()
  2408. else:
  2409. self.inform.emit("Failed. No object(s) selected...")
  2410. else:
  2411. self.inform.emit("Save the work in Editor and try again ...")
  2412. def on_set_origin(self):
  2413. """
  2414. Set the origin to the left mouse click position
  2415. :return: None
  2416. """
  2417. #display the message for the user
  2418. #and ask him to click on the desired position
  2419. self.inform.emit('Click to set the origin ...')
  2420. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  2421. def on_jump_to(self):
  2422. """
  2423. Jump to a location by setting the mouse cursor location
  2424. :return:
  2425. """
  2426. dia_box = Dialog_box(title="Jump to Coordinates", label="Enter the coordinates in format X,Y:")
  2427. if dia_box.ok is True:
  2428. try:
  2429. location = eval(dia_box.location)
  2430. if not isinstance(location, tuple):
  2431. self.inform.emit("Wrong coordinates. Enter coordinates in format: X,Y")
  2432. return
  2433. except:
  2434. return
  2435. else:
  2436. return
  2437. self.plotcanvas.fit_center(loc=location)
  2438. cursor = QtGui.QCursor()
  2439. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  2440. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  2441. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  2442. self.inform.emit("Done.")
  2443. def on_copy_object(self):
  2444. def initialize(obj_init, app):
  2445. obj_init.solid_geometry = obj.solid_geometry
  2446. if obj.tools:
  2447. obj_init.tools = obj.tools
  2448. def initialize_excellon(obj_init, app):
  2449. obj_init.tools = obj.tools
  2450. # drills are offset, so they need to be deep copied
  2451. obj_init.drills = deepcopy(obj.drills)
  2452. obj_init.create_geometry()
  2453. for obj in self.collection.get_selected():
  2454. obj_name = obj.options["name"]
  2455. try:
  2456. if isinstance(obj, FlatCAMExcellon):
  2457. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  2458. elif isinstance(obj,FlatCAMGerber):
  2459. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  2460. elif isinstance(obj,FlatCAMGeometry):
  2461. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  2462. except Exception as e:
  2463. return "Operation failed: %s" % str(e)
  2464. def on_copy_object2(self, custom_name):
  2465. def initialize_geometry(obj_init, app):
  2466. obj_init.solid_geometry = obj.solid_geometry
  2467. if obj.tools:
  2468. obj_init.tools = obj.tools
  2469. def initialize_gerber(obj_init, app):
  2470. obj_init.solid_geometry = obj.solid_geometry
  2471. obj_init.apertures = deepcopy(obj.apertures)
  2472. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  2473. def initialize_excellon(obj_init, app):
  2474. obj_init.tools = obj.tools
  2475. # drills are offset, so they need to be deep copied
  2476. obj_init.drills = deepcopy(obj.drills)
  2477. obj_init.create_geometry()
  2478. for obj in self.collection.get_selected():
  2479. obj_name = obj.options["name"]
  2480. try:
  2481. if isinstance(obj, FlatCAMExcellon):
  2482. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  2483. elif isinstance(obj,FlatCAMGerber):
  2484. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  2485. elif isinstance(obj,FlatCAMGeometry):
  2486. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  2487. except Exception as e:
  2488. return "Operation failed: %s" % str(e)
  2489. def on_rename_object(self, text):
  2490. named_obj = self.collection.get_active()
  2491. for obj in named_obj:
  2492. if obj is list:
  2493. self.on_rename_object(text)
  2494. else:
  2495. try:
  2496. obj.options['name'] = text
  2497. except:
  2498. log.warning("Could not rename the object in the list")
  2499. def on_copy_object_as_geometry(self):
  2500. def initialize(obj_init, app):
  2501. obj_init.solid_geometry = obj.solid_geometry
  2502. if obj.tools:
  2503. obj_init.tools = obj.tools
  2504. def initialize_excellon(obj, app):
  2505. objs = self.collection.get_selected()
  2506. FlatCAMGeometry.merge(objs, obj)
  2507. for obj in self.collection.get_selected():
  2508. obj_name = obj.options["name"]
  2509. try:
  2510. if isinstance(obj, FlatCAMExcellon):
  2511. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  2512. else:
  2513. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  2514. except Exception as e:
  2515. return "Operation failed: %s" % str(e)
  2516. def on_set_zero_click(self, event):
  2517. #this function will be available only for mouse left click
  2518. pos =[]
  2519. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  2520. if event.button == 1:
  2521. if self.grid_status() == True:
  2522. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2523. else:
  2524. pos = pos_canvas
  2525. x = 0 - pos[0]
  2526. y = 0 - pos[1]
  2527. for obj in self.collection.get_list():
  2528. obj.offset((x,y))
  2529. self.object_changed.emit(obj)
  2530. # obj.plot()
  2531. self.plot_all()
  2532. self.inform.emit('[success] Origin set ...')
  2533. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  2534. def on_selectall(self):
  2535. # delete the possible selection box around a possible selected object
  2536. self.delete_selection_shape()
  2537. for name in self.collection.get_names():
  2538. self.collection.set_active(name)
  2539. curr_sel_obj = self.collection.get_by_name(name)
  2540. # create the selection box around the selected object
  2541. self.draw_selection_shape(curr_sel_obj)
  2542. def on_preferences(self):
  2543. # add the tab if it was closed
  2544. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, "Preferences")
  2545. # delete the absolute and relative position and messages in the infobar
  2546. self.ui.position_label.setText("")
  2547. self.ui.rel_position_label.setText("")
  2548. # Switch plot_area to preferences page
  2549. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  2550. self.ui.show()
  2551. def on_flipy(self):
  2552. obj_list = self.collection.get_selected()
  2553. xminlist = []
  2554. yminlist = []
  2555. xmaxlist = []
  2556. ymaxlist = []
  2557. if not obj_list:
  2558. self.inform.emit("[warning_notcl] No object selected.")
  2559. msg = "Please Select an object to flip!"
  2560. warningbox = QtWidgets.QMessageBox()
  2561. warningbox.setText(msg)
  2562. warningbox.setWindowTitle("Warning ...")
  2563. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2564. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2565. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2566. warningbox.exec_()
  2567. else:
  2568. try:
  2569. # first get a bounding box to fit all
  2570. for obj in obj_list:
  2571. xmin, ymin, xmax, ymax = obj.bounds()
  2572. xminlist.append(xmin)
  2573. yminlist.append(ymin)
  2574. xmaxlist.append(xmax)
  2575. ymaxlist.append(ymax)
  2576. # get the minimum x,y and maximum x,y for all objects selected
  2577. xminimal = min(xminlist)
  2578. yminimal = min(yminlist)
  2579. xmaximal = max(xmaxlist)
  2580. ymaximal = max(ymaxlist)
  2581. px = 0.5 * (xminimal + xmaximal)
  2582. py = 0.5 * (yminimal + ymaximal)
  2583. # execute mirroring
  2584. for obj in obj_list:
  2585. obj.mirror('X', [px, py])
  2586. obj.plot()
  2587. self.object_changed.emit(obj)
  2588. except Exception as e:
  2589. self.inform.emit("[error_notcl] Due of %s, Flip action was not executed." % str(e))
  2590. return
  2591. def on_flipx(self):
  2592. obj_list = self.collection.get_selected()
  2593. xminlist = []
  2594. yminlist = []
  2595. xmaxlist = []
  2596. ymaxlist = []
  2597. if not obj_list:
  2598. self.inform.emit("[warning_notcl] No object selected.")
  2599. msg = "Please Select an object to flip!"
  2600. warningbox = QtWidgets.QMessageBox()
  2601. warningbox.setText(msg)
  2602. warningbox.setWindowTitle("Warning ...")
  2603. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2604. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2605. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2606. warningbox.exec_()
  2607. else:
  2608. try:
  2609. # first get a bounding box to fit all
  2610. for obj in obj_list:
  2611. xmin, ymin, xmax, ymax = obj.bounds()
  2612. xminlist.append(xmin)
  2613. yminlist.append(ymin)
  2614. xmaxlist.append(xmax)
  2615. ymaxlist.append(ymax)
  2616. # get the minimum x,y and maximum x,y for all objects selected
  2617. xminimal = min(xminlist)
  2618. yminimal = min(yminlist)
  2619. xmaximal = max(xmaxlist)
  2620. ymaximal = max(ymaxlist)
  2621. px = 0.5 * (xminimal + xmaximal)
  2622. py = 0.5 * (yminimal + ymaximal)
  2623. # execute mirroring
  2624. for obj in obj_list:
  2625. obj.mirror('Y', [px, py])
  2626. obj.plot()
  2627. self.object_changed.emit(obj)
  2628. except Exception as e:
  2629. self.inform.emit("[error_notcl] Due of %s, Flip action was not executed." % str(e))
  2630. return
  2631. def on_rotate(self, silent=False, preset=None):
  2632. obj_list = self.collection.get_selected()
  2633. xminlist = []
  2634. yminlist = []
  2635. xmaxlist = []
  2636. ymaxlist = []
  2637. if not obj_list:
  2638. self.inform.emit("[warning_notcl] No object selected.")
  2639. msg = "Please Select an object to rotate!"
  2640. warningbox = QtWidgets.QMessageBox()
  2641. warningbox.setText(msg)
  2642. warningbox.setWindowTitle("Warning ...")
  2643. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2644. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2645. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2646. warningbox.exec_()
  2647. else:
  2648. if silent is False:
  2649. rotatebox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2650. min=-360, max=360, decimals=3)
  2651. num, ok = rotatebox.get_value()
  2652. else:
  2653. num = preset
  2654. ok = True
  2655. if ok:
  2656. try:
  2657. # first get a bounding box to fit all
  2658. for obj in obj_list:
  2659. xmin, ymin, xmax, ymax = obj.bounds()
  2660. xminlist.append(xmin)
  2661. yminlist.append(ymin)
  2662. xmaxlist.append(xmax)
  2663. ymaxlist.append(ymax)
  2664. # get the minimum x,y and maximum x,y for all objects selected
  2665. xminimal = min(xminlist)
  2666. yminimal = min(yminlist)
  2667. xmaximal = max(xmaxlist)
  2668. ymaximal = max(ymaxlist)
  2669. px = 0.5 * (xminimal + xmaximal)
  2670. py = 0.5 * (yminimal + ymaximal)
  2671. for sel_obj in obj_list:
  2672. sel_obj.rotate(-num, point=(px, py))
  2673. sel_obj.plot()
  2674. self.object_changed.emit(sel_obj)
  2675. except Exception as e:
  2676. self.inform.emit("[error_notcl] Due of %s, rotation movement was not executed." % str(e))
  2677. return
  2678. def on_skewx(self):
  2679. obj_list = self.collection.get_selected()
  2680. xminlist = []
  2681. yminlist = []
  2682. if not obj_list:
  2683. self.inform.emit("[warning_notcl] No object selected.")
  2684. msg = "Please Select an object to skew/shear!"
  2685. warningbox = QtWidgets.QMessageBox()
  2686. warningbox.setText(msg)
  2687. warningbox.setWindowTitle("Warning ...")
  2688. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2689. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2690. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2691. warningbox.exec_()
  2692. else:
  2693. skewxbox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2694. min=-360, max=360, decimals=3)
  2695. num, ok = skewxbox.get_value()
  2696. if ok:
  2697. # first get a bounding box to fit all
  2698. for obj in obj_list:
  2699. xmin, ymin, xmax, ymax = obj.bounds()
  2700. xminlist.append(xmin)
  2701. yminlist.append(ymin)
  2702. # get the minimum x,y and maximum x,y for all objects selected
  2703. xminimal = min(xminlist)
  2704. yminimal = min(yminlist)
  2705. for obj in obj_list:
  2706. obj.skew(num, 0, point=(xminimal, yminimal))
  2707. obj.plot()
  2708. self.object_changed.emit(obj)
  2709. def on_skewy(self):
  2710. obj_list = self.collection.get_selected()
  2711. xminlist = []
  2712. yminlist = []
  2713. if not obj_list:
  2714. self.inform.emit("[warning_notcl] No object selected.")
  2715. msg = "Please Select an object to skew/shear!"
  2716. warningbox = QtWidgets.QMessageBox()
  2717. warningbox.setText(msg)
  2718. warningbox.setWindowTitle("Warning ...")
  2719. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2720. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2721. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2722. warningbox.exec_()
  2723. else:
  2724. skewybox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2725. min=-360, max=360, decimals=3)
  2726. num, ok = skewybox.get_value()
  2727. if ok:
  2728. # first get a bounding box to fit all
  2729. for obj in obj_list:
  2730. xmin, ymin, xmax, ymax = obj.bounds()
  2731. xminlist.append(xmin)
  2732. yminlist.append(ymin)
  2733. # get the minimum x,y and maximum x,y for all objects selected
  2734. xminimal = min(xminlist)
  2735. yminimal = min(yminlist)
  2736. for obj in obj_list:
  2737. obj.skew(0, num, point=(xminimal, yminimal))
  2738. obj.plot()
  2739. self.object_changed.emit(obj)
  2740. def delete_first_selected(self):
  2741. # Keep this for later
  2742. try:
  2743. name = self.collection.get_active().options["name"]
  2744. except AttributeError:
  2745. self.log.debug("Nothing selected for deletion")
  2746. return
  2747. # Remove plot
  2748. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  2749. # self.plotcanvas.auto_adjust_axes()
  2750. # Clear form
  2751. self.setup_component_editor()
  2752. # Remove from dictionary
  2753. self.collection.delete_active()
  2754. self.inform.emit("Object deleted: %s" % name)
  2755. def on_plots_updated(self):
  2756. """
  2757. Callback used to report when the plots have changed.
  2758. Adjust axes and zooms to fit.
  2759. :return: None
  2760. """
  2761. # self.plotcanvas.auto_adjust_axes()
  2762. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  2763. self.on_zoom_fit(None)
  2764. # TODO: Rework toolbar 'clear', 'replot' functions
  2765. def on_toolbar_replot(self):
  2766. """
  2767. Callback for toolbar button. Re-plots all objects.
  2768. :return: None
  2769. """
  2770. self.report_usage("on_toolbar_replot")
  2771. self.log.debug("on_toolbar_replot()")
  2772. try:
  2773. self.collection.get_active().read_form()
  2774. except AttributeError:
  2775. self.log.debug("on_toolbar_replot(): AttributeError")
  2776. pass
  2777. self.plot_all()
  2778. def on_row_activated(self, index):
  2779. if index.isValid():
  2780. if index.internalPointer().parent_item != self.collection.root_item:
  2781. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2782. def on_zoom_fit(self, event):
  2783. """
  2784. Callback for zoom-out request. This can be either from the corresponding
  2785. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  2786. with axes limits from the geometry bounds of all objects.
  2787. :param event: Ignored.
  2788. :return: None
  2789. """
  2790. self.plotcanvas.fit_view()
  2791. def grid_status(self):
  2792. if self.ui.grid_snap_btn.isChecked():
  2793. return 1
  2794. else:
  2795. return 0
  2796. def on_key_over_plot(self, event):
  2797. """
  2798. Callback for the key pressed event when the canvas is focused. Keyboard
  2799. shortcuts are handled here. So far, these are the shortcuts:
  2800. ========== ============================================
  2801. Key Action
  2802. ========== ============================================
  2803. '1' Zoom-fit. Fits the axes limits to the data.
  2804. '2' Zoom-out.
  2805. '3' Zoom-in.
  2806. 'ctrl+m' Toggle on-off the measuring tool.
  2807. ========== ============================================
  2808. :param event: Ignored.
  2809. :return: None
  2810. """
  2811. self.key_modifiers = QtWidgets.QApplication.keyboardModifiers()
  2812. if self.key_modifiers == QtCore.Qt.ControlModifier:
  2813. if event.key == 'A':
  2814. self.on_selectall()
  2815. if event.key == 'C':
  2816. self.on_copy_object()
  2817. if event.key == 'E':
  2818. self.on_fileopenexcellon()
  2819. if event.key == 'G':
  2820. self.on_fileopengerber()
  2821. if event.key == 'M':
  2822. self.measurement_tool.run()
  2823. if event.key == 'O':
  2824. self.on_file_openproject()
  2825. if event.key == 'S':
  2826. self.on_file_saveproject()
  2827. return
  2828. elif self.key_modifiers == QtCore.Qt.AltModifier:
  2829. # place holder for further shortcut key
  2830. return
  2831. elif self.key_modifiers == QtCore.Qt.ShiftModifier:
  2832. # place holder for further shortcut key
  2833. # Toggle axis
  2834. if event.key == 'G':
  2835. self.on_toggle_axis()
  2836. # Rotate Object by 90 degree CCW
  2837. if event.key == 'R':
  2838. self.on_rotate(silent=True, preset=-90)
  2839. # Toggle Workspace
  2840. if event.key == 'W':
  2841. self.on_workspace_menu()
  2842. return
  2843. else:
  2844. if event.key == self.defaults['fit_key']: # 1
  2845. self.on_zoom_fit(None)
  2846. return
  2847. if event.key == self.defaults['zoom_out_key']: # 2
  2848. self.plotcanvas.zoom(1 / self.defaults['zoom_ratio'], self.mouse)
  2849. return
  2850. if event.key == self.defaults['zoom_in_key']: # 3
  2851. self.plotcanvas.zoom(self.defaults['zoom_ratio'], self.mouse)
  2852. return
  2853. if event.key == 'Delete':
  2854. self.on_delete()
  2855. return
  2856. if event.key == 'Space':
  2857. if self.collection.get_active() is not None:
  2858. self.collection.get_active().ui.plot_cb.toggle()
  2859. self.delete_selection_shape()
  2860. if event.key == 'C':
  2861. self.on_copy_name()
  2862. if event.key == 'E':
  2863. self.object2editor()
  2864. if event.key == self.defaults['grid_toggle_key']: # G
  2865. self.ui.grid_snap_btn.trigger()
  2866. if event.key == 'J':
  2867. self.on_jump_to()
  2868. if event.key == 'M':
  2869. self.move_tool.toggle()
  2870. return
  2871. if event.key == 'N':
  2872. self.on_new_geometry()
  2873. if event.key == 'Q':
  2874. if self.options["units"] == 'MM':
  2875. self.general_options_form.general_group.units_radio.set_value("IN")
  2876. else:
  2877. self.general_options_form.general_group.units_radio.set_value("MM")
  2878. self.on_toggle_units()
  2879. if event.key == 'R':
  2880. self.on_rotate(silent=True, preset=90)
  2881. if event.key == 'S':
  2882. self.on_toggle_shell()
  2883. if event.key == 'T':
  2884. self.transform_tool.run()
  2885. if event.key == 'V':
  2886. self.on_zoom_fit(None)
  2887. if event.key == 'X':
  2888. self.on_flipx()
  2889. if event.key == 'Y':
  2890. self.on_flipy()
  2891. if event.key == '`':
  2892. self.on_shortcut_list()
  2893. def on_key_release_over_plot(self, event):
  2894. modifiers = QtWidgets.QApplication.keyboardModifiers()
  2895. if modifiers == QtCore.Qt.ControlModifier:
  2896. return
  2897. elif modifiers == QtCore.Qt.AltModifier:
  2898. # place holder for further shortcut key
  2899. return
  2900. elif modifiers == QtCore.Qt.ShiftModifier:
  2901. # place holder for further shortcut key
  2902. return
  2903. else:
  2904. return
  2905. def on_shortcut_list(self):
  2906. msg = '''<b>Shortcut list</b><br>
  2907. <br>
  2908. <b>~:</b> Show Shortcut List<br>
  2909. <br>
  2910. <b>1:</b> Zoom Fit<br>
  2911. <b>2:</b> Zoom Out<br>
  2912. <b>3:</b> Zoom In<br>
  2913. <b>A:</b> Draw an Arc (when in Edit Mode)<br>
  2914. <b>C:</b> Copy Obj_Name<br>
  2915. <b>C:</b> Copy Geo Item (when in Edit Mode)<br>
  2916. <b>E:</b> Edit Object (if selected)<br>
  2917. <b>G:</b> Grid On/Off<br>
  2918. <b>J:</b> Jump to Coordinates<br>
  2919. <b>M:</b> Move Obj<br>
  2920. <b>M:</b> Move Geo Item (when in Edit Mode)<br>
  2921. <b>N:</b> New Geometry<br>
  2922. <b>N:</b> Draw a Polygon (when in Edit Mode)<br>
  2923. <b>O:</b> Draw a Circle (when in Edit Mode)<br>
  2924. <b>Q:</b> Change Units<br>
  2925. <b>P:</b> Draw a Path (when in Edit Mode)<br>
  2926. <b>R:</b> Rotate by 90 degree CW<br>
  2927. <b>R:</b> Draw Rectangle (when in Edit Mode)<br>
  2928. <b>S:</b> Shell Toggle<br>
  2929. <b>T:</b> Transformation<br>
  2930. <b>V:</b> View Fit<br>
  2931. <b>X:</b> Flip on X_axis<br>
  2932. <b>Y:</b> Flip on Y_axis<br>
  2933. <br>
  2934. <b>Space:</b> En(Dis)able Obj Plot<br>
  2935. <b>CTRL+A:</b> Select All<br>
  2936. <b>CTRL+C:</b> Copy Obj<br>
  2937. <b>CTRL+E:</b> Open Excellon File<br>
  2938. <b>CTRL+G:</b> Open Gerber File<br>
  2939. <b>CTRL+M:</b> Measurement Tool<br>
  2940. <b>CTRL+O:</b> Open Project<br>
  2941. <b>CTRL+S:</b> Save Project As<br>
  2942. <b>CTRL+S:</b> Save Object and Exit Editor (when in Edit Mode)<br>
  2943. <br>
  2944. <b>SHIFT+G:</b> Toggle the axis<br>
  2945. <b>SHIFT+R:</b> Rotate by 90 degree CCW<br>
  2946. <b>SHIFT+W:</b> Toggle the workspace<br>
  2947. <b>Del:</b> Delete Obj'''
  2948. helpbox = QtWidgets.QMessageBox()
  2949. helpbox.setText(msg)
  2950. helpbox.setWindowTitle("Help")
  2951. helpbox.setWindowIcon(QtGui.QIcon('share/help.png'))
  2952. helpbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2953. helpbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2954. helpbox.exec_()
  2955. def on_copy_name(self):
  2956. obj = self.collection.get_active()
  2957. name = obj.options["name"]
  2958. self.clipboard.setText(name)
  2959. self.inform.emit("Name copied on clipboard ...")
  2960. def on_mouse_click_over_plot(self, event):
  2961. """
  2962. Callback for the mouse click event over the plot. This event is generated
  2963. by the Matplotlib backend and has been registered in ``self.__init__()``.
  2964. For details, see: http://matplotlib.org/users/event_handling.html
  2965. Default actions are:
  2966. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  2967. :param event: Contains information about the event, like which button
  2968. was clicked, the pixel coordinates and the axes coordinates.
  2969. :return: None
  2970. """
  2971. self.pos = []
  2972. # So it can receive key presses
  2973. self.plotcanvas.vispy_canvas.native.setFocus()
  2974. # Set the mouse button for panning
  2975. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  2976. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  2977. if self.grid_status() == True:
  2978. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  2979. self.app_cursor.enabled = True
  2980. else:
  2981. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  2982. self.app_cursor.enabled = False
  2983. try:
  2984. App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  2985. event.button, event.pos[0], event.pos[1], self.pos[0], self.pos[1]))
  2986. modifiers = QtWidgets.QApplication.keyboardModifiers()
  2987. if event.button == 1:
  2988. # Reset here the relative coordinates so there is a new reference on the click position
  2989. if self.rel_point1 is None:
  2990. self.rel_point1 = self.pos
  2991. else:
  2992. self.rel_point2 = copy(self.rel_point1)
  2993. self.rel_point1 = self.pos
  2994. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  2995. if modifiers == QtCore.Qt.ShiftModifier:
  2996. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  2997. return
  2998. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  2999. # and if it's not selected then it will be selected
  3000. if modifiers == QtCore.Qt.ControlModifier:
  3001. # If there is no active command (self.command_active is None) then we check if we clicked on
  3002. # a object by checking the bounding limits against mouse click position
  3003. if self.command_active is None:
  3004. self.select_objects(key='CTRL')
  3005. else:
  3006. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  3007. # checking the bounding limits against mouse click position
  3008. if self.command_active is None:
  3009. self.select_objects()
  3010. self.on_mouse_move_over_plot(event, origin_click=True)
  3011. except Exception as e:
  3012. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3013. def on_double_click_over_plot(self, event):
  3014. # make double click work only for the LMB
  3015. if event.button == 1:
  3016. if not self.collection.get_selected():
  3017. pass
  3018. else:
  3019. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3020. #delete the selection shape(S) as it may be in the way
  3021. self.delete_selection_shape()
  3022. def on_mouse_move_over_plot(self, event, origin_click=None):
  3023. """
  3024. Callback for the mouse motion event over the plot. This event is generated
  3025. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3026. For details, see: http://matplotlib.org/users/event_handling.html
  3027. :param event: Contains information about the event.
  3028. :param origin_click
  3029. :return: None
  3030. """
  3031. # So it can receive key presses
  3032. self.plotcanvas.vispy_canvas.native.setFocus()
  3033. self.pos_jump = event.pos
  3034. if origin_click is True:
  3035. pass
  3036. else:
  3037. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3038. if event.button == 2:
  3039. self.panning_action = True
  3040. return
  3041. else:
  3042. self.panning_action = False
  3043. if self.rel_point1 is not None:
  3044. try: # May fail in case mouse not within axes
  3045. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3046. if self.grid_status():
  3047. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3048. self.app_cursor.enabled = True
  3049. # Update cursor
  3050. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3051. else:
  3052. pos = (pos_canvas[0], pos_canvas[1])
  3053. self.app_cursor.enabled = False
  3054. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3055. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3056. dx = pos[0] - self.rel_point1[0]
  3057. dy = pos[1] - self.rel_point1[1]
  3058. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3059. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3060. self.mouse = [pos[0], pos[1]]
  3061. # if the mouse is moved and the LMB is clicked then the action is a selection
  3062. if event.is_dragging == 1 and event.button == 1:
  3063. self.delete_selection_shape()
  3064. if dx < 0:
  3065. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3066. face_color=self.defaults['global_alt_sel_fill'])
  3067. self.selection_type = False
  3068. else:
  3069. self.draw_moving_selection_shape(self.pos, pos)
  3070. self.selection_type = True
  3071. # delete the status message on mouse move
  3072. # self.inform.emit("")
  3073. except:
  3074. self.ui.position_label.setText("")
  3075. self.ui.rel_position_label.setText("")
  3076. self.mouse = None
  3077. def on_mouse_click_release_over_plot(self, event):
  3078. """
  3079. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3080. and has been registered in ''self.__init__()''.
  3081. :param event: contains information about the event.
  3082. :return:
  3083. """
  3084. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3085. if self.grid_status():
  3086. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3087. else:
  3088. pos = (pos_canvas[0], pos_canvas[1])
  3089. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3090. # canvas menu
  3091. try:
  3092. if event.button == 2: # right click
  3093. if self.panning_action is True:
  3094. self.panning_action = False
  3095. else:
  3096. self.cursor = QtGui.QCursor()
  3097. self.ui.popMenu.popup(self.cursor.pos())
  3098. except Exception as e:
  3099. log.warning("Error: %s" % str(e))
  3100. return
  3101. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3102. # selection and then select a type of selection ("enclosing" or "touching")
  3103. try:
  3104. if event.button == 1: # left click
  3105. if self.selection_type is not None:
  3106. self.selection_area_handler(self.pos, pos, self.selection_type)
  3107. self.selection_type = None
  3108. except Exception as e:
  3109. log.warning("Error: %s" % str(e))
  3110. return
  3111. def selection_area_handler(self, start_pos, end_pos, sel_type):
  3112. """
  3113. :param start_pos: mouse position when the selection LMB click was done
  3114. :param end_pos: mouse position when the left mouse button is released
  3115. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3116. :return:
  3117. """
  3118. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3119. self.delete_selection_shape()
  3120. for obj in self.collection.get_list():
  3121. try:
  3122. # select the object(s) only if it is enabled (plotted)
  3123. if obj.options['plot']:
  3124. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']), (obj.options['xmax'], obj.options['ymin']),
  3125. (obj.options['xmax'], obj.options['ymax']), (obj.options['xmin'], obj.options['ymax'])])
  3126. if sel_type is True:
  3127. if poly_obj.within(poly_selection):
  3128. # create the selection box around the selected object
  3129. self.draw_selection_shape(obj)
  3130. self.collection.set_active(obj.options['name'])
  3131. else:
  3132. if poly_selection.intersects(poly_obj):
  3133. # create the selection box around the selected object
  3134. self.draw_selection_shape(obj)
  3135. self.collection.set_active(obj.options['name'])
  3136. except:
  3137. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  3138. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  3139. # In this case poly_obj creation (see above) will fail
  3140. pass
  3141. def select_objects(self, key=None):
  3142. # list where we store the overlapped objects under our mouse left click position
  3143. objects_under_the_click_list = []
  3144. # Populate the list with the overlapped objects on the click position
  3145. curr_x, curr_y = self.pos
  3146. for obj in self.all_objects_list:
  3147. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  3148. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  3149. if obj.options['name'] not in objects_under_the_click_list:
  3150. if obj.options['plot']:
  3151. # add objects to the objects_under_the_click list only if the object is plotted
  3152. # (active and not disabled)
  3153. objects_under_the_click_list.append(obj.options['name'])
  3154. try:
  3155. # If there is no element in the overlapped objects list then make everyone inactive
  3156. # because we selected "nothing"
  3157. if not objects_under_the_click_list:
  3158. self.collection.set_all_inactive()
  3159. # delete the possible selection box around a possible selected object
  3160. self.delete_selection_shape()
  3161. # and as a convenience move the focus to the Project tab because Selected tab is now empty
  3162. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3163. else:
  3164. # case when there is only an object under the click and we toggle it
  3165. if len(objects_under_the_click_list) == 1:
  3166. if self.collection.get_active() is None :
  3167. self.collection.set_active(objects_under_the_click_list[0])
  3168. # create the selection box around the selected object
  3169. curr_sel_obj = self.collection.get_active()
  3170. self.draw_selection_shape(curr_sel_obj)
  3171. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  3172. self.collection.set_all_inactive()
  3173. self.delete_selection_shape()
  3174. self.collection.set_active(objects_under_the_click_list[0])
  3175. # create the selection box around the selected object
  3176. curr_sel_obj = self.collection.get_active()
  3177. self.draw_selection_shape(curr_sel_obj)
  3178. else:
  3179. self.collection.set_all_inactive()
  3180. self.delete_selection_shape()
  3181. else:
  3182. # If there is no selected object
  3183. # make active the first element of the overlapped objects list
  3184. if self.collection.get_active() is None:
  3185. self.collection.set_active(objects_under_the_click_list[0])
  3186. name_sel_obj = self.collection.get_active().options['name']
  3187. # In case that there is a selected object but it is not in the overlapped object list
  3188. # make that object inactive and activate the first element in the overlapped object list
  3189. if name_sel_obj not in objects_under_the_click_list:
  3190. self.collection.set_inactive(name_sel_obj)
  3191. name_sel_obj = objects_under_the_click_list[0]
  3192. self.collection.set_active(name_sel_obj)
  3193. else:
  3194. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  3195. self.collection.set_all_inactive()
  3196. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) % len(objects_under_the_click_list)])
  3197. curr_sel_obj = self.collection.get_active()
  3198. # delete the possible selection box around a possible selected object
  3199. self.delete_selection_shape()
  3200. # create the selection box around the selected object
  3201. self.draw_selection_shape(curr_sel_obj)
  3202. # for obj in self.collection.get_list():
  3203. # obj.plot()
  3204. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  3205. # TODO: on selected objects change the object colors and do not draw the selection box
  3206. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  3207. except Exception as e:
  3208. log.error("[error] Something went bad. %s" % str(e))
  3209. return
  3210. def delete_selection_shape(self):
  3211. self.move_tool.sel_shapes.clear()
  3212. self.move_tool.sel_shapes.redraw()
  3213. def draw_selection_shape(self, sel_obj):
  3214. """
  3215. :param sel_obj: the object for which the selection shape must be drawn
  3216. :return:
  3217. """
  3218. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  3219. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  3220. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  3221. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  3222. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3223. #blue_t = Color('blue')
  3224. blue_t = Color(self.defaults['global_sel_fill'])
  3225. blue_t.alpha = 0.3
  3226. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=self.defaults['global_sel_line'],
  3227. face_color=blue_t, update=True, layer=0, tolerance=None))
  3228. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  3229. """
  3230. :param old_coords: old coordinates
  3231. :param coords: new coordinates
  3232. :return:
  3233. """
  3234. if 'color' in kwargs:
  3235. color = kwargs['color']
  3236. else:
  3237. color = self.defaults['global_sel_line']
  3238. if 'face_color' in kwargs:
  3239. face_color = kwargs['face_color']
  3240. else:
  3241. face_color = self.defaults['global_sel_fill']
  3242. x0, y0 = old_coords
  3243. x1, y1 = coords
  3244. pt1 = (x0, y0)
  3245. pt2 = (x1, y0)
  3246. pt3 = (x1, y1)
  3247. pt4 = (x0, y1)
  3248. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3249. color_t = Color(face_color)
  3250. color_t.alpha = 0.3
  3251. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  3252. layer=0, tolerance=None)
  3253. def on_file_new(self):
  3254. """
  3255. Callback for menu item File->New. Returns the application to its
  3256. startup state. This method is thread-safe.
  3257. :return: None
  3258. """
  3259. self.report_usage("on_file_new")
  3260. # Remove everything from memory
  3261. App.log.debug("on_file_new()")
  3262. # Clear pool
  3263. self.clear_pool()
  3264. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  3265. self.init_tcl()
  3266. self.delete_selection_shape()
  3267. self.collection.delete_all()
  3268. self.setup_component_editor()
  3269. # Clear project filename
  3270. self.project_filename = None
  3271. # Load the application defaults
  3272. self.load_defaults()
  3273. # Re-fresh project options
  3274. self.on_options_app2project()
  3275. # Init Tools
  3276. self.init_tools()
  3277. # take the focus of the Notebook on Project Tab.
  3278. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3279. def obj_properties(self):
  3280. self.properties_tool.run()
  3281. def on_fileopengerber(self):
  3282. """
  3283. File menu callback for opening a Gerber.
  3284. :return: None
  3285. """
  3286. self.report_usage("on_fileopengerber")
  3287. App.log.debug("on_fileopengerber()")
  3288. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3289. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3290. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3291. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3292. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3293. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3294. "Allegro Files (*.art);;" \
  3295. "Mentor Files (*.pho *.gdo);;" \
  3296. "All Files (*.*)"
  3297. try:
  3298. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber",
  3299. directory=self.get_last_folder(), filter=_filter_)
  3300. except TypeError:
  3301. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber", filter=_filter_)
  3302. # The Qt methods above will return a QString which can cause problems later.
  3303. # So far json.dump() will fail to serialize it.
  3304. # TODO: Improve the serialization methods and remove this fix.
  3305. filename = str(filename)
  3306. if filename == "":
  3307. self.inform.emit("[warning_notcl]Open Gerber cancelled.")
  3308. else:
  3309. self.worker_task.emit({'fcn': self.open_gerber,
  3310. 'params': [filename]})
  3311. def on_fileopengerber_follow(self):
  3312. """
  3313. File menu callback for opening a Gerber.
  3314. :return: None
  3315. """
  3316. self.report_usage("on_fileopengerber_follow")
  3317. App.log.debug("on_fileopengerber_follow()")
  3318. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3319. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3320. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3321. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3322. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3323. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3324. "Allegro Files (*.art);;" \
  3325. "Mentor Files (*.pho *.gdo);;" \
  3326. "All Files (*.*)"
  3327. try:
  3328. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow",
  3329. directory=self.get_last_folder(), filter=_filter_)
  3330. except TypeError:
  3331. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow", filter=_filter_)
  3332. # The Qt methods above will return a QString which can cause problems later.
  3333. # So far json.dump() will fail to serialize it.
  3334. # TODO: Improve the serialization methods and remove this fix.
  3335. filename = str(filename)
  3336. follow = True
  3337. if filename == "":
  3338. self.inform.emit("[warning_notcl]Open Gerber-Follow cancelled.")
  3339. else:
  3340. self.worker_task.emit({'fcn': self.open_gerber,
  3341. 'params': [filename, follow]})
  3342. def on_fileopenexcellon(self):
  3343. """
  3344. File menu callback for opening an Excellon file.
  3345. :return: None
  3346. """
  3347. self.report_usage("on_fileopenexcellon")
  3348. App.log.debug("on_fileopenexcellon()")
  3349. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  3350. "All Files (*.*)"
  3351. try:
  3352. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Excellon",
  3353. directory=self.get_last_folder(), filter=_filter_)
  3354. except TypeError:
  3355. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Excellon", filter=_filter_)
  3356. # The Qt methods above will return a QString which can cause problems later.
  3357. # So far json.dump() will fail to serialize it.
  3358. # TODO: Improve the serialization methods and remove this fix.
  3359. filename = str(filename)
  3360. if filename == "":
  3361. self.inform.emit("[warning_notcl]Open Excellon cancelled.")
  3362. else:
  3363. self.worker_task.emit({'fcn': self.open_excellon,
  3364. 'params': [filename]})
  3365. def on_fileopengcode(self):
  3366. """
  3367. File menu call back for opening gcode.
  3368. :return: None
  3369. """
  3370. self.report_usage("on_fileopengcode")
  3371. App.log.debug("on_fileopengcode()")
  3372. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  3373. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  3374. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  3375. "All Files (*.*)"
  3376. try:
  3377. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open G-Code",
  3378. directory=self.get_last_folder(), filter=_filter_)
  3379. except TypeError:
  3380. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open G-Code", filter=_filter_)
  3381. # The Qt methods above will return a QString which can cause problems later.
  3382. # So far json.dump() will fail to serialize it.
  3383. # TODO: Improve the serialization methods and remove this fix.
  3384. filename = str(filename)
  3385. if filename == "":
  3386. self.inform.emit("[warning_notcl]Open G-Code cancelled.")
  3387. else:
  3388. self.worker_task.emit({'fcn': self.open_gcode,
  3389. 'params': [filename]})
  3390. def on_file_openproject(self):
  3391. """
  3392. File menu callback for opening a project.
  3393. :return: None
  3394. """
  3395. self.report_usage("on_file_openproject")
  3396. App.log.debug("on_file_openproject()")
  3397. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  3398. try:
  3399. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project",
  3400. directory=self.get_last_folder(), filter=_filter_)
  3401. except TypeError:
  3402. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project", filter = _filter_)
  3403. # The Qt methods above will return a QString which can cause problems later.
  3404. # So far json.dump() will fail to serialize it.
  3405. # TODO: Improve the serialization methods and remove this fix.
  3406. filename = str(filename)
  3407. if filename == "":
  3408. self.inform.emit("[warning_notcl]Open Project cancelled.")
  3409. else:
  3410. # self.worker_task.emit({'fcn': self.open_project,
  3411. # 'params': [filename]})
  3412. # The above was failing because open_project() is not
  3413. # thread safe. The new_project()
  3414. self.open_project(filename)
  3415. def on_file_exportsvg(self):
  3416. """
  3417. Callback for menu item File->Export SVG.
  3418. :return: None
  3419. """
  3420. self.report_usage("on_file_exportsvg")
  3421. App.log.debug("on_file_exportsvg()")
  3422. obj = self.collection.get_active()
  3423. if obj is None:
  3424. self.inform.emit("WARNING: No object selected.")
  3425. msg = "Please Select a Geometry object to export"
  3426. msgbox = QtWidgets.QMessageBox()
  3427. msgbox.setInformativeText(msg)
  3428. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3429. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3430. msgbox.exec_()
  3431. return
  3432. # Check for more compatible types and add as required
  3433. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  3434. and not isinstance(obj, FlatCAMExcellon)):
  3435. msg = "[error_notcl] Only Geometry, Gerber and CNCJob objects can be used."
  3436. msgbox = QtWidgets.QMessageBox()
  3437. msgbox.setInformativeText(msg)
  3438. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3439. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3440. msgbox.exec_()
  3441. return
  3442. name = self.collection.get_active().options["name"]
  3443. filter = "SVG File (*.svg);;All Files (*.*)"
  3444. try:
  3445. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG",
  3446. directory=self.get_last_save_folder(), filter=filter)
  3447. except TypeError:
  3448. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG", filter=filter)
  3449. filename = str(filename)
  3450. if filename == "":
  3451. self.inform.emit("[warning_notcl]Export SVG cancelled.")
  3452. return
  3453. else:
  3454. self.export_svg(name, filename)
  3455. self.file_saved.emit("SVG", filename)
  3456. def on_file_exportpng(self):
  3457. self.report_usage("on_file_exportpng")
  3458. App.log.debug("on_file_exportpng()")
  3459. image = _screenshot()
  3460. data = np.asarray(image)
  3461. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  3462. self.inform.emit('[[warning_notcl]] Data must be a 3D array with last dimension 3 or 4')
  3463. return
  3464. filter = "PNG File (*.png);;All Files (*.*)"
  3465. try:
  3466. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image",
  3467. directory=self.get_last_save_folder(), filter=filter)
  3468. except TypeError:
  3469. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image", filter=filter)
  3470. filename = str(filename)
  3471. if filename == "":
  3472. self.inform.emit("Export PNG cancelled.")
  3473. return
  3474. else:
  3475. write_png(filename, data)
  3476. self.file_saved.emit("png", filename)
  3477. def on_file_exportexcellon(self, altium_format=None):
  3478. """
  3479. Callback for menu item File->Export SVG.
  3480. :return: None
  3481. """
  3482. self.report_usage("on_file_exportexcellon")
  3483. App.log.debug("on_file_exportexcellon()")
  3484. obj = self.collection.get_active()
  3485. if obj is None:
  3486. self.inform.emit("[warning_notcl] No object selected.")
  3487. msg = "Please Select an Excellon object to export"
  3488. msgbox = QtWidgets.QMessageBox()
  3489. msgbox.setInformativeText(msg)
  3490. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3491. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3492. msgbox.exec_()
  3493. return
  3494. # Check for more compatible types and add as required
  3495. if not isinstance(obj, FlatCAMExcellon):
  3496. msg = "[warning_notcl] Only Excellon objects can be used."
  3497. msgbox = QtWidgets.QMessageBox()
  3498. msgbox.setInformativeText(msg)
  3499. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3500. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3501. msgbox.exec_()
  3502. return
  3503. name = self.collection.get_active().options["name"]
  3504. filter = "Excellon File (*.drl);;Excellon File (*.txt);;All Files (*.*)"
  3505. try:
  3506. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon",
  3507. directory=self.get_last_save_folder(), filter=filter)
  3508. except TypeError:
  3509. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon", filter=filter)
  3510. filename = str(filename)
  3511. if filename == "":
  3512. self.inform.emit("[warning_notcl]Export Excellon cancelled.")
  3513. return
  3514. else:
  3515. if altium_format == None:
  3516. self.export_excellon(name, filename)
  3517. self.file_saved.emit("Excellon", filename)
  3518. else:
  3519. self.export_excellon(name, filename, altium_format=True)
  3520. self.file_saved.emit("Excellon", filename)
  3521. def on_file_exportdxf(self):
  3522. """
  3523. Callback for menu item File->Export DXF.
  3524. :return: None
  3525. """
  3526. self.report_usage("on_file_exportdxf")
  3527. App.log.debug("on_file_exportdxf()")
  3528. obj = self.collection.get_active()
  3529. if obj is None:
  3530. self.inform.emit("W[warning_notcl] No object selected.")
  3531. msg = "Please Select a Geometry object to export"
  3532. msgbox = QtWidgets.QMessageBox()
  3533. msgbox.setInformativeText(msg)
  3534. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3535. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3536. msgbox.exec_()
  3537. return
  3538. # Check for more compatible types and add as required
  3539. if not isinstance(obj, FlatCAMGeometry):
  3540. msg = "[error_notcl] Only Geometry objects can be used."
  3541. msgbox = QtWidgets.QMessageBox()
  3542. msgbox.setInformativeText(msg)
  3543. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3544. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3545. msgbox.exec_()
  3546. return
  3547. name = self.collection.get_active().options["name"]
  3548. filter = "DXF File (*.DXF);;All Files (*.*)"
  3549. try:
  3550. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF",
  3551. directory=self.get_last_save_folder(), filter=filter)
  3552. except TypeError:
  3553. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF", filter=filter)
  3554. filename = str(filename)
  3555. if filename == "":
  3556. self.inform.emit("[warning_notcl]Export DXF cancelled.")
  3557. return
  3558. else:
  3559. self.export_dxf(name, filename)
  3560. self.file_saved.emit("DXF", filename)
  3561. def on_file_importsvg(self, type_of_obj):
  3562. """
  3563. Callback for menu item File->Import SVG.
  3564. :param type_of_obj: to import the SVG as Geometry or as Gerber
  3565. :type type_of_obj: str
  3566. :return: None
  3567. """
  3568. self.report_usage("on_file_importsvg")
  3569. App.log.debug("on_file_importsvg()")
  3570. filter = "SVG File (*.svg);;All Files (*.*)"
  3571. try:
  3572. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import SVG",
  3573. directory=self.get_last_folder(), filter=filter)
  3574. except TypeError:
  3575. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import SVG", filter=filter)
  3576. filename = str(filename)
  3577. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  3578. type_of_obj = "geometry"
  3579. if filename == "":
  3580. self.inform.emit("[warning_notcl]Open cancelled.")
  3581. else:
  3582. self.worker_task.emit({'fcn': self.import_svg,
  3583. 'params': [filename, type_of_obj]})
  3584. # self.import_svg(filename, "geometry")
  3585. def on_file_importdxf(self, type_of_obj):
  3586. """
  3587. Callback for menu item File->Import DXF.
  3588. :param type_of_obj: to import the DXF as Geometry or as Gerber
  3589. :type type_of_obj: str
  3590. :return: None
  3591. """
  3592. self.report_usage("on_file_importdxf")
  3593. App.log.debug("on_file_importdxf()")
  3594. filter = "DXF File (*.DXF);;All Files (*.*)"
  3595. try:
  3596. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import DXF",
  3597. directory=self.get_last_folder(), filter=filter)
  3598. except TypeError:
  3599. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import DXF", filter=filter)
  3600. filename = str(filename)
  3601. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  3602. type_of_obj = "geometry"
  3603. if filename == "":
  3604. self.inform.emit("[warning_notcl]Open cancelled.")
  3605. else:
  3606. self.worker_task.emit({'fcn': self.import_dxf,
  3607. 'params': [filename, type_of_obj]})
  3608. def on_filerunscript(self):
  3609. """
  3610. File menu callback for loading and running a TCL script.
  3611. :return: None
  3612. """
  3613. self.report_usage("on_filerunscript")
  3614. App.log.debug("on_file_runscript()")
  3615. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  3616. try:
  3617. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script",
  3618. directory=self.get_last_folder(), filter=_filter_)
  3619. except TypeError:
  3620. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script", filter=_filter_)
  3621. # The Qt methods above will return a QString which can cause problems later.
  3622. # So far json.dump() will fail to serialize it.
  3623. # TODO: Improve the serialization methods and remove this fix.
  3624. filename = str(filename)
  3625. if filename == "":
  3626. self.inform.emit("[warning_notcl]Open TCL script cancelled.")
  3627. else:
  3628. try:
  3629. with open(filename, "r") as tcl_script:
  3630. cmd_line_shellfile_content = tcl_script.read()
  3631. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  3632. except Exception as ext:
  3633. print("ERROR: ", ext)
  3634. sys.exit(2)
  3635. def on_file_saveproject(self):
  3636. """
  3637. Callback for menu item File->Save Project. Saves the project to
  3638. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  3639. if set to None. The project is saved by calling ``self.save_project()``.
  3640. :return: None
  3641. """
  3642. self.report_usage("on_file_saveproject")
  3643. if self.project_filename is None:
  3644. self.on_file_saveprojectas()
  3645. else:
  3646. self.worker_task.emit({'fcn': self.save_project,
  3647. 'params': [self.project_filename]})
  3648. # self.save_project(self.project_filename)
  3649. self.file_opened.emit("project", self.project_filename)
  3650. self.file_saved.emit("project", self.project_filename)
  3651. def on_file_saveprojectas(self, make_copy=False):
  3652. """
  3653. Callback for menu item File->Save Project As... Opens a file
  3654. chooser and saves the project to the given file via
  3655. ``self.save_project()``.
  3656. :return: None
  3657. """
  3658. self.report_usage("on_file_saveprojectas")
  3659. filter = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  3660. try:
  3661. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...",
  3662. directory=self.get_last_save_folder(), filter=filter)
  3663. except TypeError:
  3664. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...", filter=filter)
  3665. filename = str(filename)
  3666. if filename == '':
  3667. self.inform.emit("[warning_notcl]Save Project cancelled.")
  3668. return
  3669. try:
  3670. f = open(filename, 'r')
  3671. f.close()
  3672. exists = True
  3673. except IOError:
  3674. exists = False
  3675. msg = "File exists. Overwrite?"
  3676. if exists:
  3677. msgbox = QtWidgets.QMessageBox()
  3678. msgbox.setInformativeText(msg)
  3679. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel |QtWidgets.QMessageBox.Ok)
  3680. msgbox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
  3681. result = msgbox.exec_()
  3682. if result ==QtWidgets.QMessageBox.Cancel:
  3683. return
  3684. self.worker_task.emit({'fcn': self.save_project,
  3685. 'params': [filename]})
  3686. # self.save_project(filename)
  3687. self.file_opened.emit("project", filename)
  3688. self.file_saved.emit("project", filename)
  3689. if not make_copy:
  3690. self.project_filename = filename
  3691. def export_svg(self, obj_name, filename, scale_factor=0.00):
  3692. """
  3693. Exports a Geometry Object to an SVG file.
  3694. :param filename: Path to the SVG file to save to.
  3695. :return:
  3696. """
  3697. if filename is None:
  3698. filename = self.defaults["global_last_save_folder"]
  3699. self.log.debug("export_svg()")
  3700. try:
  3701. obj = self.collection.get_by_name(str(obj_name))
  3702. except:
  3703. # TODO: The return behavior has not been established... should raise exception?
  3704. return "Could not retrieve object: %s" % obj_name
  3705. with self.proc_container.new("Exporting SVG") as proc:
  3706. exported_svg = obj.export_svg(scale_factor=scale_factor)
  3707. # Determine bounding area for svg export
  3708. bounds = obj.bounds()
  3709. size = obj.size()
  3710. # Convert everything to strings for use in the xml doc
  3711. svgwidth = str(size[0])
  3712. svgheight = str(size[1])
  3713. minx = str(bounds[0])
  3714. miny = str(bounds[1] - size[1])
  3715. uom = obj.units.lower()
  3716. # Add a SVG Header and footer to the svg output from shapely
  3717. # The transform flips the Y Axis so that everything renders
  3718. # properly within svg apps such as inkscape
  3719. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  3720. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  3721. svg_header += 'width="' + svgwidth + uom + '" '
  3722. svg_header += 'height="' + svgheight + uom + '" '
  3723. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  3724. svg_header += '<g transform="scale(1,-1)">'
  3725. svg_footer = '</g> </svg>'
  3726. svg_elem = svg_header + exported_svg + svg_footer
  3727. # Parse the xml through a xml parser just to add line feeds
  3728. # and to make it look more pretty for the output
  3729. svgcode = parse_xml_string(svg_elem)
  3730. with open(filename, 'w') as fp:
  3731. fp.write(svgcode.toprettyxml())
  3732. self.file_saved.emit("SVG", filename)
  3733. self.inform.emit("[success] SVG file exported to " + filename)
  3734. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  3735. """
  3736. Exports a Geometry Object to an SVG file in negative.
  3737. :param filename: Path to the SVG file to save to.
  3738. :param: use_thread: If True use threads
  3739. :type: Bool
  3740. :return:
  3741. """
  3742. if filename is None:
  3743. filename = self.defaults["global_last_save_folder"]
  3744. self.log.debug("export_svg() negative")
  3745. try:
  3746. obj = self.collection.get_by_name(str(obj_name))
  3747. except:
  3748. # TODO: The return behavior has not been established... should raise exception?
  3749. return "Could not retrieve object: %s" % obj_name
  3750. try:
  3751. box = self.collection.get_by_name(str(box_name))
  3752. except:
  3753. # TODO: The return behavior has not been established... should raise exception?
  3754. return "Could not retrieve object: %s" % box_name
  3755. if box is None:
  3756. self.inform.emit("[warning_notcl]No object Box. Using instead %s" % obj)
  3757. box = obj
  3758. def make_negative_film():
  3759. exported_svg = obj.export_svg(scale_factor=scale_factor)
  3760. self.progress.emit(40)
  3761. # Determine bounding area for svg export
  3762. bounds = box.bounds()
  3763. size = box.size()
  3764. uom = obj.units.lower()
  3765. # Convert everything to strings for use in the xml doc
  3766. svgwidth = str(size[0] + (2 * boundary))
  3767. svgheight = str(size[1] + (2 * boundary))
  3768. minx = str(bounds[0] - boundary)
  3769. miny = str(bounds[1] + boundary + size[1])
  3770. miny_rect = str(bounds[1] - boundary)
  3771. # Add a SVG Header and footer to the svg output from shapely
  3772. # The transform flips the Y Axis so that everything renders
  3773. # properly within svg apps such as inkscape
  3774. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  3775. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  3776. svg_header += 'width="' + svgwidth + uom + '" '
  3777. svg_header += 'height="' + svgheight + uom + '" '
  3778. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  3779. svg_header += '>'
  3780. svg_header += '<g transform="scale(1,-1)">'
  3781. svg_footer = '</g> </svg>'
  3782. self.progress.emit(60)
  3783. # Change the attributes of the exported SVG
  3784. # We don't need stroke-width - wrong, we do when we have lines with certain width
  3785. # We set opacity to maximum
  3786. # We set the color to WHITE
  3787. root = ET.fromstring(exported_svg)
  3788. for child in root:
  3789. child.set('fill', '#FFFFFF')
  3790. child.set('opacity', '1.0')
  3791. child.set('stroke', '#FFFFFF')
  3792. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  3793. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  3794. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  3795. first_svg_elem_tag = 'rect'
  3796. first_svg_elem_attribs = {
  3797. 'x': minx,
  3798. 'y': miny_rect,
  3799. 'width': svgwidth,
  3800. 'height': svgheight,
  3801. 'id': 'neg_rect',
  3802. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  3803. }
  3804. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  3805. exported_svg = ET.tostring(root)
  3806. svg_elem = svg_header + str(exported_svg) + svg_footer
  3807. self.progress.emit(80)
  3808. # Parse the xml through a xml parser just to add line feeds
  3809. # and to make it look more pretty for the output
  3810. doc = parse_xml_string(svg_elem)
  3811. with open(filename, 'w') as fp:
  3812. fp.write(doc.toprettyxml())
  3813. self.progress.emit(100)
  3814. self.file_saved.emit("SVG", filename)
  3815. self.inform.emit("[success] SVG file exported to " + filename)
  3816. if use_thread is True:
  3817. proc = self.proc_container.new("Generating Film ... Please wait.")
  3818. def job_thread_film(app_obj):
  3819. try:
  3820. make_negative_film()
  3821. except Exception as e:
  3822. proc.done()
  3823. return
  3824. proc.done()
  3825. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  3826. else:
  3827. make_negative_film()
  3828. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  3829. """
  3830. Exports a Geometry Object to an SVG file in negative.
  3831. :param filename: Path to the SVG file to save to.
  3832. :param: use_thread: If True use threads
  3833. :type: Bool
  3834. :return:
  3835. """
  3836. if filename is None:
  3837. filename = self.defaults["global_last_save_folder"]
  3838. self.log.debug("export_svg() black")
  3839. try:
  3840. obj = self.collection.get_by_name(str(obj_name))
  3841. except:
  3842. # TODO: The return behavior has not been established... should raise exception?
  3843. return "Could not retrieve object: %s" % obj_name
  3844. try:
  3845. box = self.collection.get_by_name(str(box_name))
  3846. except:
  3847. # TODO: The return behavior has not been established... should raise exception?
  3848. return "Could not retrieve object: %s" % box_name
  3849. if box is None:
  3850. self.inform.emit("[warning_notcl]No object Box. Using instead %s" % obj)
  3851. box = obj
  3852. def make_black_film():
  3853. exported_svg = obj.export_svg(scale_factor=scale_factor)
  3854. self.progress.emit(40)
  3855. # Change the attributes of the exported SVG
  3856. # We don't need stroke-width
  3857. # We set opacity to maximum
  3858. # We set the colour to WHITE
  3859. root = ET.fromstring(exported_svg)
  3860. for child in root:
  3861. child.set('fill', '#000000')
  3862. child.set('opacity', '1.0')
  3863. child.set('stroke', '#000000')
  3864. exported_svg = ET.tostring(root)
  3865. # Determine bounding area for svg export
  3866. bounds = box.bounds()
  3867. size = box.size()
  3868. # This contain the measure units
  3869. uom = obj.units.lower()
  3870. # Define a boundary around SVG of about 1.0mm (~39mils)
  3871. if uom in "mm":
  3872. boundary = 1.0
  3873. else:
  3874. boundary = 0.0393701
  3875. self.progress.emit(80)
  3876. # Convert everything to strings for use in the xml doc
  3877. svgwidth = str(size[0] + (2 * boundary))
  3878. svgheight = str(size[1] + (2 * boundary))
  3879. minx = str(bounds[0] - boundary)
  3880. miny = str(bounds[1] + boundary + size[1])
  3881. self.log.debug(minx)
  3882. self.log.debug(miny)
  3883. # Add a SVG Header and footer to the svg output from shapely
  3884. # The transform flips the Y Axis so that everything renders
  3885. # properly within svg apps such as inkscape
  3886. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  3887. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  3888. svg_header += 'width="' + svgwidth + uom + '" '
  3889. svg_header += 'height="' + svgheight + uom + '" '
  3890. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  3891. svg_header += '>'
  3892. svg_header += '<g transform="scale(1,-1)">'
  3893. svg_footer = '</g> </svg>'
  3894. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  3895. self.progress.emit(90)
  3896. # Parse the xml through a xml parser just to add line feeds
  3897. # and to make it look more pretty for the output
  3898. doc = parse_xml_string(svg_elem)
  3899. with open(filename, 'w') as fp:
  3900. fp.write(doc.toprettyxml())
  3901. self.progress.emit(100)
  3902. self.file_saved.emit("SVG", filename)
  3903. self.inform.emit("[success] SVG file exported to " + filename)
  3904. if use_thread is True:
  3905. proc = self.proc_container.new("Generating Film ... Please wait.")
  3906. def job_thread_film(app_obj):
  3907. try:
  3908. make_black_film()
  3909. except Exception as e:
  3910. proc.done()
  3911. return
  3912. proc.done()
  3913. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  3914. else:
  3915. make_black_film()
  3916. def export_excellon(self, obj_name, filename, altium_format=None, use_thread=True):
  3917. """
  3918. Exports a Geometry Object to an Excellon file.
  3919. :param filename: Path to the Excellon file to save to.
  3920. :return:
  3921. """
  3922. if filename is None:
  3923. filename = self.defaults["global_last_save_folder"]
  3924. self.log.debug("export_excellon()")
  3925. format_exc = ';FILE_FORMAT=2:4\n'
  3926. units = ''
  3927. try:
  3928. obj = self.collection.get_by_name(str(obj_name))
  3929. except:
  3930. # TODO: The return behavior has not been established... should raise exception?
  3931. return "Could not retrieve object: %s" % obj_name
  3932. # updated units
  3933. units = self.general_options_form.general_group.units_radio.get_value().upper()
  3934. if units == 'IN' or units == 'INCH':
  3935. units = 'INCH'
  3936. elif units == 'MM' or units == 'METRIC':
  3937. units ='METRIC'
  3938. def make_excellon():
  3939. try:
  3940. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  3941. header = 'M48\n'
  3942. header += ';EXCELLON GENERATED BY FLATCAM - www.flatcam.org 2018\n'
  3943. header += ';Filename: %s' % str(obj_name) + '\n'
  3944. header += ';Created on : %s' % time_str + '\n'
  3945. if altium_format == None:
  3946. has_slots, excellon_code = obj.export_excellon()
  3947. header += units + '\n'
  3948. for tool in obj.tools:
  3949. if units == 'METRIC':
  3950. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.2f' % float(obj.tools[tool]['C']) + '\n'
  3951. else:
  3952. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  3953. else:
  3954. has_slots, excellon_code = obj.export_excellon_altium()
  3955. header += 'INCH,LZ\n'
  3956. header += format_exc
  3957. for tool in obj.tools:
  3958. if units == 'METRIC':
  3959. header += 'T' + str(tool) + 'F00S00' + 'C' + \
  3960. '%.4f' % (float(obj.tools[tool]['C']) / 25.4) + '\n'
  3961. else:
  3962. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  3963. header += '%\n'
  3964. footer = 'M30\n'
  3965. exported_excellon = header
  3966. exported_excellon += excellon_code
  3967. exported_excellon += footer
  3968. with open(filename, 'w') as fp:
  3969. fp.write(exported_excellon)
  3970. self.file_saved.emit("Excellon", filename)
  3971. self.inform.emit("[success] Excellon file exported to " + filename)
  3972. except:
  3973. return 'fail'
  3974. if use_thread is True:
  3975. with self.proc_container.new("Exporting Excellon") as proc:
  3976. def job_thread_exc(app_obj):
  3977. ret = make_excellon()
  3978. if ret == 'fail':
  3979. self.inform.emit('[error_notcl] Could not export Excellon file.')
  3980. return
  3981. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  3982. else:
  3983. ret = make_excellon()
  3984. if ret == 'fail':
  3985. self.inform.emit('[error_notcl] Could not export Excellon file.')
  3986. return
  3987. def export_dxf(self, obj_name, filename, use_thread=True):
  3988. """
  3989. Exports a Geometry Object to an DXF file.
  3990. :param filename: Path to the DXF file to save to.
  3991. :return:
  3992. """
  3993. if filename is None:
  3994. filename = self.defaults["global_last_save_folder"]
  3995. self.log.debug("export_dxf()")
  3996. format_exc = ''
  3997. units = ''
  3998. try:
  3999. obj = self.collection.get_by_name(str(obj_name))
  4000. except:
  4001. # TODO: The return behavior has not been established... should raise exception?
  4002. return "Could not retrieve object: %s" % obj_name
  4003. # updated units
  4004. units = self.general_options_form.general_group.units_radio.get_value().upper()
  4005. if units == 'IN' or units == 'INCH':
  4006. units = 'INCH'
  4007. elif units == 'MM' or units == 'METIRC':
  4008. units ='METRIC'
  4009. def make_dxf():
  4010. try:
  4011. dxf_code = obj.export_dxf()
  4012. dxf_code.saveas(filename)
  4013. self.file_saved.emit("DXF", filename)
  4014. self.inform.emit("[success] DXF file exported to " + filename)
  4015. except:
  4016. return 'fail'
  4017. if use_thread is True:
  4018. with self.proc_container.new("Exporting DXF") as proc:
  4019. def job_thread_exc(app_obj):
  4020. ret = make_dxf()
  4021. if ret == 'fail':
  4022. self.inform.emit('[[warning_notcl]] Could not export DXF file.')
  4023. return
  4024. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4025. else:
  4026. ret = make_dxf()
  4027. if ret == 'fail':
  4028. self.inform.emit('[[warning_notcl]] Could not export DXF file.')
  4029. return
  4030. def import_svg(self, filename, geo_type='geometry', outname=None):
  4031. """
  4032. Adds a new Geometry Object to the projects and populates
  4033. it with shapes extracted from the SVG file.
  4034. :param filename: Path to the SVG file.
  4035. :param outname:
  4036. :return:
  4037. """
  4038. obj_type = ""
  4039. if geo_type is None or geo_type == "geometry":
  4040. obj_type = "geometry"
  4041. elif geo_type == "gerber":
  4042. obj_type = geo_type
  4043. else:
  4044. self.inform.emit("[error_notcl] Not supported type was choosed as parameter. "
  4045. "Only Geometry and Gerber are supported")
  4046. return
  4047. units = self.general_options_form.general_group.units_radio.get_value().upper()
  4048. def obj_init(geo_obj, app_obj):
  4049. geo_obj.import_svg(filename, obj_type, units=units)
  4050. geo_obj.multigeo = False
  4051. with self.proc_container.new("Importing SVG") as proc:
  4052. # Object name
  4053. name = outname or filename.split('/')[-1].split('\\')[-1]
  4054. self.new_object(obj_type, name, obj_init, autoselected=False)
  4055. self.progress.emit(20)
  4056. # Register recent file
  4057. self.file_opened.emit("svg", filename)
  4058. # GUI feedback
  4059. self.inform.emit("[success] Opened: " + filename)
  4060. self.progress.emit(100)
  4061. def import_dxf(self, filename, geo_type='geometry', outname=None):
  4062. """
  4063. Adds a new Geometry Object to the projects and populates
  4064. it with shapes extracted from the DXF file.
  4065. :param filename: Path to the DXF file.
  4066. :param outname:
  4067. :type putname: str
  4068. :return:
  4069. """
  4070. obj_type = ""
  4071. if geo_type is None or geo_type == "geometry":
  4072. obj_type = "geometry"
  4073. elif geo_type == "gerber":
  4074. obj_type = geo_type
  4075. else:
  4076. self.inform.emit("[error_notcl] Not supported type was choosed as parameter. "
  4077. "Only Geometry and Gerber are supported")
  4078. return
  4079. units = self.general_options_form.general_group.units_radio.get_value().upper()
  4080. def obj_init(geo_obj, app_obj):
  4081. geo_obj.import_dxf(filename, obj_type, units=units)
  4082. geo_obj.multigeo = False
  4083. with self.proc_container.new("Importing DXF") as proc:
  4084. # Object name
  4085. name = outname or filename.split('/')[-1].split('\\')[-1]
  4086. self.new_object(obj_type, name, obj_init, autoselected=False)
  4087. self.progress.emit(20)
  4088. # Register recent file
  4089. self.file_opened.emit("dxf", filename)
  4090. # GUI feedback
  4091. self.inform.emit("[success] Opened: " + filename)
  4092. self.progress.emit(100)
  4093. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  4094. """
  4095. Adds a new Geometry Object to the projects and populates
  4096. it with shapes extracted from the SVG file.
  4097. :param filename: Path to the SVG file.
  4098. :param outname:
  4099. :return:
  4100. """
  4101. obj_type = ""
  4102. if type is None or type == "geometry":
  4103. obj_type = "geometry"
  4104. elif type == "gerber":
  4105. obj_type = type
  4106. else:
  4107. self.inform.emit("[error_notcl] Not supported type was picked as parameter. "
  4108. "Only Geometry and Gerber are supported")
  4109. return
  4110. def obj_init(geo_obj, app_obj):
  4111. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  4112. geo_obj.multigeo = False
  4113. with self.proc_container.new("Importing Image") as proc:
  4114. # Object name
  4115. name = outname or filename.split('/')[-1].split('\\')[-1]
  4116. units = self.general_options_form.general_group.units_radio.get_value()
  4117. self.new_object(obj_type, name, obj_init)
  4118. self.progress.emit(20)
  4119. # Register recent file
  4120. self.file_opened.emit("image", filename)
  4121. # GUI feedback
  4122. self.inform.emit("[success] Opened: " + filename)
  4123. self.progress.emit(100)
  4124. def open_gerber(self, filename, follow=False, outname=None):
  4125. """
  4126. Opens a Gerber file, parses it and creates a new object for
  4127. it in the program. Thread-safe.
  4128. :param outname: Name of the resulting object. None causes the
  4129. name to be that of the file.
  4130. :param filename: Gerber file filename
  4131. :type filename: str
  4132. :param follow: If true, the parser will not create polygons, just lines
  4133. following the gerber path.
  4134. :type follow: bool
  4135. :return: None
  4136. """
  4137. # How the object should be initialized
  4138. def obj_init(gerber_obj, app_obj):
  4139. assert isinstance(gerber_obj, FlatCAMGerber), \
  4140. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  4141. # Opening the file happens here
  4142. self.progress.emit(30)
  4143. try:
  4144. gerber_obj.parse_file(filename, follow=follow)
  4145. except IOError:
  4146. app_obj.inform.emit("[error_notcl] Failed to open file: " + filename)
  4147. app_obj.progress.emit(0)
  4148. self.inform.emit('[error_notcl] Failed to open file: ' + filename)
  4149. return "fail"
  4150. except ParseError as err:
  4151. app_obj.inform.emit("[error_notcl] Failed to parse file: " + filename + ". " + str(err))
  4152. app_obj.progress.emit(0)
  4153. self.log.error(str(err))
  4154. return "fail"
  4155. except:
  4156. msg = "[error] An internal error has ocurred. See shell.\n"
  4157. msg += traceback.format_exc()
  4158. app_obj.inform.emit(msg)
  4159. return "fail"
  4160. if gerber_obj.is_empty():
  4161. # app_obj.inform.emit("[error] No geometry found in file: " + filename)
  4162. # self.collection.set_active(gerber_obj.options["name"])
  4163. # self.collection.delete_active()
  4164. self.inform.emit("[error_notcl] Object is not Gerber file or empty. Aborting object creation.")
  4165. return "fail"
  4166. # Further parsing
  4167. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  4168. if follow is False:
  4169. App.log.debug("open_gerber()")
  4170. else:
  4171. App.log.debug("open_gerber() with 'follow' attribute")
  4172. with self.proc_container.new("Opening Gerber") as proc:
  4173. self.progress.emit(10)
  4174. # Object name
  4175. name = outname or filename.split('/')[-1].split('\\')[-1]
  4176. ### Object creation ###
  4177. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  4178. if ret == 'fail':
  4179. self.inform.emit('[error_notcl] Open Gerber failed. Probable not a Gerber file.')
  4180. return
  4181. # Register recent file
  4182. self.file_opened.emit("gerber", filename)
  4183. self.progress.emit(100)
  4184. # GUI feedback
  4185. self.inform.emit("[success] Opened: " + filename)
  4186. def open_excellon(self, filename, outname=None):
  4187. """
  4188. Opens an Excellon file, parses it and creates a new object for
  4189. it in the program. Thread-safe.
  4190. :param outname: Name of the resulting object. None causes the
  4191. name to be that of the file.
  4192. :param filename: Excellon file filename
  4193. :type filename: str
  4194. :return: None
  4195. """
  4196. App.log.debug("open_excellon()")
  4197. #self.progress.emit(10)
  4198. # How the object should be initialized
  4199. def obj_init(excellon_obj, app_obj):
  4200. # self.progress.emit(20)
  4201. try:
  4202. ret = excellon_obj.parse_file(filename)
  4203. if ret == "fail":
  4204. self.inform.emit("[error_notcl] This is not Excellon file.")
  4205. return "fail"
  4206. except IOError:
  4207. app_obj.inform.emit("[error_notcl] Cannot open file: " + filename)
  4208. self.progress.emit(0) # TODO: self and app_bjj mixed
  4209. return "fail"
  4210. except:
  4211. msg = "[error_notcl] An internal error has occurred. See shell.\n"
  4212. msg += traceback.format_exc()
  4213. app_obj.inform.emit(msg)
  4214. return "fail"
  4215. ret = excellon_obj.create_geometry()
  4216. if ret == 'fail':
  4217. return "fail"
  4218. if excellon_obj.is_empty():
  4219. app_obj.inform.emit("[error_notcl] No geometry found in file: " + filename)
  4220. return "fail"
  4221. with self.proc_container.new("Opening Excellon."):
  4222. # Object name
  4223. name = outname or filename.split('/')[-1].split('\\')[-1]
  4224. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  4225. if ret == 'fail':
  4226. self.inform.emit('[error_notcl] Open Excellon file failed. Probable not an Excellon file.')
  4227. return
  4228. # Register recent file
  4229. self.file_opened.emit("excellon", filename)
  4230. # GUI feedback
  4231. self.inform.emit("[success] Opened: " + filename)
  4232. # self.progress.emit(100)
  4233. def open_gcode(self, filename, outname=None):
  4234. """
  4235. Opens a G-gcode file, parses it and creates a new object for
  4236. it in the program. Thread-safe.
  4237. :param outname: Name of the resulting object. None causes the
  4238. name to be that of the file.
  4239. :param filename: G-code file filename
  4240. :type filename: str
  4241. :return: None
  4242. """
  4243. App.log.debug("open_gcode()")
  4244. # How the object should be initialized
  4245. def obj_init(job_obj, app_obj_):
  4246. """
  4247. :type app_obj_: App
  4248. """
  4249. assert isinstance(app_obj_, App), \
  4250. "Initializer expected App, got %s" % type(app_obj_)
  4251. self.progress.emit(10)
  4252. try:
  4253. f = open(filename)
  4254. gcode = f.read()
  4255. f.close()
  4256. except IOError:
  4257. app_obj_.inform.emit("[error_notcl] Failed to open " + filename)
  4258. self.progress.emit(0)
  4259. return "fail"
  4260. job_obj.gcode = gcode
  4261. self.progress.emit(20)
  4262. ret = job_obj.gcode_parse()
  4263. if ret == "fail":
  4264. self.inform.emit("[error_notcl] This is not GCODE")
  4265. return "fail"
  4266. self.progress.emit(60)
  4267. job_obj.create_geometry()
  4268. with self.proc_container.new("Opening G-Code."):
  4269. # Object name
  4270. name = outname or filename.split('/')[-1].split('\\')[-1]
  4271. # New object creation and file processing
  4272. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  4273. if ret == 'fail':
  4274. self.inform.emit("[error_notcl] Failed to create CNCJob Object. Probable not a GCode file.\n "
  4275. "Attempting to create a FlatCAM CNCJob Object from "
  4276. "G-Code file failed during processing")
  4277. return "fail"
  4278. # Register recent file
  4279. self.file_opened.emit("cncjob", filename)
  4280. # GUI feedback
  4281. self.inform.emit("[success] Opened: " + filename)
  4282. self.progress.emit(100)
  4283. def open_project(self, filename, run_from_arg=None):
  4284. """
  4285. Loads a project from the specified file.
  4286. 1) Loads and parses file
  4287. 2) Registers the file as recently opened.
  4288. 3) Calls on_file_new()
  4289. 4) Updates options
  4290. 5) Calls new_object() with the object's from_dict() as init method.
  4291. 6) Calls plot_all()
  4292. :param filename: Name of the file from which to load.
  4293. :type filename: str
  4294. :return: None
  4295. """
  4296. App.log.debug("Opening project: " + filename)
  4297. # Open and parse
  4298. try:
  4299. f = open(filename, 'r')
  4300. except IOError:
  4301. App.log.error("Failed to open project file: %s" % filename)
  4302. self.inform.emit("[error_notcl] Failed to open project file: %s" % filename)
  4303. return
  4304. try:
  4305. d = json.load(f, object_hook=dict2obj)
  4306. except:
  4307. App.log.error("Failed to parse project file: %s" % filename)
  4308. self.inform.emit("[error_notcl] Failed to parse project file: %s" % filename)
  4309. f.close()
  4310. return
  4311. self.file_opened.emit("project", filename)
  4312. # Clear the current project
  4313. ## NOT THREAD SAFE ##
  4314. if run_from_arg is True:
  4315. pass
  4316. else:
  4317. self.on_file_new()
  4318. #Project options
  4319. self.options.update(d['options'])
  4320. self.project_filename = filename
  4321. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4322. self.set_screen_units(self.options["units"])
  4323. # Re create objects
  4324. App.log.debug("Re-creating objects...")
  4325. for obj in d['objs']:
  4326. def obj_init(obj_inst, app_inst):
  4327. obj_inst.from_dict(obj)
  4328. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  4329. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  4330. # self.plot_all()
  4331. self.inform.emit("[success] Project loaded from: " + filename)
  4332. App.log.debug("Project loaded")
  4333. def propagate_defaults(self, silent=False):
  4334. """
  4335. This method is used to set default values in classes. It's
  4336. an alternative to project options but allows the use
  4337. of values invisible to the user.
  4338. :return: None
  4339. """
  4340. if silent is False:
  4341. self.log.debug("propagate_defaults()")
  4342. # Which objects to update the given parameters.
  4343. routes = {
  4344. "global_zdownrate": CNCjob,
  4345. "excellon_zeros": Excellon,
  4346. "excellon_format_upper_in": Excellon,
  4347. "excellon_format_lower_in": Excellon,
  4348. "excellon_format_upper_mm": Excellon,
  4349. "excellon_format_lower_mm": Excellon,
  4350. "excellon_units": Excellon,
  4351. "gerber_use_buffer_for_union": Gerber,
  4352. "geometry_multidepth": Geometry
  4353. }
  4354. for param in routes:
  4355. if param in routes[param].defaults:
  4356. try:
  4357. routes[param].defaults[param] = self.defaults[param]
  4358. if silent is False:
  4359. self.log.debug(" " + param + " OK")
  4360. except KeyError:
  4361. if silent is False:
  4362. self.log.debug(" ERROR: " + param + " not in defaults.")
  4363. else:
  4364. # Try extracting the name:
  4365. # classname_param here is param in the object
  4366. if param.find(routes[param].__name__.lower() + "_") == 0:
  4367. p = param[len(routes[param].__name__) + 1:]
  4368. if p in routes[param].defaults:
  4369. routes[param].defaults[p] = self.defaults[param]
  4370. if silent is False:
  4371. self.log.debug(" " + param + " OK!")
  4372. def restore_main_win_geom(self):
  4373. try:
  4374. self.ui.setGeometry(self.defaults["global_def_win_x"],
  4375. self.defaults["global_def_win_y"],
  4376. self.defaults["global_def_win_w"],
  4377. self.defaults["global_def_win_h"])
  4378. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  4379. except KeyError:
  4380. pass
  4381. def plot_all(self):
  4382. """
  4383. Re-generates all plots from all objects.
  4384. :return: None
  4385. """
  4386. self.log.debug("Plot_all()")
  4387. for obj in self.collection.get_list():
  4388. def worker_task(obj):
  4389. with self.proc_container.new("Plotting"):
  4390. obj.plot()
  4391. self.object_plotted.emit(obj)
  4392. # Send to worker
  4393. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  4394. # self.progress.emit(10)
  4395. #
  4396. # def worker_task(app_obj):
  4397. # print "worker task"
  4398. # percentage = 0.1
  4399. # try:
  4400. # delta = 0.9 / len(self.collection.get_list())
  4401. # except ZeroDivisionError:
  4402. # self.progress.emit(0)
  4403. # return
  4404. # for obj in self.collection.get_list():
  4405. # with self.proc_container.new("Plotting"):
  4406. # obj.plot()
  4407. # app_obj.object_plotted.emit(obj)
  4408. #
  4409. # percentage += delta
  4410. # self.progress.emit(int(percentage*100))
  4411. #
  4412. # self.progress.emit(0)
  4413. # self.plots_updated.emit()
  4414. #
  4415. # # Send to worker
  4416. # #self.worker.add_task(worker_task, [self])
  4417. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  4418. def register_folder(self, filename):
  4419. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  4420. def register_save_folder(self, filename):
  4421. self.defaults['global_last_save_folder'] = os.path.split(str(filename))[0]
  4422. def set_progress_bar(self, percentage, text=""):
  4423. self.ui.progress_bar.setValue(int(percentage))
  4424. def setup_shell(self):
  4425. """
  4426. Creates shell functions. Runs once at startup.
  4427. :return: None
  4428. """
  4429. self.log.debug("setup_shell()")
  4430. def shelp(p=None):
  4431. if not p:
  4432. return "Available commands:\n" + \
  4433. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  4434. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  4435. if p not in commands:
  4436. return "Unknown command: %s" % p
  4437. return commands[p]["help"]
  4438. # --- Migrated to new architecture ---
  4439. # def options(name):
  4440. # ops = self.collection.get_by_name(str(name)).options
  4441. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  4442. def h(*args):
  4443. """
  4444. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  4445. and standalone parameters into list.
  4446. """
  4447. kwa = {}
  4448. a = []
  4449. n = len(args)
  4450. name = None
  4451. for i in range(n):
  4452. match = re.search(r'^-([a-zA-Z].*)', args[i])
  4453. if match:
  4454. assert name is None
  4455. name = match.group(1)
  4456. continue
  4457. if name is None:
  4458. a.append(args[i])
  4459. else:
  4460. kwa[name] = args[i]
  4461. name = None
  4462. return a, kwa
  4463. @contextmanager
  4464. def wait_signal(signal, timeout=10000):
  4465. """
  4466. Block loop until signal emitted, timeout (ms) elapses
  4467. or unhandled exception happens in a thread.
  4468. :param signal: Signal to wait for.
  4469. """
  4470. loop = QtCore.QEventLoop()
  4471. # Normal termination
  4472. signal.connect(loop.quit)
  4473. # Termination by exception in thread
  4474. self.thread_exception.connect(loop.quit)
  4475. status = {'timed_out': False}
  4476. def report_quit():
  4477. status['timed_out'] = True
  4478. loop.quit()
  4479. yield
  4480. # Temporarily change how exceptions are managed.
  4481. oeh = sys.excepthook
  4482. ex = []
  4483. def except_hook(type_, value, traceback_):
  4484. ex.append(value)
  4485. oeh(type_, value, traceback_)
  4486. sys.excepthook = except_hook
  4487. # Terminate on timeout
  4488. if timeout is not None:
  4489. QtCore.QTimer.singleShot(timeout, report_quit)
  4490. #### Block ####
  4491. loop.exec_()
  4492. # Restore exception management
  4493. sys.excepthook = oeh
  4494. if ex:
  4495. self.raiseTclError(str(ex[0]))
  4496. if status['timed_out']:
  4497. raise Exception('Timed out!')
  4498. def make_docs():
  4499. output = ''
  4500. import collections
  4501. od = collections.OrderedDict(sorted(commands.items()))
  4502. for cmd_, val in od.items():
  4503. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  4504. t = val['help']
  4505. usage_i = t.find('>')
  4506. if usage_i < 0:
  4507. expl = t
  4508. output += expl + '\n\n'
  4509. continue
  4510. expl = t[:usage_i - 1]
  4511. output += expl + '\n\n'
  4512. end_usage_i = t[usage_i:].find('\n')
  4513. if end_usage_i < 0:
  4514. end_usage_i = len(t[usage_i:])
  4515. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  4516. else:
  4517. extras = t[usage_i+end_usage_i+1:]
  4518. parts = [s.strip() for s in extras.split('\n')]
  4519. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  4520. for p in parts:
  4521. output += ' ' + p + '\n\n'
  4522. return output
  4523. '''
  4524. Howto implement TCL shell commands:
  4525. All parameters passed to command should be possible to set as None and test it afterwards.
  4526. This is because we need to see error caused in tcl,
  4527. if None value as default parameter is not allowed TCL will return empty error.
  4528. Use:
  4529. def mycommand(name=None,...):
  4530. Test it like this:
  4531. if name is None:
  4532. self.raise_tcl_error('Argument name is missing.')
  4533. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  4534. otherwise we will miss it and processing will silently continue.
  4535. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  4536. which is catched in exec_command and displayed in TCL shell console with red background.
  4537. Error in console is displayed with TCL trace.
  4538. This behavior works only within main thread,
  4539. errors with promissed tasks can be catched and detected only with log.
  4540. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  4541. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  4542. '''
  4543. commands = {
  4544. 'help': {
  4545. 'fcn': shelp,
  4546. 'help': "Shows list of commands."
  4547. },
  4548. }
  4549. # Import/overwrite tcl commands as objects of TclCommand descendants
  4550. # This modifies the variable 'commands'.
  4551. tclCommands.register_all_commands(self, commands)
  4552. # Add commands to the tcl interpreter
  4553. for cmd in commands:
  4554. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  4555. # Make the tcl puts function return instead of print to stdout
  4556. self.tcl.eval('''
  4557. rename puts original_puts
  4558. proc puts {args} {
  4559. if {[llength $args] == 1} {
  4560. return "[lindex $args 0]"
  4561. } else {
  4562. eval original_puts $args
  4563. }
  4564. }
  4565. ''')
  4566. def setup_recent_items(self):
  4567. # TODO: Move this to constructor
  4568. icons = {
  4569. "gerber": "share/flatcam_icon16.png",
  4570. "excellon": "share/drill16.png",
  4571. "cncjob": "share/cnc16.png",
  4572. "project": "share/project16.png",
  4573. "svg": "share/geometry16.png",
  4574. "dxf": "share/dxf16.png",
  4575. "image": "share/image16.png"
  4576. }
  4577. openers = {
  4578. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  4579. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  4580. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  4581. 'project': self.open_project,
  4582. 'svg': self.import_svg,
  4583. 'dxf': self.import_dxf,
  4584. 'image': self.import_image
  4585. }
  4586. # Open file
  4587. try:
  4588. f = open(self.data_path + '/recent.json')
  4589. except IOError:
  4590. App.log.error("Failed to load recent item list.")
  4591. self.inform.emit("[error_notcl] Failed to load recent item list.")
  4592. return
  4593. try:
  4594. self.recent = json.load(f)
  4595. except json.scanner.JSONDecodeError:
  4596. App.log.error("Failed to parse recent item list.")
  4597. self.inform.emit("[error_notcl] Failed to parse recent item list.")
  4598. f.close()
  4599. return
  4600. f.close()
  4601. # Closure needed to create callbacks in a loop.
  4602. # Otherwise late binding occurs.
  4603. def make_callback(func, fname):
  4604. def opener():
  4605. func(fname)
  4606. return opener
  4607. def reset_recent():
  4608. # Reset menu
  4609. self.ui.recent.clear()
  4610. self.recent = []
  4611. try:
  4612. f = open(self.data_path + '/recent.json', 'w')
  4613. except IOError:
  4614. App.log.error("Failed to open recent items file for writing.")
  4615. return
  4616. json.dump(self.recent, f)
  4617. # Reset menu
  4618. self.ui.recent.clear()
  4619. # Create menu items
  4620. for recent in self.recent:
  4621. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  4622. try:
  4623. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  4624. # Attach callback
  4625. o = make_callback(openers[recent["kind"]], recent['filename'])
  4626. action.triggered.connect(o)
  4627. self.ui.recent.addAction(action)
  4628. except KeyError:
  4629. App.log.error("Unsupported file type: %s" % recent["kind"])
  4630. # Last action in Recent Files menu is one that Clear the content
  4631. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  4632. clear_action.triggered.connect(reset_recent)
  4633. self.ui.recent.addSeparator()
  4634. self.ui.recent.addAction(clear_action)
  4635. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  4636. # self.ui.menufilerecent.set_submenu(recent_menu)
  4637. # recent_menu.show_all()
  4638. # self.ui.recent.show()
  4639. self.log.debug("Recent items list has been populated.")
  4640. def setup_component_editor(self):
  4641. label = QtWidgets.QLabel("Choose an item from Project")
  4642. label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  4643. self.ui.selected_scroll_area.setWidget(label)
  4644. def setup_obj_classes(self):
  4645. """
  4646. Sets up application specifics on the FlatCAMObj class.
  4647. :return: None
  4648. """
  4649. FlatCAMObj.app = self
  4650. ObjectCollection.app = self
  4651. FCProcess.app = self
  4652. FCProcessContainer.app = self
  4653. def version_check(self):
  4654. """
  4655. Checks for the latest version of the program. Alerts the
  4656. user if theirs is outdated. This method is meant to be run
  4657. in a separate thread.
  4658. :return: None
  4659. """
  4660. self.log.debug("version_check()")
  4661. full_url = App.version_url + \
  4662. "?s=" + str(self.defaults['global_serial']) + \
  4663. "&v=" + str(self.version) + \
  4664. "&os=" + str(self.os) + \
  4665. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  4666. App.log.debug("Checking for updates @ %s" % full_url)
  4667. ### Get the data
  4668. try:
  4669. f = urllib.request.urlopen(full_url)
  4670. except:
  4671. # App.log.warning("Failed checking for latest version. Could not connect.")
  4672. self.log.warning("Failed checking for latest version. Could not connect.")
  4673. self.inform.emit("[warning_notcl] Failed checking for latest version. Could not connect.")
  4674. return
  4675. try:
  4676. data = json.load(f)
  4677. except Exception as e:
  4678. App.log.error("Could not parse information about latest version.")
  4679. self.inform.emit("[error_notcl] Could not parse information about latest version.")
  4680. App.log.debug("json.load(): %s" % str(e))
  4681. f.close()
  4682. return
  4683. f.close()
  4684. ### Latest version?
  4685. if self.version >= data["version"]:
  4686. App.log.debug("FlatCAM is up to date!")
  4687. self.inform.emit("[success] FlatCAM is up to date!")
  4688. return
  4689. App.log.debug("Newer version available.")
  4690. self.message.emit(
  4691. "Newer Version Available",
  4692. str("There is a newer version of FlatCAM " +
  4693. "available for download:<br><br>" +
  4694. "<B>" + data["name"] + "</b><br>" +
  4695. data["message"].replace("\n", "<br>")),
  4696. "info"
  4697. )
  4698. def enable_plots(self, objects):
  4699. def worker_task(app_obj):
  4700. percentage = 0.1
  4701. try:
  4702. delta = 0.9 / len(objects)
  4703. except ZeroDivisionError:
  4704. self.progress.emit(0)
  4705. return
  4706. for obj in objects:
  4707. obj.options['plot'] = True
  4708. percentage += delta
  4709. self.progress.emit(int(percentage*100))
  4710. self.progress.emit(0)
  4711. self.plots_updated.emit()
  4712. self.collection.update_view()
  4713. # Send to worker
  4714. # self.worker.add_task(worker_task, [self])
  4715. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  4716. def disable_plots(self, objects):
  4717. # TODO: This method is very similar to replot_all. Try to merge.
  4718. """
  4719. Disables plots
  4720. :param objects: list
  4721. Objects to be disabled
  4722. :return:
  4723. """
  4724. self.progress.emit(10)
  4725. def worker_task(app_obj):
  4726. percentage = 0.1
  4727. try:
  4728. delta = 0.9 / len(objects)
  4729. except ZeroDivisionError:
  4730. self.progress.emit(0)
  4731. return
  4732. for obj in objects:
  4733. obj.options['plot'] = False
  4734. percentage += delta
  4735. self.progress.emit(int(percentage*100))
  4736. self.progress.emit(0)
  4737. self.plots_updated.emit()
  4738. self.collection.update_view()
  4739. # Send to worker
  4740. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  4741. def clear_plots(self):
  4742. objects = self.collection.get_list()
  4743. for obj in objects:
  4744. obj.clear(obj == objects[-1])
  4745. # Clear pool to free memory
  4746. self.clear_pool()
  4747. def generate_cnc_job(self, objects):
  4748. for obj in objects:
  4749. obj.generatecncjob()
  4750. def save_project(self, filename):
  4751. """
  4752. Saves the current project to the specified file.
  4753. :param filename: Name of the file in which to save.
  4754. :type filename: str
  4755. :return: None
  4756. """
  4757. self.log.debug("save_project()")
  4758. with self.proc_container.new("Saving FlatCAM Project") as proc:
  4759. ## Capture the latest changes
  4760. # Current object
  4761. try:
  4762. self.collection.get_active().read_form()
  4763. except:
  4764. self.log.debug("[warning] There was no active object")
  4765. pass
  4766. # Project options
  4767. self.options_read_form()
  4768. # Serialize the whole project
  4769. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  4770. "options": self.options,
  4771. "version": self.version}
  4772. # Open file
  4773. try:
  4774. f = open(filename, 'w')
  4775. except IOError:
  4776. App.log.error("[error] Failed to open file for saving: %s", filename)
  4777. return
  4778. # Write
  4779. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  4780. f.close()
  4781. # verification of the saved project
  4782. # Open and parse
  4783. try:
  4784. saved_f = open(filename, 'r')
  4785. except IOError:
  4786. self.inform.emit("[error_notcl] Failed to verify project file: %s. Retry to save it." % filename)
  4787. return
  4788. try:
  4789. saved_d = json.load(saved_f, object_hook=dict2obj)
  4790. except:
  4791. self.inform.emit("[error_notcl] Failed to parse saved project file: %s. Retry to save it." % filename)
  4792. f.close()
  4793. return
  4794. saved_f.close()
  4795. if 'version' in saved_d:
  4796. self.inform.emit("[success] Project saved to: %s" % filename)
  4797. else:
  4798. self.inform.emit("[error_notcl] Failed to save project file: %s. Retry to save it." % filename)
  4799. def on_options_app2project(self):
  4800. """
  4801. Callback for Options->Transfer Options->App=>Project. Copies options
  4802. from application defaults to project defaults.
  4803. :return: None
  4804. """
  4805. self.report_usage("on_options_app2project")
  4806. self.defaults_read_form()
  4807. self.options.update(self.defaults)
  4808. self.options_write_form()
  4809. def on_options_project2app(self):
  4810. """
  4811. Callback for Options->Transfer Options->Project=>App. Copies options
  4812. from project defaults to application defaults.
  4813. :return: None
  4814. """
  4815. self.report_usage("on_options_project2app")
  4816. self.options_read_form()
  4817. self.defaults.update(self.options)
  4818. self.defaults_write_form()
  4819. def on_options_project2object(self):
  4820. """
  4821. Callback for Options->Transfer Options->Project=>Object. Copies options
  4822. from project defaults to the currently selected object.
  4823. :return: None
  4824. """
  4825. self.report_usage("on_options_project2object")
  4826. self.options_read_form()
  4827. obj = self.collection.get_active()
  4828. if obj is None:
  4829. self.inform.emit("WARNING: No object selected.")
  4830. return
  4831. for option in self.options:
  4832. if option.find(obj.kind + "_") == 0:
  4833. oname = option[len(obj.kind) + 1:]
  4834. obj.options[oname] = self.options[option]
  4835. obj.to_form() # Update UI
  4836. def on_options_object2project(self):
  4837. """
  4838. Callback for Options->Transfer Options->Object=>Project. Copies options
  4839. from the currently selected object to project defaults.
  4840. :return: None
  4841. """
  4842. self.report_usage("on_options_object2project")
  4843. obj = self.collection.get_active()
  4844. if obj is None:
  4845. self.inform.emit("WARNING: No object selected.")
  4846. return
  4847. obj.read_form()
  4848. for option in obj.options:
  4849. if option in ['name']: # TODO: Handle this better...
  4850. continue
  4851. self.options[obj.kind + "_" + option] = obj.options[option]
  4852. self.options_write_form()
  4853. def on_options_object2app(self):
  4854. """
  4855. Callback for Options->Transfer Options->Object=>App. Copies options
  4856. from the currently selected object to application defaults.
  4857. :return: None
  4858. """
  4859. self.report_usage("on_options_object2app")
  4860. obj = self.collection.get_active()
  4861. if obj is None:
  4862. self.inform.emit("WARNING: No object selected.")
  4863. return
  4864. obj.read_form()
  4865. for option in obj.options:
  4866. if option in ['name']: # TODO: Handle this better...
  4867. continue
  4868. self.defaults[obj.kind + "_" + option] = obj.options[option]
  4869. self.defaults_write_form()
  4870. def on_options_app2object(self):
  4871. """
  4872. Callback for Options->Transfer Options->App=>Object. Copies options
  4873. from application defaults to the currently selected object.
  4874. :return: None
  4875. """
  4876. self.report_usage("on_options_app2object")
  4877. self.defaults_read_form()
  4878. obj = self.collection.get_active()
  4879. if obj is None:
  4880. self.inform.emit("WARNING: No object selected.")
  4881. return
  4882. for option in self.defaults:
  4883. if option.find(obj.kind + "_") == 0:
  4884. oname = option[len(obj.kind) + 1:]
  4885. obj.options[oname] = self.defaults[option]
  4886. obj.to_form() # Update UI
  4887. # end of file