FlatCAMApp.py 322 KB

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