FlatCAMApp.py 357 KB

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