FlatCAMApp.py 297 KB

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