FlatCAMApp.py 285 KB

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