FlatCAMApp.py 323 KB

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