FlatCAMApp.py 323 KB

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