FlatCAMApp.py 264 KB

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