FlatCAMApp.py 259 KB

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