FlatCAMApp.py 328 KB

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