FlatCAMApp.py 324 KB

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