FlatCAMApp.py 296 KB

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