FlatCAMApp.py 277 KB

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