FlatCAMApp.py 300 KB

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